在一行/函数中将中间件添加到所有firebase函数 [英] Add middleware to all firebase functions in one line / function
问题描述
在 express
中,您可以添加诸如 app.use(cors())
之类的中间件,该中间件会将其添加到所有端点,但是我找不到类似的东西在Firebase示例中.这是示例(请参见下文)将其应用到所有功能中.但是,由于我有很多功能,因此我想全局地 应用中间件(cors或其他).
In express
you can add middleware such as app.use(cors())
which adds it to all of the endpoints, however I can't find something similar in firebase examples. Here is the example (see below) of how to apply it in every function. However I want to apply the middleware (cors or other) globally, as I have many functions.
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const exampleFunction= functions.https.onRequest(async (request, response) => {
corsHandler(request, response, () => { return handler(req, res) });
});
firebase中的 app.use()
等效项是什么?是添加并表达服务器 仅选项?
What is the equivalent of app.use()
in firebase? Is adding and express server the only option?
推荐答案
使用currying 创建处理程序,您必须在所有函数中重复该处理程序,但是比每次编写中间件都要容易:
Use currying to create a handler, you have to repeat it across all the functions, but it's easier than writing the middleware each time:
const applyMiddleware = handler => (req, res) => {
return cors(req, res, () => {
return handler(req, res)
})
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))
这篇关于在一行/函数中将中间件添加到所有firebase函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!