Kan*_*ong 5 cold-start express firebase google-cloud-platform google-cloud-functions
我试图弄清楚如何优化我的 firebase 功能的冷启动时间。读完这篇文章后,我想尝试一下,但我意识到这篇文章专门针对 http onRequest 函数的基本用法,并且没有给出使用express的示例。
这里出现了类似的问题,但似乎没有明确的答案。我看到文章的作者 Doug 实际上评论了这个问题,他提到为应用程序中的每个路由创建动态导入,因为 onRequest() 只允许将应用程序作为其唯一参数传递,但我不明白到底是什么他的意思是除了使用基本 API 而不使用 Express 应用程序之外。理想情况下,我能够使用express,这样我就可以更好地控制api url路径并使用express提供的一些实用程序。
谁能给我一个如何在 Doug 的例子中使用express的例子?即使我必须为每条路线定义一个新的快速应用程序,我也同意。只是不知道如何以这种方式配置它。
编辑:需要明确的是,目标是优化所有函数调用的冷启动,而不仅仅是 http 路由的调用。根据我的理解,Doug 的示例消除了使用使用 onRequest 声明的单个路由预加载的导入,但它没有显示通过 Express 定义路由时如何实现这一点。
假设您拆分出的每个路由器都在其自己的文件中定义,如下所示:
// $FUNCTIONS_DIR/routes/some-route-handler.js
import express from "express";
const router = express.Router();
/* ... define routes ... */
export default router;
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用此中间件仅在需要时加载每个路由处理程序模块。
function lazyRouterModule(modulePath) {
return async (req, res, next) {
let router;
try {
router = (await import(modulePath)).default;
} catch (err) {
// error loading module, let next() handle it
next(err);
return;
}
router(req, res, next);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的子功能文件中,您将使用该中间件来创建 Express 应用程序并连接路线。
// $FUNCTIONS_DIR/fn/my-express.js
import express from "express";
const app = express();
app.use('/api', lazyRouterModule('./routes/api.js'));
app.use('/profiles', lazyRouterModule('./routes/profiles.js'));
export default app;
Run Code Online (Sandbox Code Playgroud)
然后在主函数文件中,您可以按需连接子函数文件:
// $FUNCTIONS_DIR/index.js
import * as functions from 'firebase-functions'
export const myExpress = functions.https
.onRequest(async (request, response) => {
await (await import('./fn/my-express.js')).default(request, response)
});
export const newUserData = functions.firestore.document('/users/{userId}')
.onCreate(async (snap, context) => {
await (await import('./fn/new-user-data.js')).default(snap, context)
});
Run Code Online (Sandbox Code Playgroud)
当像这样延迟加载模块时,您将需要firebase-admin从公共文件延迟加载,这样您就不会最终调用initializeApp()多次。
// $FUNCTIONS_DIR/common/firebase-admin.js
import * as admin from "firebase-admin";
admin.initializeApp();
export = admin;
Run Code Online (Sandbox Code Playgroud)
在任何想要使用 的函数中"firebase-admin",您可以使用以下命令从此处导入它:
// $FUNCTIONS_DIR/fn/some-function.js OR $FUNCTIONS_DIR/routes/some-route-handler.js
import * as admin from "../common/firebase-admin";
// use admin as normal, it's already initialized
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1063 次 |
| 最近记录: |