在实时数据库中动态创建数据库名称

时间:2020-05-14 07:11:47

标签: firebase firebase-realtime-database chat

我需要使用Firebase实时数据库创建一个聊天应用程序。我希望它看起来像对等消息,所以我想动态创建数据库,因此我要引用的数据库应该是动态的,而不是硬编码的-我该怎么做?

请提出任何建议!

任何能提供帮助的反应本地编码员都是很棒的。

enter image description here

import firebase from 'firebase'; // 4.8.1


class Fire {
    constructor() {
        this.init();
        this.observeAuth();
    }

    init = () => {
        if (!firebase.apps.length) {
            firebase.initializeApp({
                apiKey: 'AIzaSyD5JWhxK2y8HkOSmXvqy8JDI9beS4aBkBo',
                authDomain: 'digiqure-dev.firebaseapp.com',
                databaseURL: 'https://digiqure-dev.firebaseio.com',
                projectId: 'digiqure-dev',
                storageBucket: '',
                messagingSenderId: 'G-QX9LXKN0EY'
            });
        }
    };

    observeAuth = () =>
        firebase.auth().onAuthStateChanged(this.onAuthStateChanged);

    onAuthStateChanged = user => {
        if (!user) {
            try {
                firebase.auth().signInAnonymously();
            } catch ({ message }) {
                alert(message);
            }
        }
    };

    get uid() {
        return (firebase.auth().currentUser || {}).uid;
    }

    get ref() {
        return firebase.database().ref('test-chat');
    }

    parse = snapshot => {
        const { timestamp: numberStamp, text, user } = snapshot.val();
        const { key: _id } = snapshot;
        const timestamp = new Date(numberStamp);
        const message = {
            _id,
            timestamp,
            text,
            user,
        };
        return message;
    };

    on = callback =>
        this.ref
            .limitToLast(20)
            .on('child_added', snapshot => callback(this.parse(snapshot)));

    get timestamp() {
        return firebase.database.ServerValue.TIMESTAMP;
    }
    // send the message to the Backend
    send = messages => {
        for (let i = 0; i < messages.length; i++) {
            const { text, user } = messages[i];
            const message = {
                text,
                user,
                timestamp: this.timestamp,
            };
            this.append(message);
        }
    };

    append = message => this.ref.push(message);

    // close the connection to the Backend
    off() {
        this.ref.off();
    }
}

Fire.shared = new Fire();
export default Fire;

0 个答案:

没有答案
相关问题