iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐷

Connecting to a Non-Default Firestore Database from Cloud Run Functions (Node.js)

に公開
2

Normally, when connecting to Google Cloud Firestore, the default database is used. However, in cases where you want to handle multiple databases, you will need to access a non-default database.

This article documents the steps to connect to a non-default Firestore database from a Cloud Run function. In short, it only requires specifying the database name from the SDK. The conclusive code is provided below.

import { Firestore } from "@google-cloud/firestore";

const db = new Firestore({
  databaseId: "rss-manager",
});

With this, the db instance will be pointed to the rss-manager database instead of the default one.

Background of the struggle: Google Cloud SDK vs. Firebase Admin SDK

The solution is quite simple, but it took some time to get there. To use Firestore from a Node.js Cloud Run function, using an SDK is easy. The problem is that there are two main types of SDKs.

Package Name Type of SDK Overview
firebase-admin Firebase Admin SDK Library for Firebase server-side applications
@google-cloud/firestore Google Cloud SDK General Google Cloud library

Since both Cloud Run functions and Firestore can be used with Firebase, a Google search often yields methods using firebase-admin. However, I couldn't figure out how to access a non-default database with firebase-admin.

@google-cloud/firestore is an alternative method, and for me, who doesn't usually use Firebase, this approach was easier and helpful.

Registering RSS feed URLs from a Cloud Run function

Since we're at it, let's go through a sample implementation. We will implement an API that can register RSS feed URLs to Firestore from a Cloud Run function.

Create a Firestore database

Create a database named rss-manager.

Cloud Run function

I will implement it in TypeScript and then convert it to Node.js. Import Firestore from '@google-cloud/firestore'; and create a DB client with new Firestore(). At this time, by specifying databaseId: 'rss-manager' as an option, you can access the database created earlier.

index.ts
import type { Request, Response } from 'express';
import { Firestore } from '@google-cloud/firestore';

const db = new Firestore({
  databaseId: 'rss-manager',
});

// Firestore collection name
const COLLECTION_NAME = 'rss-feeds';

// HTTP function to register RSS feed URLs in Firestore
export const rssRegister = async (req: Request, res: Response) => {
  const rssUrl = req.body.url;

  if (!rssUrl) {
    res.status(400).send('RSS URL is required.');
    return;
  }

  try {
    // Save RSS URL to Firestore
    await db.collection(COLLECTION_NAME).add({
      url: rssUrl,
      lastCheckedGuid: null, // Set to null initially to detect all new articles
    });
    res.status(200).send(`RSS URL added: ${rssUrl}`);
  } catch (error) {
    console.error('Error adding RSS URL:', error);
    res.status(500).send('Failed to add RSS URL.');
  }

Let's deploy it. Note that this assumes the default service account has access to Firestore.

gcloud functions deploy rssRegister \
--region=asia-northeast1 \
--runtime=nodejs20 \
--memory=256 \
--timeout=30s \
--source=. \
--trigger-http \
--project=my-project-name \
--entry-point=rssRegister \
--allow-unauthenticated

Let's try registering a URL from the test tab of the deployed Cloud Run function.

Confirm that it has been registered in Firestore.

We were able to register data into a non-default Firestore database from a Cloud Run function.

Conclusion

We registered an RSS feed URL to a non-default Firestore database from a Cloud Run function using @google-cloud/firestore. I hope this was helpful. If anyone knows how to access a non-default database with firebase-admin, please let me know.

References

https://github.com/googleapis/nodejs-firestore/blob/main/types/firestore.d.ts#L387-L400

Ultimately, I couldn't find any specific documentation and discovered databaseId from the @google-cloud/firestore GitHub type definitions.

Source

https://github.com/cm-wada-yusuke/llm-reviewer/tree/main/rss-manager

Discussion

QuantumQuantum

firebase-adminで非デフォルトデータベースへアクセスする方法は、
getFirestore(app, "ここにデータベース名を入れる")でアクセスできます。

https://zenn.dev/quantum/articles/43a9ef26fec1e3

サンプル
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = { // 接続設定 };

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// ↓ここでデータベース名指定
const db = getFirestore(app, "ここにデータベース名を入れる");