Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Function import function from other file - javascript

I am building firebase function with javascript. Now i have a lot of inter-call function and i plan to move those function into different file to avoid index.js become very messy.

So below is the current file structure:

/functions
   |--index.js
   |--internalFunctions.js
   |--package.json
   |--package-lock.json
   |--.eslintrc.json

I want to know:

1) How to export the function from internalFunctions.js and import it to index.js.

2) How to call internalFunctions.js function from index.js.

My code is written in JavaScript.

Edited

internalFunction.js will have multiple functions.

like image 238
Jerry Avatar asked May 09 '18 02:05

Jerry


1 Answers

First you set the function in your file:

internalFunctions.js:

module.exports = {
    HelloWorld: function test(event) {
        console.log('hello world!');
    }
};

Or if you dont like a lot messing with curly braces:

module.exports.HelloWorld = function(event) {
    console.log('hello world!');
}

module.exports.AnotherFunction = function(event) {
    console.log('hello from another!');
}

There are also other styles you can use: https://gist.github.com/kimmobrunfeldt/10848413

Then in your index.js file import the file as a module:

const ifunctions = require('./internalFunctions');

And then you can call it directly within your triggers or HTTP handlers:

ifunctions.HelloWorld();

Example:

//Code to load modules 
//...
const ifunctions = require('./internalFunctions');

exports.myTrigger = functions.database.ref('/myNode/{id}')
    .onWrite((change, context) => {

      //Some of your code...        

      ifunctions.HelloWorld();

      //A bit more of code...

});
like image 64
AarónBC. Avatar answered Nov 07 '22 12:11

AarónBC.