import { randomUUID } from 'crypto'; import { CollectionReference, DocumentReference, Query } from 'firebase-admin/firestore'; import { UnimplementedCollection } from './base/unimplemented_collection'; import { FakeDocumentRef } from './fake_document_ref'; import { FakeFirestoreCollectionData, FakeFirestoreDocumentData } from './fake_firestore_data'; import { FakeQuerySnapshot } from './fake_query_snapshot'; import { FakeQuery } from './fake_query'; export class FakeCollectionRef extends UnimplementedCollection implements CollectionReference { constructor( private _collectionData: FakeFirestoreCollectionData, ) { super(); } override doc(id?: any): FirebaseFirestore.DocumentReference { const data = this._collectionData[id]; return new FakeDocumentRef( id, data, (id, data) => this._onCreate(id, data), (id, data) => this._onUpdate(id, data), (id, _) => this._onDelete(id) ); } override async get(): Promise> { return new FakeQuerySnapshot( this._collectionData, (id, data) => this._onCreate(id, data), (id, data) => this._onUpdate(id, data), (id, _) => this._onDelete(id) ); } override async add(data: FirebaseFirestore.WithFieldValue): Promise> { const id = randomUUID(); this._collectionData = { ...this._collectionData, [id]: { data: data as T } }; return this.doc(id); } override withConverter(converter: FirebaseFirestore.FirestoreDataConverter): CollectionReference; override withConverter(converter: null): CollectionReference; override withConverter(converter: unknown): CollectionReference | CollectionReference { return this as unknown as CollectionReference; } private _onCreate(id: string, documentData: FakeFirestoreDocumentData) { this._collectionData[id] = documentData; } private _onUpdate(id: string, documentData: FakeFirestoreDocumentData) { // nothing to do } private _onDelete(id: string) { delete this._collectionData[id]; console.log(Object.keys(this._collectionData)); } override where(fieldPath: string | FirebaseFirestore.FieldPath, opStr: FirebaseFirestore.WhereFilterOp, value: any): Query; override where(filter: FirebaseFirestore.Filter): Query; override where(fieldPath: string | FirebaseFirestore.FieldPath, opStr?: FirebaseFirestore.WhereFilterOp, value?: any): Query { return new FakeQuery( this._collectionData, (id, data) => this._onCreate(id, data), (id, data) => this._onUpdate(id, data), (id, _) => this._onDelete(id) ).where(fieldPath, opStr || '==', value); } }