@gameon/web
Version:
Chat clients for web
54 lines (46 loc) • 1.33 kB
text/typescript
import { FirebaseApp, FirebaseOptions, initializeApp } from 'firebase/app';
import {
Firestore,
collection,
getFirestore,
limit,
onSnapshot,
orderBy,
query as firestoreQuery,
QuerySnapshot,
DocumentData,
FirestoreError,
} from 'firebase/firestore';
export type ConversationData = {
app: string;
channel: string;
conversationId?: string;
};
export class FirebaseInstance {
constructor(firebaseConfig: FirebaseOptions) {
this.app = initializeApp(firebaseConfig, 'on-chat-bot-client');
this.store = getFirestore(this.app);
}
app: FirebaseApp;
store: Firestore;
getFirestoreConvoPath(conversationData: ConversationData) {
return `channel:${conversationData.channel}:app:${conversationData.app}:conversations/conversation:${conversationData.conversationId}/events`;
}
listenToConvo(
conversationData: ConversationData,
messageHistoryLimit: number,
onSuccess: (data: QuerySnapshot<DocumentData>) => void,
onError: (error: FirestoreError) => void
) {
const messagesRef = collection(
this.store,
this.getFirestoreConvoPath(conversationData)
);
const messagesQuery = firestoreQuery(
messagesRef,
orderBy('timestamp', 'desc'),
limit(messageHistoryLimit)
);
onSnapshot(messagesQuery, onSuccess, onError);
}
}