mtoninelli
mtoninelli

Reputation: 714

call a function from firebase cloud function

Probably it's a simple question, but I can't understand how to do it. I would like to call a function from another function in Firebase Cloud Functions.

exports.firstFunction = functions.https.onCall((params, context) => {
  return new Promise((resolve, reject) => {
    return secondFunction()  // how can I call secondFunction?
      .then((resp) => resolve(resp))
      .catch((e) => reject(e));
  });
});

exports.secondFunction = functions.https.onCall((params, context) => {
  return new Promise((resolve, reject) => {
    return resolve("secondFunction");
  });
});

Making httpCallable("secondFunction") return the correct string. If I do httpCallable("firstFunction") I have an [Error: INTERNAL].

How can I do this?

Upvotes: 1

Views: 183

Answers (1)

Stratubas
Stratubas

Reputation: 3067

Take a look:

exports.firstFunction = functions.https.onCall((params, context) => {
  return new Promise((resolve, reject) => {
    return secondFunctionHandler()
      .then((resp) => resolve(resp))
      .catch((e) => reject(e));
  });
});

const secondFunctionHandler = (params, context) => {
  return new Promise((resolve, reject) => {
    return resolve("secondFunction");
  });
};

exports.secondFunction = functions.https.onCall(secondFunctionHandler);

I like separating all my cloud functions into "handlers" (written in separate files and then imported) and single lines in the index file, not only the ones I want to reuse. It find it makes the code more readable and manageable.

Upvotes: 2

Related Questions