diff --git a/functions/src/config.ts b/functions/src/config.ts index 00694479..680cfcde 100644 --- a/functions/src/config.ts +++ b/functions/src/config.ts @@ -1,16 +1,27 @@ -import { ServiceAccount, cert, initializeApp } from "firebase-admin/app"; +import { + cert, + getApps, + initializeApp, + ServiceAccount, +} from "firebase-admin/app"; import * as dotenv from "dotenv"; -// load environment variables dotenv.config({ path: "../.env" }); const serviceAccount = JSON.parse( process.env.PUBLIC_FIREBASE_SERVICE_ACCOUNT || "{}", ); -// initialize firebase app -export const initialize = () => - initializeApp({ - credential: cert(serviceAccount as ServiceAccount), - }); +const initializeFirebaseApp = () => { + if (getApps().length === 0) { + initializeApp({ + credential: cert(serviceAccount as ServiceAccount), + databaseURL: process.env.FIREBASE_DATABASE_URL, + }); + } +}; -export const functionsRegion = process.env.PUBLIC_FIREBASE_FUNCTIONS_REGION || ""; +const projectId = serviceAccount.project_id; + +const functionsRegion = process.env.PUBLIC_FIREBASE_FUNCTIONS_REGION || ""; + +export { initializeFirebaseApp, projectId, functionsRegion }; diff --git a/functions/src/index.ts b/functions/src/index.ts index f7a526bd..a9d70c0b 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -1,8 +1,8 @@ import * as httpApi from "./api/http/api"; import * as authOnCreate from "./api/auth/on-create"; -import { initialize } from "./config"; +import { initializeFirebaseApp } from "./config"; -initialize(); +initializeFirebaseApp(); exports.http_api = httpApi.default; exports.onCreateUser = authOnCreate.default; diff --git a/functions/test/api/auth/on-create.test.ts b/functions/test/api/auth/on-create.test.ts index 54771e50..8b7ecc44 100644 --- a/functions/test/api/auth/on-create.test.ts +++ b/functions/test/api/auth/on-create.test.ts @@ -2,7 +2,7 @@ import { expect } from "chai"; import { getAuth } from "firebase-admin/auth"; import { DocumentSnapshot, getFirestore } from "firebase-admin/firestore"; import { before, describe, test } from "mocha"; -import {initialize} from "../../../src/config"; +import { initializeFirebaseApp } from "../../../src/config"; describe("onCreate", () => { const collection = "users"; @@ -13,7 +13,7 @@ describe("onCreate", () => { }; before(async () => { - initialize(); + initializeFirebaseApp(); }); test("Create user and check if it saved in users collection", async () => {