How do I selectively insert records from Firebase ➡️ Algolia?

Hi,

I’m currently using Firebase + Algolia. So far it’s working great.

When a record is added to Firebase the Algolia extension is called. The Algolia extension calls a separate Cloud Function to do some data transformation.

Now my question.

How do I selectively send records to Algolia from the Firebase extension?

Specifically, I only want to index if there is a specific JSON key present.

I was thinking I can do it in the transform function but it’s not obvious how.

Here’s my transform code, it’s based off the example on the Algolia website.

const transformRecipe = (payload: any) => {
  return {
    "recipe_title": payload["recipe"]["data"]["bookmark"]["title"],
    "recipe_description": payload["recipe"]["data"]["bookmark"]["description"],
    "recipe_url": payload["recipe"]["data"]["bookmark"]["url"],
    "recipe_image_url": payload["recipe"]["data"]["bookmark"]["image"],
    "recipe_site_name": payload["recipe"]["data"]["bookmark"]["site_name"],
    ...payload,
  };
};

export const transformRecipeForSearch = functions.https.onCall((payload) => {
  const transformedData = transformRecipe(payload);
  return transformedData;
});

Hello!

Glad to hear it is working great. If you want a certain record (or recipe in your case) to not be indexed, I would recommend returning an error if the field is missing. This will stop the request to Algolia’s servers and keep the record only within Firestore.

Here’s an example:

import * as functions from "firebase-functions";

const transformRecipe = (payload: any) => {
  if (!Object.keys(payload).includes("recipe")) {
    throw new functions.https.HttpsError("invalid-argument", "Invalid recipe");
  }

  return {
    "recipe_title": payload["recipe"]["data"]["bookmark"]["title"],
    "recipe_description": payload["recipe"]["data"]["bookmark"]["description"],
    "recipe_url": payload["recipe"]["data"]["bookmark"]["url"],
    "recipe_image_url": payload["recipe"]["data"]["bookmark"]["image"],
    "recipe_site_name": payload["recipe"]["data"]["bookmark"]["site_name"],
    ...payload,
  };
};

I’ll double-check and see if anyone on the team knows a better method, but this does seem like the best way to handle it and also won’t generate any extra errors on Algolia’s side. Here’s some more information on handling errors within the callable functions.