import * as admin from "firebase-admin";
import DataModel from "../types/firebase";
export class FirebaseManager {
db = admin.database();
constructor() {
this.db = admin.database();
if (this.db === undefined) {
throw "cannot find database";
}
let data = this.db
.ref(`/`)
.get()
.then((snapshot) => {
if (!snapshot.exists()) {
throw "no database found :(";
} else {
let data = snapshot.val();
try {
let castedData = data as DataModel;
console.log("Database successfully initialised!");
} catch {
throw "Data could not be casted properly during initialisation";
}
}
});
}
}
嗨,我一直在一个不和谐的机器人,需要firebase作为后端工作。然而,当我初始化这个类时,调用。get()函数说Error: Error: Client is offline
,但我一直在网上,有人知道为什么吗?此处以"firebase-admin": "^9.11.1"
版本为例进行说明。如果你想看到所有的代码,https://github.com/MaxiGames/MaxiGames.js/tree/firebase
在这里。
哎呀,问题是我们需要遵循这里的https://firebase.google.com/docs/admin/setup
教程并设置一个环境变量,然后使用admin.credential.applicationDefault()
作为我们输入到initialiseApp函数中的对象的凭据参数。因此,最后的代码应该是admin.initializeApp({credential:admin.credential.applicationDefault(), databaseURL:"https://{your-project}-default-rtdb.firebaseio.com"});