📦 SwiftyLaunch Modules
⚙️ BackendKit
DBKit Integration

DatabaseKit Integration in BackendKit

DBKit Integration

Access your Firebase Firestore database data using DBKit.

Basic Usage

Import Firestore

To access your Database in your backend functions, you first need to include the getFirestore function in your file.

import { getFirestore } from "firebase-admin/firestore";

Usage Example

Here's a usage example from AIKit's AI Chatbot example, that fetches all of user's chat messages from Firestore.

index.ts
// Get AI Chat Messages of the user that is currently logged in
export const retrieveCurrentUsersAIChatMessages = onCall(async (request) => {
  const fromUid = request.auth?.uid; // See AuthKit Integration
 
  if (!fromUid) {
    // ...
    throw new Error("User Not Logged In");
  }
 
  try {
    let messages = await getAIChatHistoryOfUserWithID(fromUid);
 
    // ...
 
    // get data from database. path:
    // "users" -> USER_ID -> "AIChatMessages" -> AUTO_ID -> {isFromUser: BOOL, messageContent: STRING, timestamp: TIMESTAMP}
    const snapshot = await getFirestore()
      .collection("users")
      .doc(user)
      .collection("AIChatMessages")
      .orderBy("timestamp", "asc") // we want the newest to be last
      .get();
 
    // define data structure that will be sent to the client
    let messages: {
      id: string; //id in database
      isFromUser: boolean; // true if from user, false if from GPT
      messageContent: string; // the actual message
      timestamp: string; // when the message was sent (ISO STRING)
    }[] = [];
 
    // go through each snapshot, and append the correct data to the messages array
    snapshot.forEach((doc) => {
      const data = doc.data();
      messages.push({
        id: doc.id,
        isFromUser: data.isFromUser,
        messageContent: data.messageContent,
        timestamp: data.timestamp.toDate().toISOString(),
      });
    });
 
    // ...
 
    return messages;
  } catch (error) {
    // ...
    throw new Error("Server Error");
  }
});

You can also perform many other operations, such as adding, updating, and deleting data from Firestore. For more information, see the Firestore documentation (opens in a new tab).