Cloud Functions for Organizing Firebase

I know that this has already been asked here , but this does not answer my question. My question is how can we break index.js for cloud functions, including onWrite calls, etc.

I understand that you can use "require" and enter external code. It still leaves some code (for example, in the OCR Franks example) in index.js.

Ideally, I would like to transfer the entire trigger of the onWrite event to another file.

EXAMPLE in index.js:

exports.sysQueueUserNew = functions.database.ref("/sys/queue/user_new/{queueId}").onWrite((event) => { // do something }) 

How can I move the entire view / call of a function event to another js file and call it from index.js?

My index.js got pretty big, and reading it for organizational purposes became PAIN.

Ideally, I would like my index.js to be very organized, for example:

 --in index.js -- /// User cleanup userHelpers() /// SYS Logs sysLogs() --and in userHelpers.js have the onWrite trigger for example--- functions.database.ref("/sys/queue/user_new/{queueId}").onWrite((event) => { // create user }) 

etc....

Is this possible without having the code written like this (a la franks OCR example):

 var test = require('./test') exports.sysQueueUserNew = functions.database.ref("/sys/queue/user_new/{queueId}").onWrite((event) => { // do something test.doCleanup() }) 

Thanks in advance....

+5
source share
2 answers

You can easily distribute your functions in multiple files. Here is an example:

 ////////////// index.js exports.sysQueueUserNew = require('./sys-queue-user-new'); exports.userCleanup = require('./user-cleanup'); ///////////// sys-queue-user-new.js const functions = require('firebase-functions'); module.exports = functions.database .ref("/sys/queue/user_new/{queueId}") .onWrite(e => { // do something }); ///////////// user-cleanup.js const functions = require('firebase-functions'); module.exports = functions.auth.user().onDelete(e => { // do something }); 
+7
source

As an answer to Michael, I found this organization very neat and peculiar object oriented.

 // index.js const admin = require('firebase-admin') admin.initializeApp(functions.config().firebase) const user = require('./user')(admin) exports.sendWelcomeEmail = user.sendWelcomeEmail // user.js const functions = require('firebase-functions') module.exports = function(admin) { let sendWelcomeEmail = functions.auth.user().onCreate(event => { // return admin.database().ref().update({}) }) return { sendWelcomeEmail: sendWelcomeEmail } } 
+6
source

Source: https://habr.com/ru/post/1266603/


All Articles