I am using Firebase cloud functions (node.js) for my app and I want to create a shared wrapper for all of my endpoints that will handle errors and have some checks.
Is it possible to create a wrapper function for the cloud functions and then expose it as a new endpoint?
Example:
// normal function that works
const helloWorld = functions.https.onRequest((req, res) => {
functions.logger.log("hello world!");
return res.end();
})
// the wrapper function that handles errors and shared logic
const functionsWrapper = async ({allowedMethods, handler}) =>
functions.https.onRequest(async (req, res) => {
try {
if (allowedMethods) {
if (!allowedMethods.includes(req.method.toLowerCase())) {
return res.status(405).end();
}
}
const result = await handler;
return res.json(result);
} catch (error) {
//handling errors here
}
}
);
// the function I want to wrap and then expose as an endpoint
const anotherFunc = functionsWrapper({
allowedMethods: ['get'],
async handler() {
return {message: 'I am inside functionsWrapper'}
}
})
// exposing the functions
module.exports = {
helloWorld, // helloWorld can be called and gets an endpoint
anotherFunc // anotherFunc does not get an endpoint
}
I think that Firebase finds where functions.https.onRequest is being exported and then exposes it as an endpoint but how can I expose 'anotherFunc'?
Or in short how to expose:
const endpoint = () => functions.htpps.onRequest((req, res) => {})
Thanks!