Home > Software design >  How to view connection or disconnection to Firebase database?
How to view connection or disconnection to Firebase database?

Time:11-23

I have a firebase database, I finally managed to build a class with set, get, delete properties included.

But I was wondering how to include the text that the database was connected or not connected using console.log in the node.js work environment of bot applications such as discord.js

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
        }
    }

Find out the right way in node.js

CodePudding user response:

First, I'd recommend not putting your setup code inside the constructor. The constructor should be used to setup the class instance and not have any side effects.

Place most of your current procedure inside a login function, or whatever you prefer to call it.

If you want to setup events for your class, have the class extend node's EventEmitter:

lastly, you can use EventEmitter.emit(EventName, EventData) to emit custom events and receive them with 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}`);
});
  • Related