cbdeveloper
cbdeveloper

Reputation: 31315

How to terminate a Firebase callable function that does not need to return anything?

This example:

A function to increment a VIEWCOUNT collection.

No need to return anything. Also there's no need to await for the firestore...update() call.

export const onCall_updateViewCount = functions.https.onCall((data, context) => {

  const { id } = data;
  const VIEWCOUNT = COLLECTIONS.VIEWCOUNT;

  admin.firestore().collection(VIEWCOUNT).doc(VIEWCOUNT).update({
    [id]: admin.firestore.FieldValue.increment(1)
  });

  return;
});

What is the proper way to terminate this function? Is it fine to end with void return?

Is the void return; necessary? Will it continue running until timeout if I don't return anything? Like it does on onRequest functions?

Upvotes: 1

Views: 595

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317322

Your function must return a promise that resolves when all the async work is complete. You can't return early - you must wait for the completion, otherwise Cloud Functions might forcibly shut down the function, and it will never complete.

For callable functions in particular, you must also return a promise that resolves with the data to serialize to the client app. It's better to be specific about this than try to serialize the result of some unknown promise results.

export const onCall_updateViewCount = functions.https.onCall((data, context) => {

  const { id } = data;
  const VIEWCOUNT = COLLECTIONS.VIEWCOUNT;

  return admin.firestore().collection(VIEWCOUNT).doc(VIEWCOUNT).update({
    [id]: admin.firestore.FieldValue.increment(1)
  })
  .then(() => {
    return { result: "OK" };
  });
});

Be sure to review the documentation for callable functions.

Upvotes: 5

Related Questions