Organize Cloud Functions for Firebase

2019-04-03 08:50发布

What is the best practice to organize all our Cloud Functions for Firebase?

I see from the sample GitHub repository that all functions reside in a single index.js file.

I guess for bigger project that there is a better approach to organize Cloud Functions for Firebase in different files/directory.

2条回答
老娘就宠你
2楼-- · 2019-04-03 09:18

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.

查看更多
欢心
3楼-- · 2019-04-03 09:31

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);
});
查看更多
登录 后发表回答