Declare separate Firebase Cloud Functions and still use Express.js

后端 未结 3 1563
天涯浪人
天涯浪人 2020-12-28 10:36

There are many examples of using Express for Firebase Cloud Functions.

In every example of I have found the code exposes the Express app as a single Cloud Function:<

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 11:13

    Interesting discussion.

    I choose the same approach : one "endpoint" (aka a root route like "/posts", "/users") == a dedicated cloud function (for the reason already evoked + it's more "µservice like" and it's what are "lambda functions" for me).

    To be "DRY" all my function import an "express" generator. I configure my express instance in one place.

    const express = () => {
      const express = require("express");
      const cors = require("cors")({ origin: true });
      const morgan = require("morgan");
      const helmet = require("helmet");
    
      const app = express();
    
      app.use(helmet());
      app.use(helmet.noCache());
      app.use(cors);
      app.use(morgan("combined"));
    
      return app;
    };
    
    module.exports = express;
    

    My "hello" endpoint :

    const app = require("./../../express")();
    
    /**
     * /hello
     */
    
    app.get("/", (req, res) => {
      return res.send("Hello World");
    });
    
    module.exports = app;
    

    My index.js (main export) :

    const helloApi = require("./api/hello");
    
    const https = functions.region("europe-west1").https;
    
    module.exports.hello = https.onRequest(helloApi);
    

    Seems to work well for us :)

提交回复
热议问题