我正在从 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
Firebase Web SDK 不能替代 firebase-admin。在后端,您仍然需要使用 firebase-admin 及其常规 API。 firebase-admin 没有“模块化”API。
更具体地说: