Solutions: Cloud Functions
Integrate Firesearch into your stack using Cloud Functions for Firebase.
This guide explains how to integrate Firesearch into the platform stack to automate index creation for users, to generate access keys, and to automatically maintain your search indexes when data changes.
- The code examples on this page show how you might automate the search experience for a blog service
- Functions are written in TypeScript
- The Firesearch TypeScript client code is deployed alongside the functions in a file called
firesearch.ts
You will learn how to:
Synchronize Firestore documents
When data in Firestore changes, you may want to automatically update the Firesearch index.
You can do this using the onWrite
handler:
- We import the Firesearch SDK and create a
Client
andIndexService
- This function will run whenever a document that matches
firestorePath
changes - If the document was deleted (
!change.after.exists
) we useindexService.deleteDoc
to delete the document from the search index - If the document was added or updated, we use
change.after.data()
to get the data and update the search index viaindexService.putDoc
Create an index per user
You may decide to silo search data for each of your users by creating an index whenever a new user signs into your app.
If you are using Firebase Authentication you can write a Cloud Function that uses the Firesearch client libs or SDKs to create an index when a user is created:
- We import the Firesearch SDK and create a
Client
andIndexService
- We use
functions.auth.user().onCreate
to add a function that runs whenever a new user is created - The
indexPath
incorporates theuser.uid
, which allows us to safely generate access keys that will provide access only to this user's search data - Using
indexService.createIndex
we create a new index
Generate user-specific access keys
If data is organized by user (i.e. if the user's ID is part of the index path), you can write a Cloud Function to get an access key without leaking your API key to the front-end.
We can use functions.https.onCall
to create a callable function:
- First we must check that the user is authenticated (since we're using Firebase Authentication, we use
context.auth?.uid
) - If there is no user, it's important that this call fails—so we throw a
functions.https.HttpsError
- We generate an
indexPathPrefix
based on the path of the user's search index(es) - We use the
accessKeyService.generateKey
and return the key from this callable function