All files / admin/firestore FirestoreDocument.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 5/5
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 461x   1x 1x 1x   1x           19x 19x       25x       6x 6x       7x       1x                              
import { Flattable } from '@stevenkellner/typescript-common-functionality';
import type { Firestore } from 'firebase-admin/firestore';
import { FirestoreCollection } from './FirestoreCollection';
import { FirestorePath } from '../../shared/firestore/FirestorePath';
import { FirestoreSnapshot } from './FirestoreSnapshot';
 
export class FirestoreDocument<
    Values extends Record<string, any>,
    SubCollections extends Record<string, FirestoreCollection<any>> = never
> {
 
    public constructor(
        private readonly firestore: Firestore,
        private readonly path: FirestorePath
    ) {}
 
    public collection<Key extends keyof SubCollections & string>(key: Key): SubCollections[Key] {
        return new FirestoreCollection(this.firestore, this.path.appending(key)) as SubCollections[Key];
    }
 
    public async snapshot(): Promise<FirestoreSnapshot<Values>> {
        const snapshot = await this.firestore.doc(this.path.fullPath).get() as FirebaseFirestore.DocumentSnapshot<Flattable.Flatten<Values>>;
        return new FirestoreSnapshot(snapshot);
    }
 
    public async set(values: Values): Promise<void> {
        await this.firestore.doc(this.path.fullPath).set(Flattable.flatten(values) as any);
    }
 
    public async remove(): Promise<void> {
        await this.firestore.doc(this.path.fullPath).delete();
    }
}
 
// istanbul ignore next
export namespace FirestoreDocument {
 
    export function base<SubCollections extends Record<string, FirestoreCollection<any>>>(firestore: Firestore): FirestoreDocument<never, SubCollections> {
        return new FirestoreDocument(firestore, new FirestorePath());
    }
 
    export type ValuesOf<Document extends FirestoreDocument<any, any>> = Document extends FirestoreDocument<infer Values, any> ? Values : never;
 
    export type SubCollectionsOf<Document extends FirestoreDocument<any, any>> = Document extends FirestoreDocument<any, infer SubCollections> ? SubCollections : never;
}