Firebase Web 模块化 API -initializeApp()

问题描述 投票:0回答:1

我正在从 JavaScript 命名空间(compat)切换到 JavaScript Web 模块化 API。 我的代码是一个 Firebase 函数,带有在 GCP 上运行的 http 触发器,因此代码“存在”在 GCP 基础设施中。我的想法是,正因为如此,我不需要指定一堆数据来初始化应用程序和数据库,如果我的代码运行在 ReactJS 或任何其他前端框架上,就会出现这种情况。

在我的旧代码中,我只是在一个名为

firebase-db
的文件中初始化了应用程序,该文件包含在需要的地方。这也给了我一个数据库的句柄。模块化 API 不再需要数据库句柄。

// This is the old namespaced code
const admin = require("firebase-admin");

const app = admin.initializeApp();
const database = admin.database(app);
module.exports = database;

在我的新代码中,我没有此文件,我只是在我的文件中使用以下代码。

const { ref, getDatabase, get } = require("firebase/database");
...

但是,这是行不通的。 我收到一个错误,明确指出“应用程序”需要初始化。

FirebaseError:Firebase:未创建 Firebase 应用程序“[DEFAULT]” - 首先调用initializeApp()(应用程序/无应用程序)

我的新

firebase-db
文件如下所示;但它不起作用:

// This is the new modular code
const { initializeApp } = require("firebase-admin");
const { getDatabase } = require("firebase/database");

const app = initializeApp(); //<-- This line generates an error!
const database = getDatabase(app);

module.exports = database;

调用

initializeApp();
会生成错误:

类型错误:无法读取未定义的属性“INTERNAL”

我已经查看了文档,但找不到任何关于如何初始化应用程序的好示例,以便我可以使用 getDatabase() 获取 Dabase 句柄。

https://firebase.google.com/docs/database/admin/retrieve-data#node.js_19 https://firebase.google.com/docs/database/web/read-and-write#web-modular-api_5 https://firebase.google.com/docs/reference/js/database.md#equalto_51c2c8b

非常感谢任何帮助! /K

javascript firebase firebase-realtime-database firebase-admin
1个回答
0
投票

Firebase Web SDK 不能替代 firebase-admin。在后端,您仍然需要使用 firebase-admin 及其常规 API。 firebase-admin 没有“模块化”API。

更具体地说:

  • “firebase/database”是为前端 Web 应用程序设计的。它并不是真正设计用于后端的(除非可能在非常特殊的情况下,这可能不适用于您)。包含经典和模块化 API 的文档:https://firebase.google.com/docs/database/web/start
  • “firebase-admin”仍然是与 Nodejs 后端一起使用的主要包。它并没有过时,它的 API 没有发生重大变化,并且它没有提供反映现代 Web SDK 中内容的模块化 API。文档:https://firebase.google.com/docs/database/admin/start
© www.soinside.com 2019 - 2024. All rights reserved.