将中间件添加到一行/函数中的所有 firebase 函数 [英] Add middleware to all firebase functions in one line / function

查看:27
本文介绍了将中间件添加到一行/函数中的所有 firebase 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

使用柯里化来创建处理程序,你必须在所有函数中重复它,但它比每次编写中间件更容易:

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))

编辑,更复杂的中间件示例:

const applyMiddleware =
  (handler, { authenticatedRoute = false } = {}) =>
  (req, res) => {
    if (authenticatedRoute) {
      const isAuthorized = isAuthenticated(req)
      if (!isAuthorized) {
        return res.status(401).send('Unauthorized')
      }
    }
    return cors(req, res, () => {
      return handler(req, res)
    })
  }
exports.handler = functions.https.onRequest(
   applyMiddleware(handler, { authenticatedRoute: true })
)

这篇关于将中间件添加到一行/函数中的所有 firebase 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆