繁体   English   中英

如何查看Firebase数据库的连接或断开?

[英]How to view connection or disconnection to Firebase database?

我有一个 firebase 数据库,我终于成功地构建了一个 class,其中包含set, get, delete属性。

但是我想知道如何在discord.js等bot应用程序的discord.js工作环境中使用console.log包含数据库已连接或未连接的文本

class fireBase {
    constructor(client) {
        try {
            console.info(cyan('Firebase: database is now connected...'))
            if(!firebaseConfig || !firebaseConfig.credential || !firebaseConfig.databaseURL){
               throw ('config data must be added to connect to the database\n [credential], [databaseURL] in config.json')
            }
            this.client = client;
            this.app  = initializeApp({ credential: cert(firebaseConfig.credential), databaseURL: firebaseConfig.databaseURL });
            this.db  = getFirestore(this.app);

            console.info(green('Firebase: database connected successfully'))
        } catch (err) {
            throw new Error(red(err)).message
        }
    }

在node.js中找到正确的方法

首先,我建议不要将设置代码放在构造函数中。 构造函数应该用于设置 class 实例并且没有任何副作用。

将您当前的大部分过程放在登录名 function 中,或者您喜欢的任何名称。

如果你想为你的 class 设置事件,让 class 扩展节点的EventEmitter

最后,您可以使用EventEmitter.emit(EventName, EventData)发出自定义事件并使用EventEmitter.on(EventName)接收它们。

// import EventEmitter from "node:events"
class FireBase extends EventEmitter {
    constructor(client) {
         this.client = client;
     }

    login() {
        try {
            if(!firebaseConfig || !firebaseConfig.credential || !firebaseConfig.databaseURL){
               throw ('config data must be added to connect to the database\n [credential], [databaseURL] in config.json')
            }
            this.app  = initializeApp({ credential: cert(firebaseConfig.credential), databaseURL: firebaseConfig.databaseURL });
            this.db  = getFirestore(this.app);
            
            // Emit Event
            this.emit("login");
        } catch (err) {
            this.emit("error", err);
            throw new Error(red(err)).message
        }
    }
}
const fb = new Firebase(client);
fb.login();

// Receive Event
fb.on("login", () => {
   console.log('Logged in!');
});

fb.on("error", err => {
   console.error(`An error occured: ${err}`);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM