问题描述
组织所有 Cloud Functions for Firebase 的最佳做法是什么?
What is the best practice to organize all our Cloud Functions for Firebase?
我从 示例 GitHub 存储库 中看到,所有函数都驻留在一个 中index.js
文件.
I see from the sample GitHub repository that all functions reside in a single index.js
file.
我猜对于更大的项目,有更好的方法可以在不同的文件/目录中组织 Cloud Functions for Firebase.
I guess for bigger project that there is a better approach to organize Cloud Functions for Firebase in different files/directory.
推荐答案
我在一个名为 triggers
的文件夹中按提供程序和资源组织我的事件处理程序.例如.其中 auth
是提供者,user
是资源;functions/triggers/auth/user
文件夹包含一个 onCreate.js
和 onDelete.js
,分别欢迎和清理用户.
I organize my event handlers by provider and resource in a folder called triggers
. E.g. where auth
is the provider and user
is the resource; the folder functions/triggers/auth/user
contains an onCreate.js
and onDelete.js
, which welcomes and cleans up a user respectively.
+--/auth
| +--/user
| +--/onCreate.js
| +--/onDelete.js
+--/database
+--/storage
您可以使用 require
函数导出特定触发器:
You can export a particular trigger by using the require
function:
exports.onCreateAuthUser = require('./triggers/auth/user/onCreate');
exports.onDeleteAuthUser = require('./triggers/auth/user/onDelete');
我更进一步,创建了一个自动为我导出函数的脚本.我将文件的扩展名更改为 f.js
并递归搜索触发器目录.对于找到的每个文件,通过分解目录和文件路径来炮制函数名称.
I went a step further and created a script that automatically exports the functions for me. I change the extension of the files to f.js
and search recursively the triggers directory. For each file found, the function name is concocted by breaking down the directory and file path.
这个结构的灵感来自于检查 firebase-functions
npm 包的内部结构.
This structure was inspired by inspecting the internals of the firebase-functions
npm package.
这篇关于为 Firebase 组织云函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!