Skip to main content

Configure handlers

Basics

A document class handler connects Firebase TypeScript with your used Firebase SDK. It defines, how the classes are read and stored to your Firestore instance.

This concept allows the Firebase TypeScript library to be independent of the Firebase SDK used and allows that the library works even if your Firebase SDK updates to a newer version.

The good thing about document class handlers is that you probably don't need to worry about them except of using one of the pre defined document class handlers below and adding them to your project.

Example document class handlers

classes/DocumentHandler.ts
import {
WebDocumentBatchHandler,
WebDocumentClassHandler,
WebWriteBatch,
WebDocumentReference,
WebDocumentData,
WebCollectionReference,
WebSetOptions
} from "@janwuesten/firebase-typescript"
import {
collection,
getDoc,
addDoc,
setDoc,
updateDoc,
deleteDoc,
doc,
getFirestore,
writeBatch
} from "firebase/firestore"

export class DocumentHandler implements WebDocumentClassHandler {
collection(name: string) {
return collection(getFirestore(), name)
}
getDoc(ref: WebDocumentReference<WebDocumentData>) {
return getDoc(ref)
}
addDoc(collectionRef: WebCollectionReference<WebDocumentData>, data: Partial<unknown>) {
return addDoc(collectionRef, data)
}
setDoc(ref: WebDocumentReference<WebDocumentData>, data: Partial<unknown>, options: WebSetOptions) {
return setDoc(ref, data, options)
}
updateDoc(ref: WebDocumentReference<WebDocumentData>, data: Partial<unknown>) {
return updateDoc(ref, data)
}
deleteDoc(ref: WebDocumentReference<WebDocumentData>) {
return deleteDoc(ref)
}
doc(ref: WebCollectionReference<WebDocumentData>, id: string) {
return doc(ref, id)
}
}
export class BatchHandler implements WebDocumentBatchHandler {
create() {
return writeBatch(getFirestore())
}
set(batch: WebWriteBatch, ref: WebDocumentReference<WebDocumentData>, data: WebDocumentData) {
batch.set(ref, data)
}
update(batch: WebWriteBatch, ref: WebDocumentReference<WebDocumentData>, data: WebDocumentData) {
batch.update(ref, data)
}
delete(batch: WebWriteBatch, ref: WebDocumentReference<WebDocumentData>) {
batch.delete(ref)
}
commit(batch: WebWriteBatch) {
return batch.commit()
}
}