Organize Cloud Functions for Firebase

两盒软妹~` 提交于 2019-12-03 22:27:25

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

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

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.

This structure was inspired by inspecting the internals of the firebase-functions npm package.

Pablo Marconi

You could use something like export { functionName } from './file' at your index.js file.

/functions/index.js
// This is the main entry point for the app written in ES that is compatible with node lts
import * as functions from 'firebase-functions';

export { sendWelcomeEmail } from './userEmails';

exports.helloWorld = functions.https.onRequest((request, response) => {
  let helloMsg = `Hello!`;
  response.send(helloMsg);
});

This is a great question and something I have recently been looking for. I found this great strategy from Tarik Huber: Organizing your Firebase Cloud Functions. It's his take on his own thoughts and a few other contributors in this area.

He organizes his functions based on their usage and type (i.e. trigger, Http, etc) into a folder structure. The index.js code iterates thorugh the structure and imports the functions in a very structured and succinct way. It not only allows the developers to simply add new functions in a well understood structure but they don't have to manually manipulate the index.js file, and it deploys the function names in Firebase according to the structure as well.

Definitely check it out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!