Functions-samples: Writing Multiple Functions

Created on 30 Apr 2018  Â·  10Comments  Â·  Source: firebase/functions-samples

I understand cloud functions were recently updated to 1.0. I saw the original post here and also created my own SO post, I am trying to understand how to create multiple cloud functions as I plan on having 5 - 10 in total and do not want to include all in my index.js:

I understand Cloud Functions recently updated to v1.0.

I am trying to write multiple functions from within Android Studio. I plan on having several cloud functions, and want to ensure my data structure is correct. Here is the current setup I have:

enter image description here

index.js

const functions = require('firebase-functions');
const trackVote = require('./trackVote')
const trendingCopy = require('./trendingCopy')
const admin = require('firebase-admin');
admin.initializeApp();



exports.trackVote = functions.firestore.document('Polls/{pollId}/responses/{userId}').onCreate(trackVoteModule.handler);
exports.trendingCopy = functions.firestore.document('Polls').onCreate(trendingCopyModule.handler);

trackVote:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.handler = (change, context => {

       const data = change.after.data();
       const answerSelected = data.answer;

       const answerRef = admin.firestore().doc(`Polls/${event.params.pollId}/answers/${answerSelected}`);
       const voteCountRef = admin.firestore.doc(`Polls/${event.params.pollId}/vote_count`);

        return admin.firestore().runTransaction(t => {
                    return t.get(answerRef)
                        .then(doc => {
                            if (doc.data()) {
                                t.update(answerRef, { vote_count: doc.data().vote_count + 1 });
                            }
                        })
                };
          //TODO DO NOT ADD TO GIT
         return admin.firestore().runTransaction(t => {
            return t.get(voteCountRef)
                .then(doc =>){
                    if (doc.data()){
                        t.update(voteCountRef, {vote_count:doc.data().vote_count+1});
                    }
                }
         });

});

    });

Below is my console:

Error: functions predeploy error: Command terminated with non-zero exit code1

EDIT: I have seen this as a proposed solution, however it provides multiple options and unsure of best practice: https://github.com/firebase/functions-samples/issues/170

Most helpful comment

@cdock1029 we took your suggestion and added a new page on this topic:
https://firebase.google.com/docs/functions/organize-functions

In our opinion something like better-firebase-functions is premature optimization in most cases, although there's nothing wrong with using it!

All 10 comments

i just want some help,,,actually i just want to push a notification to two different modules in same app like notification for attendance node and notification for Result node …but i cant understand how to do this plz help me if anyone know how to do this…….Thank u :)

i just want some help,,,actually i just want to push a notification to two different modules in same app like notification for attendance node and notification for Result node …but i cant understand how to do this plz help me if anyone know how to do this…….Thank u :)

@troy21688 as you noticed, the correct thing to do is define your functions in other files and then just re-export them in index.js. That's the correct pattern. And you also pointed out that there's great discussion on this in #170, so going to close this.

@samtstern why isn't this solved by Firebase team? Instead we have to filter through that thread of 50 different versions of the same idea every time we want to create more than a toy project with 5 or more functions. It seems completely in line with Firebase incentives of wanting people to use their product effectively (and in volume) to handle this in official way (to benefit cold start times especially), no?

At the very least shouldn't it be documented...somewhere?

Perhaps a reference to this:

https://github.com/gramstr/better-firebase-functions

@cdock1029 just to confirm are you asking for some documentation on firebase.google.com that shows how to organize functions code into more than one file?

Yes..apologize for tone and sounding so whiny, just that it seems to me to be important to do this, for every application that has multiple functions. Otherwise we are increasing cold start time loading all code for each function instance correct? Certainly organization becomes difficult beyond some number of functions as well.

So yes documentation and direction as to which one of many implementations is recommended, or why this should be considered for new users.

Perhaps even (mirroring better-firebase-functions approach) something in the library:

// entrypoint index.ts
import * as functions from 'firebase-functions'
functions.exportCloudFunctions(__dirname, __filename, exports, './', './**/*.js')

@cdock1029 we took your suggestion and added a new page on this topic:
https://firebase.google.com/docs/functions/organize-functions

In our opinion something like better-firebase-functions is premature optimization in most cases, although there's nothing wrong with using it!

Great, looks good!

Any ballpark figure on number of functions beyond which loading all of them effects cold starts? Just wondering if the team had measured this...

@cdock1029 you can check out this article for some benchmarks but I want to point out that there are two optimizations in better-firebase-functions:

  1. Instead of globally loading all your dependencies and variables, only load them as needed within your functions.
  2. Instead of globally loading all of your function entrypoints, use the GCLOUD_FUNCTION environment variable to decide at runtime which one you need to execute and only evaluate that code.

(1) can be a big help because dependencies can be very large, this is something you can do yourself without anything as complex as better-firebase-functions. You just move your import or require statements into the function body.

(2) only matters if your codebase, excluding dependencies, is so big that even evaluating the surface of your JS code is expensive. It's extremely unlikely that this is your bottleneck, you'd probably need tens of thousands of lines of JS to even notice the benefit of optimizing for this.

OK that makes sense..I think what ultimately motivates some to dynamically load specific functions is it accomplishes (1) by itself, avoiding dynamic imports (requires lose typo info I'm thinking?) and initialization code in the functions, and having to write all function imports into your main entry file. Small win, but maybe it's mostly a matter of DX vs actual performance.

I'll try the way you suggest.. probably a misplaced concern just cause I'm not used to working with dynamic imports in node.
Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

artcab picture artcab  Â·  4Comments

6vedant picture 6vedant  Â·  5Comments

IchordeDionysos picture IchordeDionysos  Â·  3Comments

rodrigosol picture rodrigosol  Â·  3Comments

Rovel picture Rovel  Â·  5Comments