Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Setting up an API call through firebase firestore functions

Hey there! I'm building an application and we're working with a team to integrate their API so custom events are triggered and sent to their database. We're trying to use firebase functions but keep running into issues with error saying "X is not a function"

I'm attempting to send an event for when a user is created and when a user's signedUp property changes to TRUE

Here is my code

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const axios = require("axios");
const crypto = require("crypto");

admin.initializeApp();

const clientId = "409d72d8-3849-44aa-874f-57ed7773644a";
const clientSecret = "XQ5FC7wJTpLnWc3wUCRAukaiL8L7oHUq";
const gameId = "5bd512c4-4f39-4081-8362-5f21ffd60788";

const generateSignature = (body, timestamp) => {
  const message = `${clientId}${timestamp}${JSON.stringify(body)}`;
  return crypto.createHmac("sha256", clientSecret)
      .update(message)
      .digest("hex");
};

exports.onUserCreate = functions.firestore.document("users/{userId}")
    .onCreate(async (snap, context) => {
      const newUser = snap.data();
      const timestamp = Date.now();
      const body = {
        gameId: gameId,
        identifiers: [
          {
            userId: context.params.userId,
            email: newUser.email,
          // Add other identifiers as needed
          },
        ],
      };

      const signature = generateSignature(body, timestamp);

      try {
        await axios.post("https://events.earnalliance.com/v2/custom-events", body, {
          headers: {
            "x-client-id": clientId,
            "x-timestamp": timestamp,
            "x-signature": signature,
            "Content-Type": "application/json",
          },
        });
        console.log("User created event sent successfully");
      } catch (error) {
        console.error("Error sending user created event:", error);
      }
    });

exports.onUserSignUpChange = functions.firestore.document("users/{userId}")
    .onUpdate(async (change, context) => {
      const before = change.before.data();
      const after = change.after.data();

      if (before.signedUp !== after.signedUp && after.signedUp === true) {
        const timestamp = Date.now();
        const body = {
          gameId: gameId,
          identifiers: [
            {
              userId: context.params.userId,
              email: after.email,
            // Add other identifiers as needed
            },
          ],
        };

        const signature = generateSignature(body, timestamp);

        try {
          await axios.post("https://events.earnalliance.com/v2/custom-events", body, {
            headers: {
              "x-client-id": clientId,
              "x-timestamp": timestamp,
              "x-signature": signature,
              "Content-Type": "application/json",
            },
          });
          console.log("User signed up event sent successfully");
        } catch (error) {
          console.error("Error sending user signed up event:", error);
        }
      }
    });

Here are the docs - https://docs.earnalliance.com/
any guidance would be much appreciated!
0 1 613
1 REPLY 1

Hi @NewGameJay,

Welcome to Google Cloud community!

I understand that you're implementing a function that's triggered by an event when a user signs up, but to narrow things down, let's focus first on the nature of your Cloud Firestore function code.

You mentioned that you had an error similar to "X is not a function". Could this actually be something similar to TypeError: functions.firestore.document(...).onCreate is not a function ? If so, errors like that could indicate that either the function event type is unrecognizable or even if it is, the written function code doesn’t align with the latest changes applied in the latest version of ‘firebase-functions’. Otherwise, it would be best if you can provide the exact error message raised during the deployment failure.

As a first approach, ensure that you're using the latest Firebase CLI and ‘firebase-functions’ versions.

I verified in your code that you're using a document.onCreate event for a Cloud Firestore trigger, but it appears that this is for 1st gen. It's still supported to use the 1st gen, but make sure to change your import statement from

const functions = require("firebase-functions");

to

const functions = require('firebase-functions/v1');

This recommendation has also been covered in a similar GitHub post.

Firebase Cloud Run functions currently has 2nd gen support, and it's recommended for developers to migrate from v1 to v2 as much as possible. In your case, this might be the opportunity for you to migrate your functions.firestore.document(...).onCreate function to its version 2 counterpart. For more information, you can also check the complete migration guideline.

I hope the above information is helpful.

Top Solution Authors