| 38 | imports: [AsyncPipe], |
| 39 | }) |
| 40 | export class UpboatsComponent implements OnInit { |
| 41 | |
| 42 | private readonly transferState = inject(TransferState); |
| 43 | private readonly transferStateKeys = { |
| 44 | disableInputs: makeStateKey<boolean>("upboats:disableInputs"), |
| 45 | animals: makeStateKey<Animal[]>("upboats:animals"), |
| 46 | } as const; |
| 47 | |
| 48 | protected readonly disableInputs = authState(inject(Auth)).pipe( |
| 49 | map(it => !it), |
| 50 | isPlatformServer(inject(PLATFORM_ID)) ? |
| 51 | tap(it => this.transferState.set(this.transferStateKeys.disableInputs, it)) : |
| 52 | startWith(this.transferState.get(this.transferStateKeys.disableInputs, true)) |
| 53 | ); |
| 54 | |
| 55 | public readonly animals: Observable<Animal[]>; |
| 56 | |
| 57 | private readonly firestore; |
| 58 | |
| 59 | constructor() { |
| 60 | this.firestore = getFirestore(inject(FirebaseApp));; |
| 61 | if (!(this.firestore as any)._settingsFrozen && environment.emulatorPorts?.firestore) { |
| 62 | connectFirestoreEmulator(this.firestore, "localhost", environment.emulatorPorts.firestore); |
| 63 | } |
| 64 | |
| 65 | const animalsCollection = collection(this.firestore, 'animals').withConverter<Animal>({ |
| 66 | fromFirestore: snapshot => { |
| 67 | const { name, upboats } = snapshot.data(); |
| 68 | const { id } = snapshot; |
| 69 | const { hasPendingWrites } = snapshot.metadata; |
| 70 | return { id, name, upboats, hasPendingWrites }; |
| 71 | }, |
| 72 | toFirestore: (it: any) => it, |
| 73 | }); |
| 74 | const animalsQuery = query(animalsCollection, orderBy('upboats', 'desc'), orderBy('updatedAt', 'desc')); |
| 75 | |
| 76 | this.animals = collectionData(animalsQuery).pipe( |
| 77 | traceUntilFirst('animals'), |
| 78 | isPlatformServer(inject(PLATFORM_ID)) ? |
| 79 | tap(it => this.transferState.set(this.transferStateKeys.animals, it)) : |
| 80 | this.transferState.hasKey(this.transferStateKeys.animals) ? |
| 81 | startWith(this.transferState.get(this.transferStateKeys.animals, [])) : |
| 82 | tap() |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | ngOnInit(): void { |
| 87 | } |
| 88 | |
| 89 | async upboat(id: string) { |
| 90 | return await updateDoc(doc(this.firestore, `animals/${id}`), { |
| 91 | upboats: increment(1), |
| 92 | updatedAt: serverTimestamp(), |
| 93 | }); |
| 94 | } |
| 95 | |
| 96 | async downboat(id: string) { |
| 97 | return await updateDoc(doc(this.firestore, `animals/${id}`), { |