Created
September 12, 2023 22:39
-
-
Save metruzanca/fc07dfdda4ade293ca40e2b9f61329c0 to your computer and use it in GitHub Desktop.
An experimental util for making firebase queries following the Builder Pattern. I've since moved to using something cooler though :D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class QueryBuilder { | |
private collection: CollectionReference<DocumentData, DocumentData> | |
constructor(path: string) { | |
this.collection = collection(firestore, path) | |
} | |
private where: QueryFieldFilterConstraint[] = [] | |
filter(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown) { | |
this.where.push(where(fieldPath, opStr, value)) | |
return this | |
} | |
private after: QueryStartAtConstraint | undefined | |
startAfter(doc: QueryDocumentSnapshot<DocumentData, DocumentData>) { | |
this.after = startAfter(doc) | |
return this | |
} | |
private limit: QueryLimitConstraint | undefined | |
limitTo(pageCount: number) { | |
this.limit = limit(pageCount) | |
return this | |
} | |
private order: QueryOrderByConstraint | undefined | |
orderBy(fieldPath: string | FieldPath, directionStr?: 'asc' | 'desc') { | |
this.order = orderBy(fieldPath, directionStr) | |
return this | |
} | |
buildQuery() { | |
let parts = [this.collection, ...this.where, this.order, this.after, this.limit] | |
parts = parts.filter(Boolean) | |
// eslint-disable-next-line | |
// @ts-ignore I CBA to write the type for parts | |
return query(...parts) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment