@tech4good/angular-schematics 17.0.4 → 18.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/package.json +4 -4
- package/src/collection.json +0 -16
- package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +22 -8
- package/src/component/index.js +2 -45
- package/src/component/index.js.map +1 -1
- package/src/component/schema.json +0 -5
- package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +12 -0
- package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +1 -0
- package/src/entity/files/__name@dasherize__/__name@dasherize__.store.ts.template +41 -0
- package/src/entity/index.js +29 -50
- package/src/entity/index.js.map +1 -1
- package/src/init/files/.firebaserc.template +8 -0
- package/src/init/files/README.md.template +6 -6
- package/src/init/files/angular.json.template +18 -11
- package/src/init/files/package.json.template +29 -30
- package/src/init/files/src/app/admin/{waitlist/waitlist.animations.ts.template → admin-panel/admin-panel.animations.ts.template} +1 -1
- package/src/init/files/src/app/admin/{waitlist/waitlist.component.html.template → admin-panel/admin-panel.component.html.template} +3 -3
- package/src/init/files/src/app/admin/{waitlist/waitlist.component.scss.template → admin-panel/admin-panel.component.scss.template} +1 -1
- package/src/init/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +25 -0
- package/src/init/files/src/app/admin/admin-panel/admin-panel.component.ts.template +99 -0
- package/src/init/files/src/app/app.component.html.template +1 -0
- package/src/init/files/src/app/app.component.ts.template +14 -8
- package/src/init/files/src/app/app.config.ts.template +63 -0
- package/src/init/files/src/app/app.routes.ts.template +32 -0
- package/src/init/files/src/app/core/analytics/log.service.ts.template +122 -89
- package/src/init/files/src/app/core/analytics/time-analytics.service.ts.template +9 -17
- package/src/init/files/src/app/core/auth/auth.guard.ts.template +25 -22
- package/src/init/files/src/app/core/firebase/cached-listeners.service.ts.template +291 -0
- package/src/init/files/src/app/core/firebase/database.service.ts.template +56 -0
- package/src/init/files/src/app/core/firebase/firebase.mock.service.ts.template +276 -0
- package/src/init/files/src/app/core/firebase/firebase.service.ts.template +265 -215
- package/src/init/files/src/app/core/local-storage/session.service.ts.template +3 -4
- package/src/init/files/src/app/core/store/app.model.ts.template +19 -0
- package/src/init/files/src/app/core/store/app.store.ts.template +1074 -0
- package/src/init/files/src/app/core/store/auth/auth.mock.ts.template +20 -0
- package/src/init/files/src/app/core/store/auth/auth.store.ts.template +136 -0
- package/src/init/files/src/app/core/store/batch-write.firebase.service.ts.template +58 -0
- package/src/init/files/src/app/core/store/batch-write.mock.service.ts.template +105 -0
- package/src/init/files/src/app/core/store/batch-write.service.ts.template +126 -0
- package/src/init/files/src/app/core/store/user/user.mock.ts.template +24 -0
- package/src/init/files/src/app/core/store/user/user.model.ts.template +1 -1
- package/src/init/files/src/app/core/store/user/user.store.ts.template +41 -0
- package/src/init/files/src/app/core/store/user-context/user-context.mock.ts.template +24 -0
- package/src/init/files/src/app/core/store/user-context/user-context.model.ts.template +1 -0
- package/src/init/files/src/app/core/store/user-context/user-context.store.ts.template +41 -0
- package/src/init/files/src/app/core/utils/rand.utils.ts.template +13 -0
- package/src/init/files/src/app/{onboarding → first-time}/consent/consent.component.html.template +8 -13
- package/src/init/files/src/app/first-time/consent/consent.component.ts.template +90 -0
- package/src/init/files/src/app/first-time/early-access/early-access.animations.ts.template +4 -0
- package/src/init/files/src/app/first-time/early-access/early-access.component.html.template +69 -0
- package/src/init/files/src/app/{onboarding/waiting/waiting.component.scss.template → first-time/early-access/early-access.component.scss.template} +1 -1
- package/src/init/files/src/app/first-time/early-access/early-access.component.spec.ts.template +25 -0
- package/src/init/files/src/app/first-time/early-access/early-access.component.ts.template +194 -0
- package/src/init/files/src/app/first-time/early-access/early-access.model.ts.template +7 -0
- package/src/init/files/src/app/{general → first-time}/landing/landing.component.html.template +1 -1
- package/src/init/files/src/app/first-time/landing/landing.component.ts.template +44 -0
- package/src/init/files/src/app/first-time/login/login.component.html.template +10 -0
- package/src/init/files/src/app/first-time/login/login.component.ts.template +45 -0
- package/src/init/files/src/app/first-time/onboarding/onboarding.animations.ts.template +4 -0
- package/src/init/files/src/app/first-time/onboarding/onboarding.component.html.template +2 -0
- package/src/init/files/src/app/first-time/onboarding/onboarding.component.scss.template +5 -0
- package/src/init/files/src/app/{admin/waitlist/waitlist.component.spec.ts.template → first-time/onboarding/onboarding.component.spec.ts.template} +6 -6
- package/src/init/files/src/app/first-time/onboarding/onboarding.component.ts.template +41 -0
- package/src/init/files/src/app/main/home/home.component.html.template +5 -0
- package/src/init/files/src/app/main/home/home.component.ts.template +51 -0
- package/src/init/files/src/app/shared/navbar/navbar.component.html.template +15 -0
- package/src/init/files/src/app/shared/navbar/navbar.component.scss.template +43 -0
- package/src/init/files/src/app/shared/navbar/navbar.component.spec.ts.template +25 -0
- package/src/init/files/src/app/shared/navbar/navbar.component.ts.template +40 -0
- package/src/init/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +9 -0
- package/src/init/files/src/app/shared/{components/redeployment-warning → redeployment-warning}/redeployment-warning.component.ts.template +17 -6
- package/src/init/files/src/app/shared/{components/redeployment-warning → redeployment-warning}/redeployment-warning.service.ts.template +2 -2
- package/src/init/files/src/assets/images/close-x.svg +3 -0
- package/src/init/files/src/environments/environment.ts.template +1 -0
- package/src/init/files/src/index.html.template +1 -1
- package/src/init/files/tsconfig.json.template +0 -1
- package/src/container/files/__name@dasherize__/+state/__name@dasherize__.actions.ts.template +0 -26
- package/src/container/files/__name@dasherize__/+state/__name@dasherize__.effects.ts.template +0 -48
- package/src/container/files/__name@dasherize__/+state/__name@dasherize__.model.ts.template +0 -0
- package/src/container/files/__name@dasherize__/+state/__name@dasherize__.selectors.ts.template +0 -20
- package/src/container/files/__name@dasherize__/+state/__name@dasherize__.state.ts.template +0 -13
- package/src/container/files/__name@dasherize__/__name@dasherize__.animations.ts.template +0 -4
- package/src/container/files/__name@dasherize__/__name@dasherize__.component.html.template +0 -3
- package/src/container/files/__name@dasherize__/__name@dasherize__.component.scss.template +0 -5
- package/src/container/files/__name@dasherize__/__name@dasherize__.component.spec.ts.template +0 -25
- package/src/container/files/__name@dasherize__/__name@dasherize__.component.ts.template +0 -90
- package/src/container/index.d.ts +0 -2
- package/src/container/index.js +0 -127
- package/src/container/index.js.map +0 -1
- package/src/container/index_spec.d.ts +0 -1
- package/src/container/index_spec.js +0 -23
- package/src/container/index_spec.js.map +0 -1
- package/src/container/schema.json +0 -50
- package/src/entity/files/__name@dasherize__/__name@dasherize__.actions.ts.template +0 -249
- package/src/entity/files/__name@dasherize__/__name@dasherize__.effects.ts.template +0 -131
- package/src/entity/files/__name@dasherize__/__name@dasherize__.reducer.spec.ts.template +0 -13
- package/src/entity/files/__name@dasherize__/__name@dasherize__.reducer.ts.template +0 -51
- package/src/entity/files/__name@dasherize__/__name@dasherize__.service.ts.template +0 -50
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.actions.ts.template +0 -270
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.effects.ts.template +0 -131
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.model.ts.template +0 -3
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.reducer.spec.ts.template +0 -13
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.reducer.ts.template +0 -51
- package/src/entity-in-example/files/__name@dasherize__/__name@dasherize__.service.ts.template +0 -50
- package/src/entity-in-example/index.d.ts +0 -2
- package/src/entity-in-example/index.js +0 -141
- package/src/entity-in-example/index.js.map +0 -1
- package/src/entity-in-example/index_spec.d.ts +0 -1
- package/src/entity-in-example/index_spec.js +0 -23
- package/src/entity-in-example/index_spec.js.map +0 -1
- package/src/entity-in-example/schema.json +0 -45
- package/src/init/files/CHANGELOG.md.template +0 -10
- package/src/init/files/src/app/admin/admin-routing.module.ts.template +0 -17
- package/src/init/files/src/app/admin/admin.module.spec.ts.template +0 -13
- package/src/init/files/src/app/admin/admin.module.ts.template +0 -28
- package/src/init/files/src/app/admin/waitlist/+state/waitlist.actions.ts.template +0 -23
- package/src/init/files/src/app/admin/waitlist/+state/waitlist.effects.ts.template +0 -50
- package/src/init/files/src/app/admin/waitlist/+state/waitlist.model.ts.template +0 -0
- package/src/init/files/src/app/admin/waitlist/+state/waitlist.selectors.ts.template +0 -39
- package/src/init/files/src/app/admin/waitlist/+state/waitlist.state.ts.template +0 -13
- package/src/init/files/src/app/admin/waitlist/waitlist.component.ts.template +0 -141
- package/src/init/files/src/app/app-routing.module.ts.template +0 -26
- package/src/init/files/src/app/app.module.ts.template +0 -34
- package/src/init/files/src/app/core/core.module.ts.template +0 -75
- package/src/init/files/src/app/core/setup/firebase-setup.ts.template +0 -25
- package/src/init/files/src/app/core/setup/module-import-guard.ts.template +0 -5
- package/src/init/files/src/app/core/snackbar/snackbar.actions.ts.template +0 -24
- package/src/init/files/src/app/core/snackbar/snackbar.effects.ts.template +0 -41
- package/src/init/files/src/app/core/store/app-state/app-state.actions.ts.template +0 -249
- package/src/init/files/src/app/core/store/app-state/app-state.effects.ts.template +0 -131
- package/src/init/files/src/app/core/store/app-state/app-state.model.ts.template +0 -8
- package/src/init/files/src/app/core/store/app-state/app-state.reducer.spec.ts.template +0 -13
- package/src/init/files/src/app/core/store/app-state/app-state.reducer.ts.template +0 -51
- package/src/init/files/src/app/core/store/app-state/app-state.service.ts.template +0 -50
- package/src/init/files/src/app/core/store/app.actions.ts.template +0 -92
- package/src/init/files/src/app/core/store/app.effects.ts.template +0 -175
- package/src/init/files/src/app/core/store/app.reducer.ts.template +0 -36
- package/src/init/files/src/app/core/store/app.selectors.ts.template +0 -42
- package/src/init/files/src/app/core/store/auth/auth.actions.ts.template +0 -77
- package/src/init/files/src/app/core/store/auth/auth.effects.ts.template +0 -163
- package/src/init/files/src/app/core/store/auth/auth.reducer.spec.ts.template +0 -13
- package/src/init/files/src/app/core/store/auth/auth.reducer.ts.template +0 -26
- package/src/init/files/src/app/core/store/auth/auth.selectors.ts.template +0 -25
- package/src/init/files/src/app/core/store/cached-load-connections.service.ts.template +0 -405
- package/src/init/files/src/app/core/store/cached-selectors.service.ts.template +0 -376
- package/src/init/files/src/app/core/store/effects.helpers.ts.template +0 -66
- package/src/init/files/src/app/core/store/user/user.actions.ts.template +0 -248
- package/src/init/files/src/app/core/store/user/user.effects.ts.template +0 -148
- package/src/init/files/src/app/core/store/user/user.reducer.spec.ts.template +0 -13
- package/src/init/files/src/app/core/store/user/user.reducer.ts.template +0 -50
- package/src/init/files/src/app/core/store/user/user.service.ts.template +0 -50
- package/src/init/files/src/app/core/store/user-context/user-context.actions.ts.template +0 -248
- package/src/init/files/src/app/core/store/user-context/user-context.effects.ts.template +0 -131
- package/src/init/files/src/app/core/store/user-context/user-context.reducer.spec.ts.template +0 -13
- package/src/init/files/src/app/core/store/user-context/user-context.reducer.ts.template +0 -51
- package/src/init/files/src/app/core/store/user-context/user-context.service.ts.template +0 -50
- package/src/init/files/src/app/core/utils/string-case.utils.ts.template +0 -96
- package/src/init/files/src/app/general/general-routing.module.ts.template +0 -25
- package/src/init/files/src/app/general/general.module.spec.ts.template +0 -13
- package/src/init/files/src/app/general/general.module.ts.template +0 -36
- package/src/init/files/src/app/general/home/+state/home.actions.ts.template +0 -26
- package/src/init/files/src/app/general/home/+state/home.effects.ts.template +0 -48
- package/src/init/files/src/app/general/home/+state/home.model.ts.template +0 -0
- package/src/init/files/src/app/general/home/+state/home.selectors.ts.template +0 -20
- package/src/init/files/src/app/general/home/+state/home.state.ts.template +0 -13
- package/src/init/files/src/app/general/home/home.component.html.template +0 -5
- package/src/init/files/src/app/general/home/home.component.ts.template +0 -88
- package/src/init/files/src/app/general/landing/+state/landing.actions.ts.template +0 -26
- package/src/init/files/src/app/general/landing/+state/landing.effects.ts.template +0 -48
- package/src/init/files/src/app/general/landing/+state/landing.model.ts.template +0 -0
- package/src/init/files/src/app/general/landing/+state/landing.selectors.ts.template +0 -20
- package/src/init/files/src/app/general/landing/+state/landing.state.ts.template +0 -13
- package/src/init/files/src/app/general/landing/landing.component.ts.template +0 -98
- package/src/init/files/src/app/general/login/login.component.html.template +0 -11
- package/src/init/files/src/app/general/login/login.component.ts.template +0 -80
- package/src/init/files/src/app/onboarding/consent/+state/consent.actions.ts.template +0 -23
- package/src/init/files/src/app/onboarding/consent/+state/consent.effects.ts.template +0 -47
- package/src/init/files/src/app/onboarding/consent/+state/consent.model.ts.template +0 -0
- package/src/init/files/src/app/onboarding/consent/+state/consent.selectors.ts.template +0 -20
- package/src/init/files/src/app/onboarding/consent/+state/consent.state.ts.template +0 -13
- package/src/init/files/src/app/onboarding/consent/consent.component.ts.template +0 -151
- package/src/init/files/src/app/onboarding/onboarding-routing.module.ts.template +0 -19
- package/src/init/files/src/app/onboarding/onboarding.module.spec.ts.template +0 -13
- package/src/init/files/src/app/onboarding/onboarding.module.ts.template +0 -32
- package/src/init/files/src/app/onboarding/waiting/+state/waiting.actions.ts.template +0 -26
- package/src/init/files/src/app/onboarding/waiting/+state/waiting.effects.ts.template +0 -52
- package/src/init/files/src/app/onboarding/waiting/+state/waiting.model.ts.template +0 -9
- package/src/init/files/src/app/onboarding/waiting/+state/waiting.selectors.ts.template +0 -42
- package/src/init/files/src/app/onboarding/waiting/+state/waiting.state.ts.template +0 -13
- package/src/init/files/src/app/onboarding/waiting/waiting.animations.ts.template +0 -4
- package/src/init/files/src/app/onboarding/waiting/waiting.component.html.template +0 -57
- package/src/init/files/src/app/onboarding/waiting/waiting.component.spec.ts.template +0 -25
- package/src/init/files/src/app/onboarding/waiting/waiting.component.ts.template +0 -281
- package/src/init/files/src/app/shared/components/redeployment-warning/redeployment-warning.component.html.template +0 -10
- package/src/init/files/src/app/shared/shared.module.ts.template +0 -87
- package/src/init/files/src/main.ts.template +0 -12
- package/src/module/files/__name@dasherize__/__name@dasherize__-routing.module.ts.template +0 -15
- package/src/module/files/__name@dasherize__/__name@dasherize__.module.spec.ts.template +0 -13
- package/src/module/files/__name@dasherize__/__name@dasherize__.module.ts.template +0 -24
- package/src/module/index.d.ts +0 -2
- package/src/module/index.js +0 -97
- package/src/module/index.js.map +0 -1
- package/src/module/index_spec.d.ts +0 -1
- package/src/module/index_spec.js +0 -23
- package/src/module/index_spec.js.map +0 -1
- package/src/module/schema.json +0 -38
- /package/src/init/files/src/app/{onboarding → first-time}/consent/consent.animations.ts.template +0 -0
- /package/src/init/files/src/app/{onboarding → first-time}/consent/consent.component.scss.template +0 -0
- /package/src/init/files/src/app/{onboarding → first-time}/consent/consent.component.spec.ts.template +0 -0
- /package/src/init/files/src/app/{general → first-time}/landing/landing.animations.ts.template +0 -0
- /package/src/init/files/src/app/{general → first-time}/landing/landing.component.scss.template +0 -0
- /package/src/init/files/src/app/{general → first-time}/landing/landing.component.spec.ts.template +0 -0
- /package/src/init/files/src/app/{general → first-time}/login/login.component.scss.template +0 -0
- /package/src/init/files/src/app/{general → first-time}/login/login.component.spec.ts.template +0 -0
- /package/src/init/files/src/app/{general → main}/home/home.animations.ts.template +0 -0
- /package/src/init/files/src/app/{general → main}/home/home.component.scss.template +0 -0
- /package/src/init/files/src/app/{general → main}/home/home.component.spec.ts.template +0 -0
- /package/src/init/files/src/app/shared/{components/redeployment-warning → redeployment-warning}/redeployment-warning.component.scss.template +0 -0
- /package/src/init/files/src/app/shared/{components/redeployment-warning → redeployment-warning}/redeployment-warning.component.spec.ts.template +0 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { Inject, Injectable, WritableSignal, inject, DestroyRef, computed } from '@angular/core';
|
|
2
|
+
import { toObservable } from '@angular/core/rxjs-interop';
|
|
3
|
+
import { Subject, Observable, merge, forkJoin, of, from, pipe } from 'rxjs';
|
|
4
|
+
import { startWith, pairwise, publishLast, publish, publishReplay, refCount, tap, pluck, mergeMap, filter, takeUntil, skipUntil, buffer, skip, switchMap, map, take } from 'rxjs/operators';
|
|
5
|
+
import { patchState } from '@ngrx/signals';
|
|
6
|
+
import { setEntities, setEntity, removeEntities, SelectEntityId } from '@ngrx/signals/entities';
|
|
7
|
+
import { EntityLoadQuery, EntityStreamQuery, entityInQueryResults } from '../store/app.store';
|
|
8
|
+
import { QueryParams, QueryOptions, AnyEntity } from '../store/app.model';
|
|
9
|
+
import { DocumentChange } from '@angular/fire/firestore';
|
|
10
|
+
import { DATABASE_SERVICE, DatabaseService } from './database.service';
|
|
11
|
+
|
|
12
|
+
const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
|
|
13
|
+
|
|
14
|
+
export interface CachedConnection {
|
|
15
|
+
queryKey: string;
|
|
16
|
+
registeredSet: Set<DestroyRef>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
@Injectable({
|
|
20
|
+
providedIn: 'root',
|
|
21
|
+
})
|
|
22
|
+
export class CachedListenersService {
|
|
23
|
+
/** Cached connections by loadKey. */
|
|
24
|
+
private connectionByQueryKey: Record<string, CachedConnection> = {};
|
|
25
|
+
|
|
26
|
+
/** Close connection events. */
|
|
27
|
+
private closeConnection$: Subject<string> = new Subject<string>();
|
|
28
|
+
|
|
29
|
+
/** Load state across the app by queryKey. Stores last load time in milliseconds. */
|
|
30
|
+
private lastLoadTime: Record<string, number> = {};
|
|
31
|
+
|
|
32
|
+
/** Define a unique key for each connection. */
|
|
33
|
+
private getQueryKey(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): string {
|
|
34
|
+
let queryOptionsString = '';
|
|
35
|
+
if (queryOptions) {
|
|
36
|
+
if (queryOptions.orderBy) {
|
|
37
|
+
queryOptionsString = queryOptionsString.concat(`orderBy${queryOptions.orderBy}`);
|
|
38
|
+
}
|
|
39
|
+
if (queryOptions.limit) {
|
|
40
|
+
queryOptionsString = queryOptionsString.concat(`limit${queryOptions.limit}`);
|
|
41
|
+
}
|
|
42
|
+
if (queryOptions.startAt) {
|
|
43
|
+
queryOptionsString = queryOptionsString.concat(`startAt${queryOptions.startAt}`);
|
|
44
|
+
}
|
|
45
|
+
if (queryOptions.startAfter) {
|
|
46
|
+
queryOptionsString = queryOptionsString.concat(`startAfter${queryOptions.startAfter}`);
|
|
47
|
+
}
|
|
48
|
+
if (queryOptions.endAt) {
|
|
49
|
+
queryOptionsString = queryOptionsString.concat(`endAt${queryOptions.endAt}`);
|
|
50
|
+
}
|
|
51
|
+
if (queryOptions.endBefore) {
|
|
52
|
+
queryOptionsString = queryOptionsString.concat(`endBefore${queryOptions.endBefore}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return `${collection}.${queryParams.sort()}.${queryOptionsString}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Return whether a stream exists for this query. */
|
|
59
|
+
isStreamForQuery(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
|
|
60
|
+
const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
|
|
61
|
+
return !!this.connectionByQueryKey[queryKey];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Get the last load time for a particular query. */
|
|
65
|
+
getLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): number {
|
|
66
|
+
// If there are queryOptions, we don't support saving load times
|
|
67
|
+
if (queryOptions && Object.keys(queryOptions).length > 0) return -1;
|
|
68
|
+
|
|
69
|
+
const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
|
|
70
|
+
return this.lastLoadTime[queryKey] || -1;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Set the last load time for a particular query. */
|
|
74
|
+
setLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions, time: number): void {
|
|
75
|
+
// If there are queryOptions, we don't support saving load times
|
|
76
|
+
if (queryOptions && Object.keys(queryOptions).length > 0) return;
|
|
77
|
+
|
|
78
|
+
const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
|
|
79
|
+
this.lastLoadTime[queryKey] = time;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Gets a cached connection if one exists. */
|
|
83
|
+
private getConnection(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): CachedConnection {
|
|
84
|
+
const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
|
|
85
|
+
return this.connectionByQueryKey[queryKey];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Main function called by the outside.
|
|
90
|
+
*/
|
|
91
|
+
public async processStreamQuery<T extends AnyEntity>(
|
|
92
|
+
collection: string,
|
|
93
|
+
store,
|
|
94
|
+
queryParams: QueryParams,
|
|
95
|
+
queryOptions: QueryOptions,
|
|
96
|
+
injector,
|
|
97
|
+
streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
|
|
98
|
+
options?: {
|
|
99
|
+
loading?: WritableSignal<boolean>,
|
|
100
|
+
},
|
|
101
|
+
): Promise<CachedConnection> {
|
|
102
|
+
// console.log("PROCESS QUERY: " + this.getQueryKey(collection, queryParams, queryOptions));
|
|
103
|
+
|
|
104
|
+
// Get destroyRef for the component that called processStreamQuery
|
|
105
|
+
// (which will be used to determine when to trigger unsubscribe)
|
|
106
|
+
const destroyRef = injector.get(DestroyRef);
|
|
107
|
+
|
|
108
|
+
// get connection and process the immediate query
|
|
109
|
+
let connection = this.getConnection(collection, queryParams, queryOptions);
|
|
110
|
+
|
|
111
|
+
if (connection) {
|
|
112
|
+
// if the connection already exists, don't need to create a new connection,
|
|
113
|
+
// but may need to add the DestroyRef if it doesn't already exist
|
|
114
|
+
if (!connection.registeredSet.has(destroyRef)) {
|
|
115
|
+
connection.registeredSet.add(destroyRef);
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
// if the connection does not exist, create it and initialize the
|
|
119
|
+
// registeredSet to include destroyRef
|
|
120
|
+
// this function also will subscribe and link to the store
|
|
121
|
+
connection = this.createConnection<T>(collection, store, queryParams, queryOptions, destroyRef);
|
|
122
|
+
this.connectionByQueryKey[connection.queryKey] = connection;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Unregister from the connection when the component is destroyed
|
|
126
|
+
// Disconnects the "virtual" connection. If this was the only DestroyRef,
|
|
127
|
+
// then actually unsubscribe
|
|
128
|
+
destroyRef.onDestroy(() => {
|
|
129
|
+
// Add a 5-second delay so we don't have to reconnect multiple times
|
|
130
|
+
// if the next view happens to use the same stream
|
|
131
|
+
setTimeout(() => {
|
|
132
|
+
connection.registeredSet.delete(destroyRef);
|
|
133
|
+
if (connection.registeredSet.size === 0) {
|
|
134
|
+
this.closeConnection$.next(connection.queryKey);
|
|
135
|
+
this.connectionByQueryKey[connection.queryKey] = undefined;
|
|
136
|
+
}
|
|
137
|
+
}, 5000);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// For every new entity on the stream, process the nested streamQueries
|
|
141
|
+
if (streamQueries) {
|
|
142
|
+
// get the entities we're streaming as a signal. we do it here rather than
|
|
143
|
+
// using the firestore stream so that we can always get the latest version
|
|
144
|
+
// without needing to multicast the original stream to all future components
|
|
145
|
+
// querying for the stream
|
|
146
|
+
const streamEntities = computed(() => {
|
|
147
|
+
return store.selectEntities(queryParams, queryOptions);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// convert to an observable, convert to the changes, then subscribe
|
|
151
|
+
// note: we do not need takeUntil for unsubscribing because toObservable will
|
|
152
|
+
// unsubscribe once the injector context (passed in from the component/container) is destroyed
|
|
153
|
+
toObservable(streamEntities, { injector }).pipe(
|
|
154
|
+
// convert to entityMap to more easily compare
|
|
155
|
+
map((entities) => {
|
|
156
|
+
const entityMap = {};
|
|
157
|
+
for (const entity of entities) {
|
|
158
|
+
entityMap[entity.__id] = entity;
|
|
159
|
+
}
|
|
160
|
+
return entityMap;
|
|
161
|
+
}),
|
|
162
|
+
// compare current with prior including the first
|
|
163
|
+
startWith({}),
|
|
164
|
+
pairwise(),
|
|
165
|
+
// get the changedEntities
|
|
166
|
+
map(([prevEntities, currEntities]) => {
|
|
167
|
+
const changedEntities = [];
|
|
168
|
+
for (const key in currEntities) {
|
|
169
|
+
if (!(key in prevEntities)) {
|
|
170
|
+
// the entity was added
|
|
171
|
+
changedEntities.push({
|
|
172
|
+
type: 'added',
|
|
173
|
+
doc: currEntities[key],
|
|
174
|
+
});
|
|
175
|
+
} else if (currEntities[key]['_deleted']) {
|
|
176
|
+
// the entity was removed
|
|
177
|
+
changedEntities.push({
|
|
178
|
+
type: 'removed',
|
|
179
|
+
doc: currEntities[key],
|
|
180
|
+
});
|
|
181
|
+
} else if (currEntities[key]['_updatedAt'] !== prevEntities[key]['_updatedAt']) {
|
|
182
|
+
// the entity was modified
|
|
183
|
+
changedEntities.push({
|
|
184
|
+
type: 'modified',
|
|
185
|
+
doc: currEntities[key],
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return changedEntities;
|
|
191
|
+
}),
|
|
192
|
+
// We don't need the removed ones for nested streamQueries (but I just
|
|
193
|
+
// included it above for debugging purposes so we can see all changes)
|
|
194
|
+
map((changes) => changes.filter((c) => c.type !== 'removed')),
|
|
195
|
+
filter((changes) => changes.length > 0),
|
|
196
|
+
).subscribe(async (changes) => {
|
|
197
|
+
// create a matrix of queries, each row corresponding to a given entity
|
|
198
|
+
const queriesByEntity = changes.map((change) => streamQueries(change.doc));
|
|
199
|
+
|
|
200
|
+
// transpose the matrix so each row corresponds to all queries for the same query type
|
|
201
|
+
const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
|
|
202
|
+
|
|
203
|
+
// Process all query types concurrently
|
|
204
|
+
await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
|
|
205
|
+
// Seeing if we can optimize by collapsing equality queries into 'in' queries
|
|
206
|
+
const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);
|
|
207
|
+
|
|
208
|
+
// Process queries concurrently using Promise.all
|
|
209
|
+
await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
|
|
210
|
+
await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, {
|
|
211
|
+
loading: options?.loading,
|
|
212
|
+
});
|
|
213
|
+
}));
|
|
214
|
+
}));
|
|
215
|
+
});
|
|
216
|
+
} else {
|
|
217
|
+
// We'll turn off the loading indicator the first time there is a query that doesn't have nested queries
|
|
218
|
+
// (ideally we'd want to turn if off after each of the streams have gotten their first entities, but I
|
|
219
|
+
// don't think we can do that easily and this won't be too off)
|
|
220
|
+
options?.loading?.set(false);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return connection;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private createConnection<T>(collection: string, store, queryParams: QueryParams, queryOptions: QueryOptions, destroyRef: DestroyRef): CachedConnection {
|
|
227
|
+
// console.log("CONNECT " + this.getQueryKey(collection, queryParams, queryOptions));
|
|
228
|
+
|
|
229
|
+
// ------------ DEFINE OBSERVABLES FOR DISCONNECTING ------------------------------
|
|
230
|
+
|
|
231
|
+
const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
|
|
232
|
+
const disconnectObs$ = this.closeConnection$.pipe(
|
|
233
|
+
filter((qk) => qk === queryKey),
|
|
234
|
+
take(1),
|
|
235
|
+
// tap(a => { console.log("DISCONNECT: " + queryKey) }),
|
|
236
|
+
publish(),
|
|
237
|
+
refCount(),
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
// ------------ HANDLE PATCHING TO STORE ------------------------------------------
|
|
241
|
+
|
|
242
|
+
// Handle patching to the store
|
|
243
|
+
this.db.streamEntitiesChanges(collection, queryParams, queryOptions).pipe(
|
|
244
|
+
takeUntil(disconnectObs$),
|
|
245
|
+
).subscribe((fbPayload: Array<{ type: string, docData: AnyEntity }>) => {
|
|
246
|
+
// Handle all the added entities
|
|
247
|
+
const entitiesToAdd = fbPayload
|
|
248
|
+
.filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])
|
|
249
|
+
.map((dc) => dc.docData);
|
|
250
|
+
|
|
251
|
+
// Handle all the modified entities
|
|
252
|
+
const entitiesToModify = fbPayload
|
|
253
|
+
.filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])
|
|
254
|
+
.map((dc) => dc.docData);
|
|
255
|
+
|
|
256
|
+
// Handle all the removed entities
|
|
257
|
+
const entitiesToRemove = fbPayload
|
|
258
|
+
.filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])
|
|
259
|
+
.map((dc) => dc.docData['__id']);
|
|
260
|
+
|
|
261
|
+
// Handle changes of the 'removed' type. In general, firebase 'removed'
|
|
262
|
+
// could be due to no longer matching the stream query rather than being
|
|
263
|
+
// deleted from the DB. this is why we use soft deletes (set _deleted to true)
|
|
264
|
+
// so technically we shouldn't be getting any 'removed' entries. however,
|
|
265
|
+
// if there were manual deletions in the database, there could still be changes
|
|
266
|
+
// of this type which the below code seeks to handle
|
|
267
|
+
const entitiesToModify2 = fbPayload
|
|
268
|
+
.filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, queryOptions))
|
|
269
|
+
.map((dc) => dc.docData);
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
const entitiesToRemove2 = fbPayload
|
|
273
|
+
.filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, queryOptions))
|
|
274
|
+
.map((dc) => dc.docData['__id']);
|
|
275
|
+
|
|
276
|
+
// Patch all the changes to the store
|
|
277
|
+
patchState(store, setEntities(entitiesToAdd, { selectId }));
|
|
278
|
+
patchState(store, setEntities([...entitiesToModify, ...entitiesToModify2], { selectId }));
|
|
279
|
+
patchState(store, removeEntities([...entitiesToRemove, ...entitiesToRemove2]));
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
return {
|
|
283
|
+
queryKey: this.getQueryKey(collection, queryParams, queryOptions),
|
|
284
|
+
registeredSet: new Set<DestroyRef>([destroyRef]),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
constructor(
|
|
289
|
+
@Inject(DATABASE_SERVICE) private db: DatabaseService,
|
|
290
|
+
) { }
|
|
291
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { InjectionToken, Injector } from '@angular/core';
|
|
2
|
+
import { QueryParams, QueryOptions, AnyEntity } from '../store/app.model';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { User } from '@angular/fire/auth';
|
|
5
|
+
import { WriteBatchI } from '../store/batch-write.service';
|
|
6
|
+
|
|
7
|
+
export interface DatabaseService {
|
|
8
|
+
createId(): string;
|
|
9
|
+
afUser(): Observable<{ uid: string, email: string, displayName: string, photoURL: string }>;
|
|
10
|
+
login(providerId: string, scope?: string): any;
|
|
11
|
+
loginLink(error): void;
|
|
12
|
+
logout(): any;
|
|
13
|
+
streamEntity<T>(collectionName: string, id: string): Observable<T>;
|
|
14
|
+
streamEntities<T>(collectionName, queryParams, queryOptions?): Observable<T[]>;
|
|
15
|
+
streamEntitiesChanges<T>(collectionName, queryParams, queryOptions?): Observable<{
|
|
16
|
+
type: string;
|
|
17
|
+
docData: T;
|
|
18
|
+
}[]>;
|
|
19
|
+
getEntity<T>(collectionName: string, id: string): Promise<T>;
|
|
20
|
+
getEntities<S>(
|
|
21
|
+
collectionName: string,
|
|
22
|
+
queryParams: [string, string, any][],
|
|
23
|
+
queryOptions?: { [index: string]: any },
|
|
24
|
+
): Promise<S[]>;
|
|
25
|
+
count(
|
|
26
|
+
collectionName: string,
|
|
27
|
+
queryParams: QueryParams,
|
|
28
|
+
queryOptions?: QueryOptions,
|
|
29
|
+
): Promise<number>;
|
|
30
|
+
aggregate<S extends { [k: string]: number }>(
|
|
31
|
+
collectionName: string,
|
|
32
|
+
queryParams: QueryParams,
|
|
33
|
+
queryOptions: QueryOptions,
|
|
34
|
+
aggregateParams: { [K in keyof S]: [string] | [string, string] },
|
|
35
|
+
): Promise<{ [K in keyof S]: number }>;
|
|
36
|
+
addEntity(
|
|
37
|
+
collectionName: string,
|
|
38
|
+
entity: AnyEntity,
|
|
39
|
+
batch?: WriteBatchI,
|
|
40
|
+
): Promise<any>;
|
|
41
|
+
updateEntity(
|
|
42
|
+
collectionName: string,
|
|
43
|
+
id: string,
|
|
44
|
+
changes: Partial<AnyEntity>,
|
|
45
|
+
batch?: WriteBatchI,
|
|
46
|
+
): Promise<any>;
|
|
47
|
+
removeEntity(
|
|
48
|
+
collectionName: string,
|
|
49
|
+
id: string,
|
|
50
|
+
batch?: WriteBatchI,
|
|
51
|
+
): Promise<any>;
|
|
52
|
+
incrementEntityField(collectionName, id, field, delta): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// InjectionToken that can be swapped out for
|
|
56
|
+
export const DATABASE_SERVICE = new InjectionToken<DatabaseService>('DatabaseService');
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { Injectable, inject, Injector, computed } from '@angular/core';
|
|
2
|
+
import { toObservable } from '@angular/core/rxjs-interop';
|
|
3
|
+
import { Observable, combineLatest, merge, of, from, pipe } from 'rxjs';
|
|
4
|
+
import { tap, pluck, mergeMap, pairwise, delay, startWith, filter, takeUntil, skip, switchMap, map, take } from 'rxjs/operators';
|
|
5
|
+
import { environment } from '../../../environments/environment';
|
|
6
|
+
import { DocumentSnapshot, serverTimestamp, Timestamp, getDoc, getDocs, doc, setDoc, updateDoc, deleteDoc, docData, collection, collectionData, collectionChanges, query, where, orderBy, OrderByDirection, limit, startAt, startAfter, endAt, endBefore, DocumentChange, increment, AggregateQuerySnapshot, AggregateField, AggregateSpec, getAggregateFromServer, getCountFromServer } from '@angular/fire/firestore';
|
|
7
|
+
import { AnyEntity, QueryParams, QueryOptions } from '../store/app.model';
|
|
8
|
+
import { DatabaseService } from './database.service';
|
|
9
|
+
import { SelectEntityId, setAllEntities } from '@ngrx/signals/entities';
|
|
10
|
+
import { patchState } from '@ngrx/signals';
|
|
11
|
+
import { AuthMockDB } from '../store/auth/auth.mock';
|
|
12
|
+
|
|
13
|
+
// Entity Model DB Data
|
|
14
|
+
import { UserMockDB, USER_DB } from '../store/user/user.mock';
|
|
15
|
+
import { UserContextMockDB, USERCONTEXT_DB } from '../store/user-context/user-context.mock';
|
|
16
|
+
|
|
17
|
+
const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
|
|
18
|
+
|
|
19
|
+
@Injectable({
|
|
20
|
+
providedIn: 'root',
|
|
21
|
+
})
|
|
22
|
+
export class FirebaseMockService implements DatabaseService {
|
|
23
|
+
readonly authDB = inject(AuthMockDB);
|
|
24
|
+
readonly DB = {
|
|
25
|
+
'users': inject(UserMockDB),
|
|
26
|
+
'userContexts': inject(UserContextMockDB),
|
|
27
|
+
};
|
|
28
|
+
private user$ = toObservable(this.authDB.user);
|
|
29
|
+
|
|
30
|
+
// Constant for simulating delay (e.g. to see loading icon in action)
|
|
31
|
+
GET_LATENCY_SIMULATION_DELAY = 100;
|
|
32
|
+
PUT_LATENCY_SIMULATION_DELAY = 300;
|
|
33
|
+
|
|
34
|
+
constructor(
|
|
35
|
+
private injector: Injector,
|
|
36
|
+
) {
|
|
37
|
+
// Init Entity Models
|
|
38
|
+
patchState(this.DB['users'], setAllEntities(USER_DB, { selectId }));
|
|
39
|
+
patchState(this.DB['userContexts'], setAllEntities(USERCONTEXT_DB, { selectId }));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Creates a unique id */
|
|
43
|
+
createId(): string {
|
|
44
|
+
// see https://stackoverflow.com/questions/56574593/access-firestore-id-generator-on-the-front-end?noredirect=1&lq=1
|
|
45
|
+
// see https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36
|
|
46
|
+
// Alphanumeric characters
|
|
47
|
+
const chars =
|
|
48
|
+
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
49
|
+
let autoId = '';
|
|
50
|
+
for (let i = 0; i < 20; i++) {
|
|
51
|
+
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
|
|
52
|
+
}
|
|
53
|
+
return autoId;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
afUser(): Observable<{ uid: string, accessToken: string, email: string, displayName: string, photoURL: string }> {
|
|
57
|
+
return this.user$;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async login(providerId, scope?: string): Promise<any> {
|
|
61
|
+
this.authDB.login();
|
|
62
|
+
return {
|
|
63
|
+
user: {
|
|
64
|
+
uid: USER_DB[0].__id,
|
|
65
|
+
email: USER_DB[0].email,
|
|
66
|
+
displayName: USER_DB[0].name,
|
|
67
|
+
photoURL: USER_DB[0].photoURL,
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
loginLink(error) { }
|
|
73
|
+
|
|
74
|
+
logout() {
|
|
75
|
+
this.authDB.logout();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
streamEntity<T>(collectionName: string, id: string) {
|
|
79
|
+
const store = this.DB[collectionName];
|
|
80
|
+
const entity = computed(() => {
|
|
81
|
+
return store.selectEntity(id);
|
|
82
|
+
});
|
|
83
|
+
return toObservable(entity, { injector: this.injector }).pipe(
|
|
84
|
+
delay(this.GET_LATENCY_SIMULATION_DELAY),
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
streamEntities<T>(collectionName, queryParams, queryOptions) {
|
|
89
|
+
const store = this.DB[collectionName];
|
|
90
|
+
const entities = computed(() => {
|
|
91
|
+
return store.selectEntities(queryParams, queryOptions);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
return toObservable(entities, { injector: this.injector }).pipe(
|
|
95
|
+
delay(this.GET_LATENCY_SIMULATION_DELAY),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
streamEntitiesChanges<T>(collectionName, queryParams, queryOptions) {
|
|
100
|
+
const store = this.DB[collectionName];
|
|
101
|
+
const streamEntities = computed(() => {
|
|
102
|
+
return store.selectEntities(queryParams, queryOptions);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
return toObservable(streamEntities, { injector: this.injector }).pipe(
|
|
106
|
+
// convert to entityMap to more easily compare
|
|
107
|
+
map((entities) => {
|
|
108
|
+
const entityMap = {};
|
|
109
|
+
for (const entity of entities) {
|
|
110
|
+
entityMap[entity.__id] = entity;
|
|
111
|
+
}
|
|
112
|
+
return entityMap;
|
|
113
|
+
}),
|
|
114
|
+
// compare current with prior including the first
|
|
115
|
+
startWith({}),
|
|
116
|
+
pairwise(),
|
|
117
|
+
// get the changedEntities
|
|
118
|
+
map(([prevEntities, currEntities]) => {
|
|
119
|
+
const changedEntities = [];
|
|
120
|
+
for (const key in currEntities) {
|
|
121
|
+
if (!(key in prevEntities)) {
|
|
122
|
+
// the entity was added
|
|
123
|
+
changedEntities.push({
|
|
124
|
+
type: 'added',
|
|
125
|
+
docData: currEntities[key],
|
|
126
|
+
});
|
|
127
|
+
} else if (currEntities[key]['_deleted']) {
|
|
128
|
+
// the entity was removed
|
|
129
|
+
changedEntities.push({
|
|
130
|
+
type: 'removed',
|
|
131
|
+
docData: currEntities[key],
|
|
132
|
+
});
|
|
133
|
+
} else if (currEntities[key]['_updatedAt'] !== prevEntities[key]['_updatedAt']) {
|
|
134
|
+
// the entity was modified
|
|
135
|
+
changedEntities.push({
|
|
136
|
+
type: 'modified',
|
|
137
|
+
docData: currEntities[key],
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return changedEntities;
|
|
143
|
+
}),
|
|
144
|
+
filter((changes: Array<{ type: string, docData: T }>) => changes.length > 0),
|
|
145
|
+
delay(this.GET_LATENCY_SIMULATION_DELAY),
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async getEntity<T>(collectionName: string, id: string) {
|
|
150
|
+
const store = this.DB[collectionName];
|
|
151
|
+
await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
|
|
152
|
+
return store.selectEntity(id);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async getEntities<S>(
|
|
156
|
+
collectionName: string,
|
|
157
|
+
queryParams: [string, string, any][],
|
|
158
|
+
queryOptions?: { [index: string]: any },
|
|
159
|
+
): Promise<S[]> {
|
|
160
|
+
const db = this.DB[collectionName];
|
|
161
|
+
await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
|
|
162
|
+
return db.selectEntities(queryParams, queryOptions);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async count(
|
|
166
|
+
collectionName: string,
|
|
167
|
+
queryParams: QueryParams,
|
|
168
|
+
queryOptions?: QueryOptions,
|
|
169
|
+
): Promise<number> {
|
|
170
|
+
const result = await this.aggregate(collectionName, queryParams, queryOptions, {
|
|
171
|
+
count: ['count'],
|
|
172
|
+
});
|
|
173
|
+
await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
|
|
174
|
+
return result['count'];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/*
|
|
178
|
+
* Example of aggregateSpec
|
|
179
|
+
* {
|
|
180
|
+
* countOfDocs: ['count'],
|
|
181
|
+
* totalPopulation: ['sum', 'population'],
|
|
182
|
+
* averagePopulation: ['average', 'population'],
|
|
183
|
+
* }
|
|
184
|
+
*/
|
|
185
|
+
async aggregate<S extends { [k: string]: number }>(
|
|
186
|
+
collectionName: string,
|
|
187
|
+
queryParams: QueryParams,
|
|
188
|
+
queryOptions: QueryOptions,
|
|
189
|
+
aggregateSpec: { [K in keyof S]: [string] | [string, string] },
|
|
190
|
+
): Promise<{ [K in keyof S]: number }> {
|
|
191
|
+
const store = this.DB[collectionName];
|
|
192
|
+
const entities = store.selectEntities(queryParams, queryOptions);
|
|
193
|
+
const result: Partial<{ [K in keyof S]: number }> = {};
|
|
194
|
+
for (const key in aggregateSpec) {
|
|
195
|
+
if (Object.prototype.hasOwnProperty.call(aggregateSpec, key)) {
|
|
196
|
+
const value = aggregateSpec[key];
|
|
197
|
+
|
|
198
|
+
if (value[0] === 'count') {
|
|
199
|
+
result[key] = entities.length;
|
|
200
|
+
} else if (value[0] === 'sum') {
|
|
201
|
+
result[key] = entities.reduce((s, e) => s + e[value[1]], 0);
|
|
202
|
+
} else if (value[0] === 'average') {
|
|
203
|
+
result[key] = entities.reduce((s, e) => s + e[value[1]], 0)/entities.length;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
await new Promise((resolve) => setTimeout(resolve, this.GET_LATENCY_SIMULATION_DELAY));
|
|
208
|
+
return result as { [K in keyof S]: number };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async addEntity(collectionName, entity, batch?) {
|
|
212
|
+
const store = this.DB[collectionName];
|
|
213
|
+
const entityFinal = Object.assign({}, entity, {
|
|
214
|
+
_createdAt: Timestamp.now(),
|
|
215
|
+
_updatedAt: Timestamp.now(),
|
|
216
|
+
_deleted: false,
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
if (batch) {
|
|
220
|
+
const docRef = {
|
|
221
|
+
path: `${collectionName}/${entity.__id}`
|
|
222
|
+
};
|
|
223
|
+
return batch.set(docRef, entityFinal);
|
|
224
|
+
} else {
|
|
225
|
+
await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
|
|
226
|
+
return store.add(entityFinal);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async updateEntity(collectionName, id, changes, batch?) {
|
|
231
|
+
const store = this.DB[collectionName];
|
|
232
|
+
const changesFinal = Object.assign({}, changes, {
|
|
233
|
+
_updatedAt: Timestamp.now(),
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
if (batch) {
|
|
237
|
+
const docRef = {
|
|
238
|
+
path: `${collectionName}/${id}`
|
|
239
|
+
};
|
|
240
|
+
return batch.update(docRef, changesFinal);
|
|
241
|
+
} else {
|
|
242
|
+
await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
|
|
243
|
+
return store.update(id, changesFinal);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async removeEntity(collectionName, id, batch?) {
|
|
248
|
+
const store = this.DB[collectionName];
|
|
249
|
+
const changes = {
|
|
250
|
+
_updatedAt: Timestamp.now(),
|
|
251
|
+
_deleted: true,
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
if (batch) {
|
|
255
|
+
const docRef = {
|
|
256
|
+
path: `${collectionName}/${id}`
|
|
257
|
+
};
|
|
258
|
+
return batch.update(docRef, changes);
|
|
259
|
+
} else {
|
|
260
|
+
await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
|
|
261
|
+
return store.update(id, changes);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async incrementEntityField(collectionName, id, field, delta) {
|
|
266
|
+
const store = this.DB[collectionName];
|
|
267
|
+
const entity = store.selectEntity(id);
|
|
268
|
+
const changes = {
|
|
269
|
+
_updatedAt: Timestamp.now(),
|
|
270
|
+
};
|
|
271
|
+
changes[field] = entity[field] + delta;
|
|
272
|
+
|
|
273
|
+
await new Promise((resolve) => setTimeout(resolve, this.PUT_LATENCY_SIMULATION_DELAY));
|
|
274
|
+
return await store.update(id, changes);
|
|
275
|
+
}
|
|
276
|
+
}
|