From 6330f22bf4bd9e4e39315dc41bdb63c4de654c56 Mon Sep 17 00:00:00 2001 From: Daniel Young Lee Date: Thu, 7 Dec 2023 09:28:44 +0900 Subject: [PATCH 1/2] Memoize firestore.getDatabase. --- src/deploy/functions/services/firestore.ts | 20 +++++++++++++++++++- src/gcp/firestore.ts | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/deploy/functions/services/firestore.ts b/src/deploy/functions/services/firestore.ts index d4eb39b45d5..dade0774b8e 100644 --- a/src/deploy/functions/services/firestore.ts +++ b/src/deploy/functions/services/firestore.ts @@ -2,6 +2,24 @@ import * as backend from "../backend"; import * as firestore from "../../../gcp/firestore"; import { FirebaseError } from "../../../error"; +const dbCache = new Map(); + +/** + * A memoized version of firestore.getDatabase that avoids repeated calls to the API. + * + * @param project the project ID + * @param databaseId the database ID or "(default)" + */ +async function getDatabase(project: string, databaseId: string): Promise { + const key = `${project}/${databaseId}`; + if (dbCache.has(key)) { + return dbCache.get(key)!; + } + const db = await firestore.getDatabase(project, databaseId); + dbCache.set(key, db); + return db; +} + /** * Sets a firestore event trigger's region to the firestore database region. * @param endpoint the firestore endpoint @@ -9,7 +27,7 @@ import { FirebaseError } from "../../../error"; export async function ensureFirestoreTriggerRegion( endpoint: backend.Endpoint & backend.EventTriggered ): Promise { - const db = await firestore.getDatabase( + const db = await getDatabase( endpoint.project, endpoint.eventTrigger.eventFilters?.database || "(default)" ); diff --git a/src/gcp/firestore.ts b/src/gcp/firestore.ts index e5897c75f66..c870fa95485 100644 --- a/src/gcp/firestore.ts +++ b/src/gcp/firestore.ts @@ -8,7 +8,7 @@ const apiClient = new Client({ urlPrefix: firestoreOrigin, }); -interface Database { +export interface Database { name: string; uid: string; createTime: string; From 762c4e3ae47fdb790242f2aee4affd1cb437c0b8 Mon Sep 17 00:00:00 2001 From: Daniel Young Lee Date: Thu, 7 Dec 2023 09:33:35 +0900 Subject: [PATCH 2/2] Add changelog. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29bb2d..c60322ef68a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1 @@ +- Fix bug where deploying Firestore function resulted in redudant API calls to the Firestore API (#6583).