4

How can we implement Micro-service architecture using Firebase Cloud Functions can we write multiple .js files unlike writing all functions into index.js so that we need not re-deploy all functions for change in single function

Mahi Tej Gvp
  • 984
  • 1
  • 14
  • 34

3 Answers3

8

I'm importing other .js files with firebase functions. Just think of the functions folder as root, I was mistakenly trying to import files from /functions parent folder.

index.js

var paymentFunctions = require('./payment_functions');

along with something like:

exports.paymentMethodTask = functions.database.ref('/newPaymentMethodTask/{taskId}').onWrite(event => {
    return paymentFunctions.processPaymentMethodTask(event);
});

With the folder structure:

/myProject/functions/index.js
/myProject/functions/payment_functions.js

Then export your functions in payment_functions.js as normal:

module.exports = {
    processPaymentMethodTask: function test(event) {
        //do something here with the event
    }
};

https://medium.com/step-up-labs/our-experience-with-cloud-functions-for-firebase-d206448a8850

viral 9966
  • 515
  • 5
  • 16
6

All your Cloud Functions for Firebase will have to be defined in the index.js file. But that doesn't mean you have to implement all functionality in a single file.

I often implement the bulk of each function in a separate file. For example, if I'm using the Google Cloud Vision API to extra text from images, I'll have an ocr.js. I give this file a main section, so that I can run the script from a local terminal using node ocr.js. Then in my index.js I need little more code than an import of ocr.js and wiring that up to Cloud Functions.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Hi you can do this in the following way.

alpha.js

const functions = require('firebase-functions');
exports.alphaFunction = functions.https.onRequest((request, response) => {
   // Your code
});

index.js

const functions = require('firebase-functions');
var alphaFunction = require('./alpha');
exports.mainFunction = functions.https.onRequest((request, response) => {
    //Inside your main function
    exports.alphaFunction = alphaFunction.alphaFunction();
});
srijan439
  • 401
  • 5
  • 7