How to have internal shared functions in Firebase Cloud function project?

96 Views Asked by At

In order to organize my project, I have decided to spread my cloud functions into multiple files, following this documentation : https://firebase.google.com/docs/functions/organize-functions?gen=1st#write_functions_in_multiple_files

It works good, but now I would like to have shared internal functions in order to avoid code duplication.

Here is what I tried:

I have created a sharedFunctions.js file at the root level containing some test functions like:

function sayHello1(){
 
    console.log('Hello world1');
  
}

function sayHello2(){
 
    console.log('Hello world2');
  
}

And a testSharedFunction.js file containing:

const functions = require('firebase-functions');
const sharedFunc = require('./sharedFunctions');

// firebase deploy --only functions:testSharedFunction
exports.testSharedFunction = functions.https.onRequest((request, response) => {
    sharedFunc.sayHello1();
    return true;
 });

But when I tried to deploy my testSharedFunction function for testing it, I get this error: Error: Error parsing triggers: Cannot find module './sharedFunctions

Do you have and idea of what could be wrong , or how I can succeed to achieved having those internal shared functions ?

Thank you for your help, Benjamin

1

There are 1 best solutions below

1
Rohit Kharche On

You are not exporting the sayHello1() and sayHello2() functions from the sharedFunctions.js which is why you are getting this error. Updated code will be :

sharedFunctions.js :

exports.sayHello1 = function() {
  console.log("Hello world1");
};

exports.sayHello2 = function() {
  console.log("Hello world2");
};

And importing those in main file as follows :

testSharedFunction.js :

const functions = require('firebase-functions');
const sharedFunc = require('./sharedFunctions');

// firebase deploy --only functions:testSharedFunction
exports.testSharedFunction = functions.https.onRequest((request, response) => {
    sharedFunc.sayHello1();
    sharedFunc.sayHello2();
    return true;
 });

You were using CommonJS-style module exports in Node.js. but you should give a try to ES6 modules imports which will simplify as following : sharedFunctions.js :

export function sayHello1() {
  console.log("Hello world1");
}

export function sayHello2() {
  console.log("Hello world2");
}

And importing will become :

testSharedFunction.js :

// following import is used with typescript
import * as functions from "firebase-functions";
import { sayHello1, sayHello2 } from "./sharedFunctions";

export const helloWorld = functions.https.onRequest((request, response) => {
  sayHello1();
  sayHello2();
  response.send(true);
})