Lou*_*uis 1 firebase google-cloud-functions
我正在尝试改善我的 firebase 云功能的冷启动时间。正如 firebase 团队所建议的那样,可能不需要的依赖项可以放在函数本身中,以便仅在需要时加载它。但这与我已经将函数拆分为单个文件的情况有何关系?我在那里导入的依赖项是否仅在调用函数时自动加载?
这正是我在这篇博文中提到的情况。
基本策略是在函数本身内部使用异步导入(对于 TypeScript)或 JavaScript 要求,以便将每个函数的脚本文件的加载推迟到执行。这可以防止为所有函数加载一个函数的依赖项。
下面是几个函数在 TypeScript 中的样子:
import * as functions from 'firebase-functions'
export const httpFn =
functions.https.onRequest(async (request, response) => {
// Move the implementation of this function to fn/httFn.ts
await (await import('./fn/httpFn')).default(request, response)
})
export const firestoreFn =
functions.firestore.document("users/{id}")
.onCreate(async (snapshot, context) => {
// Move the implementation of this function to fn/firestoreFn.ts
await (await import('./fn/firestoreFn')).default(snapshot, context)
})
Run Code Online (Sandbox Code Playgroud)
然后,对于 HTTP 函数,中的实现fn/httpFn.ts如下所示:
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
admin.initializeApp()
// Note: Need to be explicit about parameter types here for HTTP
// type functions, to support type safety and IDE assistance.
export default async (
request: functions.https.Request,
response: functions.Response
) => {
// Here we can use the admin SDK to get a document
const snapshot = await admin.firestore()
.collection('users')
.doc('uid')
.get()
const data = snapshot.data()
response.send(data)
}
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 中,策略是相同的。您只需使用 arequire而不是await import。
| 归档时间: |
|
| 查看次数: |
529 次 |
| 最近记录: |