@tech4good/angular-schematics 17.0.3 → 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 +28 -29
- 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 -149
- 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,1074 @@
|
|
|
1
|
+
import { WritableSignal, inject } from '@angular/core';
|
|
2
|
+
import { Timestamp, writeBatch } from '@angular/fire/firestore';
|
|
3
|
+
import { patchState, signalStoreFeature, withMethods } from '@ngrx/signals';
|
|
4
|
+
import { removeEntities, removeEntity, setEntities, setEntity, updateEntity, withEntities } from '@ngrx/signals/entities';
|
|
5
|
+
import { EntityChanges, EntityId, SelectEntityId } from '@ngrx/signals/entities/src/models';
|
|
6
|
+
import { CachedListenersService } from '../firebase/cached-listeners.service';
|
|
7
|
+
import { DATABASE_SERVICE, DatabaseService } from '../firebase/database.service';
|
|
8
|
+
import { AnyEntity, QueryOptions, QueryParams } from './app.model';
|
|
9
|
+
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
|
|
10
|
+
import { WriteBatchI } from './batch-write.service';
|
|
11
|
+
|
|
12
|
+
const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
|
|
13
|
+
|
|
14
|
+
export function openSnackBarWithUndoOption(
|
|
15
|
+
snackBar: MatSnackBar,
|
|
16
|
+
snackBarConfig: {
|
|
17
|
+
successMessage: string,
|
|
18
|
+
failureMessage: string,
|
|
19
|
+
undoOnAction?: boolean,
|
|
20
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
21
|
+
config?: MatSnackBarConfig<any>,
|
|
22
|
+
},
|
|
23
|
+
revertFns: Array<() => void>,
|
|
24
|
+
dbRevertFns: Array<() => void>,
|
|
25
|
+
revertBatch?: WriteBatchI,
|
|
26
|
+
) {
|
|
27
|
+
const snackBarRef = snackBar.open(
|
|
28
|
+
snackBarConfig.successMessage,
|
|
29
|
+
snackBarConfig.undoOnAction ? 'Undo' : '',
|
|
30
|
+
snackBarConfig.config,
|
|
31
|
+
);
|
|
32
|
+
// if there is an undo option for the snackbar, then we should
|
|
33
|
+
// revert both local and database changes if the undo was clicked
|
|
34
|
+
if (snackBarConfig.undoOnAction) {
|
|
35
|
+
snackBarRef.onAction().subscribe(async () => {
|
|
36
|
+
try {
|
|
37
|
+
// first try to undo changes on the database
|
|
38
|
+
// dbRevertFns will directly remove from DB if not in the batch setting.
|
|
39
|
+
// if it is a batch setting, it will do revertBatch.set to prepare
|
|
40
|
+
// revertBatch for a commit
|
|
41
|
+
await Promise.all(dbRevertFns.map((dbRevertFn) => dbRevertFn()));
|
|
42
|
+
if (revertBatch) {
|
|
43
|
+
await revertBatch.commit();
|
|
44
|
+
}
|
|
45
|
+
// if successful, then undo changes locally too
|
|
46
|
+
revertFns.forEach((revertFn) => revertFn());
|
|
47
|
+
} catch (e) {
|
|
48
|
+
console.error(e);
|
|
49
|
+
snackBar.open('Failed to undo', '', {
|
|
50
|
+
duration: 3000,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function withEntitiesAndSelectMethods<S extends AnyEntity>() {
|
|
58
|
+
return signalStoreFeature(
|
|
59
|
+
withEntities<S>(),
|
|
60
|
+
withMethods((store) => ({
|
|
61
|
+
selectEntity(id: string): S {
|
|
62
|
+
const result = store.entityMap()[id];
|
|
63
|
+
|
|
64
|
+
if (result && !result['_deleted']) {
|
|
65
|
+
return result;
|
|
66
|
+
} else {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S {
|
|
71
|
+
// Note: selectEntities already filters out _deleted
|
|
72
|
+
const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
|
|
73
|
+
if (entities && entities.length > 0) {
|
|
74
|
+
return entities[0];
|
|
75
|
+
} else {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {
|
|
80
|
+
// Note: selectEntities already filters out _deleted
|
|
81
|
+
return selectEntities<S>(store.entityMap(), queryParams, queryOptions);
|
|
82
|
+
},
|
|
83
|
+
})),
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function withEntitiesForMockDB<S extends AnyEntity>() {
|
|
88
|
+
return signalStoreFeature(
|
|
89
|
+
withEntitiesAndSelectMethods<S>(),
|
|
90
|
+
withMethods((store) => ({
|
|
91
|
+
add(entity: S) {
|
|
92
|
+
patchState(store, setEntity<S>(entity, { selectId }));
|
|
93
|
+
},
|
|
94
|
+
update(id: string, changes: Partial<S>) {
|
|
95
|
+
patchState(store, updateEntity({ id, changes }, { selectId }));
|
|
96
|
+
},
|
|
97
|
+
})),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: string) {
|
|
103
|
+
return signalStoreFeature(
|
|
104
|
+
withEntitiesAndSelectMethods<S>(),
|
|
105
|
+
withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATABASE_SERVICE), snackBar = inject(MatSnackBar)) => ({
|
|
106
|
+
// streaming tries to reduce redundant loads through the following:
|
|
107
|
+
// - caching listeners and reusing them with a 5-second delay after moving to a new container before unsubscribing
|
|
108
|
+
// additionally, it has the following constraints:
|
|
109
|
+
// - nested loadQueries are only loaded, not streamed, to prevent huge numbers of listeners.
|
|
110
|
+
// - nested loadQueries can only be made based on the id of retrieved entities to ensure we only need to replay loads/adds
|
|
111
|
+
// - containers pass in an id for loads, then onDestroy, they call cachedListeners.disconnect(id)
|
|
112
|
+
async stream(
|
|
113
|
+
queryParams: QueryParams,
|
|
114
|
+
queryOptions: QueryOptions,
|
|
115
|
+
injector,
|
|
116
|
+
streamQueries?: (entity: S) => EntityStreamQuery<AnyEntity>[],
|
|
117
|
+
options?: {
|
|
118
|
+
loading?: WritableSignal<boolean>, // set to true on start, set to false once all are complete
|
|
119
|
+
},
|
|
120
|
+
) {
|
|
121
|
+
try {
|
|
122
|
+
// start loading icon if available
|
|
123
|
+
options?.loading?.set(true);
|
|
124
|
+
|
|
125
|
+
await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
|
|
126
|
+
} catch (e) {
|
|
127
|
+
console.error(e);
|
|
128
|
+
|
|
129
|
+
// stop loading icon. when no error, loading icon is stopped
|
|
130
|
+
// upon the initial payload coming through the stream and the
|
|
131
|
+
// loadQueries being processed
|
|
132
|
+
options?.loading?.set(false);
|
|
133
|
+
throw e;
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
// loading tries to reduce redundant loads through the following:
|
|
137
|
+
// - below only applies when there are no queryOptions
|
|
138
|
+
// - only loads (not deleted) entities since the last time this query was made and when there is not already an active stream for that
|
|
139
|
+
// - delete entities since the last load where _deleted is true and when there is not already an active stream for that (which would handle deletions too)
|
|
140
|
+
// - to calculate loadQueries, use the entities within the store (to get both the deltas and the things already loaded)
|
|
141
|
+
async load(
|
|
142
|
+
queryParams: QueryParams,
|
|
143
|
+
queryOptions: QueryOptions,
|
|
144
|
+
loadQueries?: (entity: S) => EntityLoadQuery<AnyEntity>[],
|
|
145
|
+
options?: {
|
|
146
|
+
loading?: WritableSignal<boolean>,
|
|
147
|
+
},
|
|
148
|
+
) {
|
|
149
|
+
try {
|
|
150
|
+
// start loading icon if available
|
|
151
|
+
options?.loading?.set(true);
|
|
152
|
+
|
|
153
|
+
// only load if there is not already a listener for the same query
|
|
154
|
+
if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
|
|
155
|
+
// get the last load time and next load time
|
|
156
|
+
const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
|
|
157
|
+
const newLoadTime = Timestamp.now().toMillis();
|
|
158
|
+
|
|
159
|
+
// load entities since last load that are not deleted
|
|
160
|
+
// note that we always load all entities if there exist queryOptions since adding
|
|
161
|
+
// the _updatedAt filter will change queries with limit
|
|
162
|
+
let queryParamsWithTime;
|
|
163
|
+
if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
|
|
164
|
+
queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
|
|
165
|
+
} else {
|
|
166
|
+
queryParamsWithTime = [
|
|
167
|
+
...queryParams,
|
|
168
|
+
['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
|
|
169
|
+
['_deleted', '==', false],
|
|
170
|
+
];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// get entities that have been added or updated since last load
|
|
174
|
+
const entitiesDelta: S[] = await db.getEntities(
|
|
175
|
+
collectionName,
|
|
176
|
+
queryParamsWithTime,
|
|
177
|
+
queryOptions,
|
|
178
|
+
);
|
|
179
|
+
patchState(store, setEntities<S>(entitiesDelta, { selectId }));
|
|
180
|
+
|
|
181
|
+
// delete any new deleted entities
|
|
182
|
+
if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
|
|
183
|
+
const entitiesDeletedDelta: S[] = await db.getEntities(
|
|
184
|
+
collectionName,
|
|
185
|
+
[...queryParams, ['_deleted', '==', true]],
|
|
186
|
+
queryOptions,
|
|
187
|
+
);
|
|
188
|
+
patchState(store, removeEntities(
|
|
189
|
+
entitiesDeletedDelta.map((e) => e.__id),
|
|
190
|
+
));
|
|
191
|
+
} else {
|
|
192
|
+
const entitiesDeletedDelta: S[] = await db.getEntities(
|
|
193
|
+
collectionName,
|
|
194
|
+
[...queryParams,
|
|
195
|
+
['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
|
|
196
|
+
['_deleted', '==', true]],
|
|
197
|
+
queryOptions,
|
|
198
|
+
);
|
|
199
|
+
patchState(store, removeEntities(
|
|
200
|
+
entitiesDeletedDelta.map((e) => e.__id),
|
|
201
|
+
));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// save a new lastLoadTime for this query
|
|
205
|
+
cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (loadQueries) {
|
|
209
|
+
// retrieve entities from store for loading queries
|
|
210
|
+
// note we cannot simply use entities from load since it may not be all entities (only those for which updatedAt > lastLoadTime)
|
|
211
|
+
const allQueriedEntities = store.selectEntities(queryParams, queryOptions);
|
|
212
|
+
await processLoadQueries<S>(allQueriedEntities, loadQueries);
|
|
213
|
+
}
|
|
214
|
+
} catch (e) {
|
|
215
|
+
console.error(e);
|
|
216
|
+
throw e;
|
|
217
|
+
} finally {
|
|
218
|
+
// stop loading icon
|
|
219
|
+
options?.loading?.set(false);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
async count(
|
|
223
|
+
queryParams: QueryParams,
|
|
224
|
+
queryOptions: QueryOptions,
|
|
225
|
+
options?: {
|
|
226
|
+
loading?: WritableSignal<boolean>,
|
|
227
|
+
},
|
|
228
|
+
): Promise<number> {
|
|
229
|
+
try {
|
|
230
|
+
// start loading icon if available
|
|
231
|
+
options?.loading?.set(true);
|
|
232
|
+
|
|
233
|
+
const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
|
|
234
|
+
return await db.count(collectionName, queryParamsNotDeleted, queryOptions);
|
|
235
|
+
} catch (e) {
|
|
236
|
+
console.error(e);
|
|
237
|
+
throw e;
|
|
238
|
+
} finally {
|
|
239
|
+
// stop loading icon
|
|
240
|
+
options?.loading?.set(false);
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
async aggregate<T extends { [k: string]: number }>(
|
|
244
|
+
queryParams: QueryParams,
|
|
245
|
+
queryOptions: QueryOptions,
|
|
246
|
+
aggregateParams: { [K in keyof T]: [string] | [string, string] },
|
|
247
|
+
options?: {
|
|
248
|
+
loading?: WritableSignal<boolean>,
|
|
249
|
+
},
|
|
250
|
+
): Promise<{ [K in keyof T]: number }> {
|
|
251
|
+
try {
|
|
252
|
+
// start loading icon if available
|
|
253
|
+
options?.loading?.set(true);
|
|
254
|
+
|
|
255
|
+
const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
|
|
256
|
+
return await db.aggregate<T>(
|
|
257
|
+
collectionName, queryParamsNotDeleted, queryOptions, aggregateParams,
|
|
258
|
+
);
|
|
259
|
+
} catch (e) {
|
|
260
|
+
console.error(e);
|
|
261
|
+
throw e;
|
|
262
|
+
} finally {
|
|
263
|
+
// stop loading icon
|
|
264
|
+
options?.loading?.set(false);
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
async increment(id: string, field: string, delta: number, options?: {
|
|
268
|
+
loading?: WritableSignal<boolean>,
|
|
269
|
+
optimistic?: boolean
|
|
270
|
+
}) {
|
|
271
|
+
// get current value
|
|
272
|
+
const currEntityValue = store.entityMap()[id];
|
|
273
|
+
const changes = {};
|
|
274
|
+
changes[field] = (currEntityValue[field] || 0) + delta;
|
|
275
|
+
changes['_updatedAt'] = Timestamp.now();
|
|
276
|
+
|
|
277
|
+
if (options?.optimistic) {
|
|
278
|
+
try {
|
|
279
|
+
// optimistically set then query backend
|
|
280
|
+
patchState(store, updateEntity({
|
|
281
|
+
id,
|
|
282
|
+
changes: Object.assign({}, changes, {
|
|
283
|
+
_updatedAt: Timestamp.now(),
|
|
284
|
+
}) as EntityChanges<NoInfer<S>>,
|
|
285
|
+
}, { selectId }));
|
|
286
|
+
await db.incrementEntityField(collectionName, id, field, delta);
|
|
287
|
+
} catch (e) {
|
|
288
|
+
// undo ngrx store value
|
|
289
|
+
if (currEntityValue) {
|
|
290
|
+
patchState(store, setEntity<S>(currEntityValue, { selectId }));
|
|
291
|
+
} else {
|
|
292
|
+
patchState(store, removeEntity(id));
|
|
293
|
+
}
|
|
294
|
+
console.error(e);
|
|
295
|
+
throw e;
|
|
296
|
+
}
|
|
297
|
+
} else {
|
|
298
|
+
try {
|
|
299
|
+
// start loading icon
|
|
300
|
+
options?.loading?.set(true);
|
|
301
|
+
|
|
302
|
+
// update entity
|
|
303
|
+
await db.incrementEntityField(collectionName, id, field, delta);
|
|
304
|
+
patchState(store, updateEntity({
|
|
305
|
+
id,
|
|
306
|
+
changes: Object.assign({}, changes, {
|
|
307
|
+
_updatedAt: Timestamp.now(),
|
|
308
|
+
}) as EntityChanges<NoInfer<S>>,
|
|
309
|
+
}, { selectId }));
|
|
310
|
+
} catch (e) {
|
|
311
|
+
console.error(e);
|
|
312
|
+
throw e;
|
|
313
|
+
} finally {
|
|
314
|
+
// stop loading icon
|
|
315
|
+
options?.loading?.set(false);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
async add(
|
|
320
|
+
entityOpId: S | Omit<S, '__id'>,
|
|
321
|
+
options?: {
|
|
322
|
+
optimistic?: boolean,
|
|
323
|
+
loading?: WritableSignal<boolean>,
|
|
324
|
+
snackBarConfig?: {
|
|
325
|
+
successMessage: string,
|
|
326
|
+
failureMessage: string,
|
|
327
|
+
undoOnAction?: boolean,
|
|
328
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
329
|
+
config?: MatSnackBarConfig<any>,
|
|
330
|
+
},
|
|
331
|
+
batchConfig?: {
|
|
332
|
+
batch: WriteBatchI,
|
|
333
|
+
revertBatch: WriteBatchI,
|
|
334
|
+
patchFns: Array<() => void>,
|
|
335
|
+
revertFns: Array<() => void>,
|
|
336
|
+
dbRevertFns: Array<() => void>,
|
|
337
|
+
optimistic?: boolean,
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
) {
|
|
341
|
+
// Create an __id if one was not provided
|
|
342
|
+
const entity: S = Object.assign({}, entityOpId, {
|
|
343
|
+
__id: entityOpId['__id'] || db.createId(),
|
|
344
|
+
}) as S;
|
|
345
|
+
|
|
346
|
+
// Function for setting the entity locally
|
|
347
|
+
const patchFn = () => {
|
|
348
|
+
patchState(store, setEntity<S>(
|
|
349
|
+
Object.assign({}, entity, {
|
|
350
|
+
_updatedAt: Timestamp.now(),
|
|
351
|
+
_createdAt: Timestamp.now(),
|
|
352
|
+
_deleted: false,
|
|
353
|
+
}),
|
|
354
|
+
{ selectId },
|
|
355
|
+
));
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// Function for reverting changes for optimistic adds
|
|
359
|
+
const currEntityValue = store.entityMap()[entity.__id];
|
|
360
|
+
const revertFn = () => {
|
|
361
|
+
if (currEntityValue) {
|
|
362
|
+
patchState(store, setEntity<S>(currEntityValue, { selectId }));
|
|
363
|
+
} else {
|
|
364
|
+
patchState(store, removeEntity(entity.__id));
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
// Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
|
|
369
|
+
const dbRevertFn = async () => {
|
|
370
|
+
try {
|
|
371
|
+
if (currEntityValue) {
|
|
372
|
+
await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
|
|
373
|
+
} else {
|
|
374
|
+
await db.removeEntity(collectionName, entity.__id, options?.batchConfig?.revertBatch);
|
|
375
|
+
}
|
|
376
|
+
} catch (e) {
|
|
377
|
+
console.error(e);
|
|
378
|
+
throw e;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
// Add the patchFn, revertFn, dbRevertFn if this is a batch write
|
|
383
|
+
options?.batchConfig?.patchFns?.push(patchFn);
|
|
384
|
+
options?.batchConfig?.revertFns?.push(revertFn);
|
|
385
|
+
options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
// optimistically set locally, then in backend and revert if needed
|
|
389
|
+
if (options?.optimistic || options?.batchConfig?.optimistic) {
|
|
390
|
+
patchFn();
|
|
391
|
+
try {
|
|
392
|
+
await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
|
|
393
|
+
// it will only go into here when not in a batch setting
|
|
394
|
+
// since there is no snackBarConfig in the a batch seting
|
|
395
|
+
if (options?.snackBarConfig) {
|
|
396
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
397
|
+
}
|
|
398
|
+
} catch (e) {
|
|
399
|
+
// will only get here when it's not a batch
|
|
400
|
+
revertFn();
|
|
401
|
+
console.error(e);
|
|
402
|
+
if (options?.snackBarConfig) {
|
|
403
|
+
snackBar.open(
|
|
404
|
+
options.snackBarConfig.failureMessage,
|
|
405
|
+
'',
|
|
406
|
+
options.snackBarConfig.config,
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
throw e;
|
|
410
|
+
}
|
|
411
|
+
// set in backend and then locally if successful
|
|
412
|
+
} else {
|
|
413
|
+
// start loading icon
|
|
414
|
+
options?.loading?.set(true);
|
|
415
|
+
try {
|
|
416
|
+
await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
|
|
417
|
+
// only patch if not using batch writes since if we're using
|
|
418
|
+
// batch writes, we should be patching after the batch write
|
|
419
|
+
// is successful
|
|
420
|
+
if (!options?.batchConfig?.batch) {
|
|
421
|
+
patchFn();
|
|
422
|
+
if (options?.snackBarConfig) {
|
|
423
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
} catch (e) {
|
|
427
|
+
console.error(e);
|
|
428
|
+
// will only get here when it's not a batch
|
|
429
|
+
if (options?.snackBarConfig) {
|
|
430
|
+
snackBar.open(
|
|
431
|
+
options.snackBarConfig.failureMessage,
|
|
432
|
+
'',
|
|
433
|
+
options.snackBarConfig.config,
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
throw e;
|
|
437
|
+
} finally {
|
|
438
|
+
// stop loading icon
|
|
439
|
+
options?.loading?.set(false);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
},
|
|
443
|
+
async update(
|
|
444
|
+
id: string,
|
|
445
|
+
changes: Partial<S>,
|
|
446
|
+
options?: {
|
|
447
|
+
optimistic?: boolean,
|
|
448
|
+
loading?: WritableSignal<boolean>,
|
|
449
|
+
snackBarConfig?: {
|
|
450
|
+
successMessage: string,
|
|
451
|
+
failureMessage: string,
|
|
452
|
+
undoOnAction?: boolean,
|
|
453
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
454
|
+
config?: MatSnackBarConfig<any>,
|
|
455
|
+
},
|
|
456
|
+
batchConfig?: {
|
|
457
|
+
batch: WriteBatchI,
|
|
458
|
+
revertBatch: WriteBatchI,
|
|
459
|
+
patchFns?: Array<() => void>,
|
|
460
|
+
revertFns: Array<() => void>,
|
|
461
|
+
dbRevertFns: Array<() => void>,
|
|
462
|
+
optimistic?: boolean,
|
|
463
|
+
}
|
|
464
|
+
},
|
|
465
|
+
) {
|
|
466
|
+
// Function for updating the entity locally
|
|
467
|
+
const patchFn = () => {
|
|
468
|
+
patchState(store, updateEntity({
|
|
469
|
+
id,
|
|
470
|
+
changes: Object.assign({}, changes, {
|
|
471
|
+
_updatedAt: Timestamp.now(),
|
|
472
|
+
}) as EntityChanges<NoInfer<S>>,
|
|
473
|
+
}, { selectId }));
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
// Function for reverting changes for optimistic updates
|
|
477
|
+
const currEntityValue = store.entityMap()[id];
|
|
478
|
+
const revertFn = () => {
|
|
479
|
+
if (currEntityValue) {
|
|
480
|
+
patchState(store, setEntity<S>(currEntityValue, { selectId }));
|
|
481
|
+
} else {
|
|
482
|
+
patchState(store, removeEntity(id));
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
|
|
486
|
+
// Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
|
|
487
|
+
const dbRevertFn = async () => {
|
|
488
|
+
try {
|
|
489
|
+
if (currEntityValue) {
|
|
490
|
+
await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
|
|
491
|
+
} else {
|
|
492
|
+
await db.removeEntity(collectionName, id, options?.batchConfig?.revertBatch);
|
|
493
|
+
}
|
|
494
|
+
} catch (e) {
|
|
495
|
+
console.error(e);
|
|
496
|
+
throw e;
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
// Add the patchFn, revertFn, dbRevertFn if this is a batch write
|
|
501
|
+
options?.batchConfig?.patchFns?.push(patchFn);
|
|
502
|
+
options?.batchConfig?.revertFns?.push(revertFn);
|
|
503
|
+
options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
|
|
504
|
+
|
|
505
|
+
// optimistically update locally, then in backend and revert if needed
|
|
506
|
+
if (options?.optimistic || options?.batchConfig?.optimistic) {
|
|
507
|
+
patchFn();
|
|
508
|
+
try {
|
|
509
|
+
await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
|
|
510
|
+
// it will only go into here when not in a batch setting
|
|
511
|
+
// since there is no snackBarConfig in the a batch seting
|
|
512
|
+
if (options?.snackBarConfig) {
|
|
513
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
514
|
+
}
|
|
515
|
+
} catch (e) {
|
|
516
|
+
// will only get here when it's not a batch
|
|
517
|
+
revertFn();
|
|
518
|
+
console.error(e);
|
|
519
|
+
if (options?.snackBarConfig) {
|
|
520
|
+
snackBar.open(
|
|
521
|
+
options.snackBarConfig.failureMessage,
|
|
522
|
+
'',
|
|
523
|
+
options.snackBarConfig.config,
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
throw e;
|
|
527
|
+
}
|
|
528
|
+
// update in backend and then locally if successful
|
|
529
|
+
} else {
|
|
530
|
+
// start loading icon
|
|
531
|
+
options?.loading?.set(true);
|
|
532
|
+
try {
|
|
533
|
+
await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
|
|
534
|
+
// only patch if not using batch writes since if we're using
|
|
535
|
+
// batch writes, we should be patching after the batch write
|
|
536
|
+
// is successful
|
|
537
|
+
if (!options?.batchConfig?.batch) {
|
|
538
|
+
patchFn();
|
|
539
|
+
if (options?.snackBarConfig) {
|
|
540
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
} catch (e) {
|
|
544
|
+
console.error(e);
|
|
545
|
+
// will only get here when it's not a batch
|
|
546
|
+
if (options?.snackBarConfig) {
|
|
547
|
+
snackBar.open(
|
|
548
|
+
options.snackBarConfig.failureMessage,
|
|
549
|
+
'',
|
|
550
|
+
options.snackBarConfig.config,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
throw e;
|
|
554
|
+
} finally {
|
|
555
|
+
// stop loading icon
|
|
556
|
+
options?.loading?.set(false);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
async remove(
|
|
561
|
+
id: string,
|
|
562
|
+
options?: {
|
|
563
|
+
optimistic?: boolean,
|
|
564
|
+
loading?: WritableSignal<boolean>,
|
|
565
|
+
snackBarConfig?: {
|
|
566
|
+
successMessage: string,
|
|
567
|
+
failureMessage: string,
|
|
568
|
+
undoOnAction?: boolean,
|
|
569
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
570
|
+
config?: MatSnackBarConfig<any>,
|
|
571
|
+
},
|
|
572
|
+
batchConfig?: {
|
|
573
|
+
batch: WriteBatchI,
|
|
574
|
+
revertBatch: WriteBatchI,
|
|
575
|
+
patchFns?: Array<() => void>,
|
|
576
|
+
revertFns: Array<() => void>,
|
|
577
|
+
dbRevertFns: Array<() => void>,
|
|
578
|
+
optimistic?: boolean,
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
) {
|
|
582
|
+
// Function for updating the entity locally
|
|
583
|
+
const patchFn = () => {
|
|
584
|
+
patchState(store, removeEntity(id));
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// Function for reverting changes for optimistic deletes
|
|
588
|
+
const currEntityValue = store.entityMap()[id];
|
|
589
|
+
const revertFn = () => {
|
|
590
|
+
if (currEntityValue) {
|
|
591
|
+
patchState(store, setEntity<S>(currEntityValue, { selectId }));
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
// Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
|
|
596
|
+
const dbRevertFn = async () => {
|
|
597
|
+
try {
|
|
598
|
+
if (currEntityValue) {
|
|
599
|
+
await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
|
|
600
|
+
}
|
|
601
|
+
} catch (e) {
|
|
602
|
+
console.error(e);
|
|
603
|
+
throw e;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
// Add the patchFn, revertFn, dbRevertFn if this is a batch write
|
|
608
|
+
options?.batchConfig?.patchFns?.push(patchFn);
|
|
609
|
+
options?.batchConfig?.revertFns?.push(revertFn);
|
|
610
|
+
options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
|
|
611
|
+
|
|
612
|
+
// optimistically remove locally, then in backend and revert if needed
|
|
613
|
+
if (options?.optimistic || options?.batchConfig?.optimistic) {
|
|
614
|
+
patchFn();
|
|
615
|
+
try {
|
|
616
|
+
await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
|
|
617
|
+
// it will only go into here when not in a batch setting
|
|
618
|
+
// since there is no snackBarConfig in the a batch seting
|
|
619
|
+
if (options?.snackBarConfig) {
|
|
620
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
621
|
+
}
|
|
622
|
+
} catch (e) {
|
|
623
|
+
// will only get here when it's not a batch
|
|
624
|
+
revertFn();
|
|
625
|
+
console.error(e);
|
|
626
|
+
if (options?.snackBarConfig) {
|
|
627
|
+
snackBar.open(
|
|
628
|
+
options.snackBarConfig.failureMessage,
|
|
629
|
+
'',
|
|
630
|
+
options.snackBarConfig.config,
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
throw e;
|
|
634
|
+
}
|
|
635
|
+
// update in backend and then locally if successful
|
|
636
|
+
} else {
|
|
637
|
+
// start loading icon
|
|
638
|
+
options?.loading?.set(true);
|
|
639
|
+
try {
|
|
640
|
+
await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
|
|
641
|
+
// only patch if not using batch writes since if we're using
|
|
642
|
+
// batch writes, we should be patching after the batch write
|
|
643
|
+
// is successful
|
|
644
|
+
if (!options?.batchConfig?.batch) {
|
|
645
|
+
patchFn();
|
|
646
|
+
if (options?.snackBarConfig) {
|
|
647
|
+
openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
} catch (e) {
|
|
651
|
+
console.error(e);
|
|
652
|
+
// will only get here when it's not a batch
|
|
653
|
+
if (options?.snackBarConfig) {
|
|
654
|
+
snackBar.open(
|
|
655
|
+
options.snackBarConfig.failureMessage,
|
|
656
|
+
'',
|
|
657
|
+
options.snackBarConfig.config,
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
throw e;
|
|
661
|
+
} finally {
|
|
662
|
+
// stop loading icon
|
|
663
|
+
options?.loading?.set(false);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
})),
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Select entities from store given the entityMap and queries.
|
|
673
|
+
* Filters out any entities that have '_deleted' === true. In general
|
|
674
|
+
* this shouldn't matter, but in case someone intentionally sets
|
|
675
|
+
* the _deleted parameter, this adds more robustness.
|
|
676
|
+
* Note: firestore supports setting and querying for null, but not
|
|
677
|
+
* undefined. We filter out cases where the value is undefined
|
|
678
|
+
* to protect against cases when people are doing a nested query
|
|
679
|
+
* and some entity does not have a particular field, e.g.
|
|
680
|
+
* [['__hashtagId', '==', q.__hashtagId]] when __hashtagId is
|
|
681
|
+
* an optional parameter
|
|
682
|
+
*/
|
|
683
|
+
export function selectEntities<T>(entityMap: Record<string, T>, queryParams: QueryParams, queryOptions: QueryOptions): T[] {
|
|
684
|
+
let filteredEntities = [];
|
|
685
|
+
|
|
686
|
+
// APPLY '__id', '=='/in FILTERS
|
|
687
|
+
const selectIdEqQueries = queryParams.filter((q) => q[0] === '__id' && q[1] === '==' && q[2] !== undefined);
|
|
688
|
+
const uniqSelectEqIds = selectIdEqQueries.map((q) => q[2]).filter((q, i, a) => a.indexOf(q) === i);
|
|
689
|
+
const selectIdInQueries = queryParams
|
|
690
|
+
.filter((q) => q[0] === '__id' && q[1] === 'in' && q[2] !== undefined)
|
|
691
|
+
.map((q) => [q[0], q[1], q[2].filter((v) => v !== undefined)])
|
|
692
|
+
.filter((q) => q[2].length > 0);
|
|
693
|
+
|
|
694
|
+
if (uniqSelectEqIds.length === 1 && entityMap[uniqSelectEqIds[0]] && !entityMap[uniqSelectEqIds[0]]['_deleted']) {
|
|
695
|
+
// If there is exactly one '__id', we can start with that to filter
|
|
696
|
+
filteredEntities.push(entityMap[uniqSelectEqIds[0]]);
|
|
697
|
+
} else if (uniqSelectEqIds.length > 1) {
|
|
698
|
+
// If there are more than one select id ==, then there cannot be any matches
|
|
699
|
+
return [];
|
|
700
|
+
} else if (selectIdInQueries.length > 0) {
|
|
701
|
+
// If there is at least one 'in' query, start with that.
|
|
702
|
+
const firstInIds = selectIdInQueries[0][2];
|
|
703
|
+
filteredEntities = firstInIds.map((id) => entityMap[id]).filter((e) => e && !e['_deleted']);
|
|
704
|
+
|
|
705
|
+
// Then apply remaining 'in' filters. See general filter section
|
|
706
|
+
// for comments since this is just copied from that.
|
|
707
|
+
if (selectIdInQueries.length > 1) {
|
|
708
|
+
filteredEntities = filteredEntities.filter((e) => {
|
|
709
|
+
return !selectIdInQueries.slice(1).find((f) => {
|
|
710
|
+
const [key, rel, val] = f;
|
|
711
|
+
return !(val.includes(e[key]));
|
|
712
|
+
});
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
} else {
|
|
716
|
+
// Otherwise, start with the full list and filter further.
|
|
717
|
+
filteredEntities = Object.keys(entityMap)
|
|
718
|
+
.map((id) => entityMap[id])
|
|
719
|
+
.filter((e) => e && !e['_deleted']);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// APPLY REMAINING FILTERS
|
|
723
|
+
if (queryParams) {
|
|
724
|
+
filteredEntities = filteredEntities.filter((e) => {
|
|
725
|
+
// Looks for the first failed filter. If there exists any,
|
|
726
|
+
// return false (filter it out)
|
|
727
|
+
const filterValue = !queryParams.find((f) => {
|
|
728
|
+
const [key, rel, val] = f;
|
|
729
|
+
|
|
730
|
+
// already processed '__id', '=='/'in', so always passes this filter
|
|
731
|
+
if (key === '__id' && (rel === '==' || rel === 'in')) {
|
|
732
|
+
return false;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// value cannot be undefined. if it is, we ignore this query
|
|
736
|
+
// parameter (so it always passes)
|
|
737
|
+
if (val === undefined) {
|
|
738
|
+
return false;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// we try to handle the same operations as Firestore for consistency
|
|
742
|
+
switch (rel) {
|
|
743
|
+
case '==':
|
|
744
|
+
return !(e[key] === val);
|
|
745
|
+
|
|
746
|
+
case '!=':
|
|
747
|
+
return !(e[key] !== val);
|
|
748
|
+
|
|
749
|
+
case '>=':
|
|
750
|
+
return !(e[key] >= val);
|
|
751
|
+
|
|
752
|
+
case '<=':
|
|
753
|
+
return !(e[key] <= val);
|
|
754
|
+
|
|
755
|
+
case '>':
|
|
756
|
+
return !(e[key] > val);
|
|
757
|
+
|
|
758
|
+
case '<':
|
|
759
|
+
return !(e[key] < val);
|
|
760
|
+
|
|
761
|
+
case 'array-contains':
|
|
762
|
+
// If the parameter in question is optional, it should be filtered out
|
|
763
|
+
return e[key] ? !e[key].includes(val) : true;
|
|
764
|
+
|
|
765
|
+
case 'array-contains-any':
|
|
766
|
+
// If the parameter in question is optional, it should be filtered out
|
|
767
|
+
return e[key] ? !val.some((v) => e[key].includes(v)) : true;
|
|
768
|
+
|
|
769
|
+
case 'in':
|
|
770
|
+
return !val.includes(e[key]);
|
|
771
|
+
|
|
772
|
+
case 'not-in':
|
|
773
|
+
return val.includes(e[key]);
|
|
774
|
+
|
|
775
|
+
default:
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
});
|
|
779
|
+
return filterValue;
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// Sort based on orderBy
|
|
784
|
+
if (queryOptions?.orderBy) {
|
|
785
|
+
// If orderBy is provided, will only return entities with that property
|
|
786
|
+
// just like the Firestore API
|
|
787
|
+
|
|
788
|
+
const [field, order] = Array.isArray(queryOptions.orderBy) ? queryOptions.orderBy : [queryOptions.orderBy, 'asc'];
|
|
789
|
+
|
|
790
|
+
filteredEntities = filteredEntities.filter((e) => e[field] !== undefined && e[field] !== null);
|
|
791
|
+
filteredEntities.sort((a, b) => {
|
|
792
|
+
if (a[field] < b[field]) return order === 'desc' ? 1 : -1;
|
|
793
|
+
if (a[field] > b[field]) return order === 'desc' ? -1 : 1;
|
|
794
|
+
return 0;
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Filter based on startAt/startAfter/endAt/endAfter
|
|
799
|
+
if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
|
|
800
|
+
queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
|
|
801
|
+
filteredEntities = filteredEntities.filter((e) => {
|
|
802
|
+
const value = e[queryOptions.orderBy as string];
|
|
803
|
+
if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
|
|
807
|
+
return false;
|
|
808
|
+
}
|
|
809
|
+
if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
|
|
813
|
+
return false;
|
|
814
|
+
}
|
|
815
|
+
return true;
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// Limit based on limit
|
|
820
|
+
if (queryOptions?.limit !== undefined) {
|
|
821
|
+
filteredEntities = filteredEntities.slice(0, queryOptions.limit);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
return filteredEntities;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Check whether the entity satisfies the query results.
|
|
829
|
+
* We use this to double-check whether a 'removed' change was truly
|
|
830
|
+
* removed from the backend or whether it just doesn't match
|
|
831
|
+
* the query anymore.
|
|
832
|
+
*/
|
|
833
|
+
export function entityInQueryResults<T>(e: T, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
|
|
834
|
+
if (queryParams) {
|
|
835
|
+
// Looks for the first failed filter. If there exists any,
|
|
836
|
+
// return false
|
|
837
|
+
const inQueryParams = !queryParams.find((f) => {
|
|
838
|
+
const [key, rel, val] = f;
|
|
839
|
+
|
|
840
|
+
// value cannot be undefined. if it is, we ignore this query
|
|
841
|
+
// parameter (so it always passes)
|
|
842
|
+
if (val === undefined) {
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// we try to handle the same operations as Firestore for consistency
|
|
847
|
+
switch (rel) {
|
|
848
|
+
case '==':
|
|
849
|
+
return !(e[key] === val);
|
|
850
|
+
|
|
851
|
+
case '!=':
|
|
852
|
+
return !(e[key] !== val);
|
|
853
|
+
|
|
854
|
+
case '>=':
|
|
855
|
+
return !(e[key] >= val);
|
|
856
|
+
|
|
857
|
+
case '<=':
|
|
858
|
+
return !(e[key] <= val);
|
|
859
|
+
|
|
860
|
+
case '>':
|
|
861
|
+
return !(e[key] > val);
|
|
862
|
+
|
|
863
|
+
case '<':
|
|
864
|
+
return !(e[key] < val);
|
|
865
|
+
|
|
866
|
+
case 'array-contains':
|
|
867
|
+
// If the parameter in question is optional, it should be filtered out
|
|
868
|
+
return e[key] ? !e[key].includes(val) : true;
|
|
869
|
+
|
|
870
|
+
case 'array-contains-any':
|
|
871
|
+
// If the parameter in question is optional, it should be filtered out
|
|
872
|
+
return e[key] ? !val.some((v) => e[key].includes(v)) : true;
|
|
873
|
+
|
|
874
|
+
case 'in':
|
|
875
|
+
return !val.includes(e[key]);
|
|
876
|
+
|
|
877
|
+
case 'not-in':
|
|
878
|
+
return val.includes(e[key]);
|
|
879
|
+
|
|
880
|
+
default:
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
|
|
885
|
+
if (!inQueryParams) {
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// Filter based on startAt/startAfter/endAt/endAfter
|
|
891
|
+
if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
|
|
892
|
+
queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
|
|
893
|
+
const value = e[queryOptions.orderBy as string];
|
|
894
|
+
if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
|
|
898
|
+
return false;
|
|
899
|
+
}
|
|
900
|
+
if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
|
|
904
|
+
return false;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
return true;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
export async function processLoadQueries<T extends { __id: string }>(entities: T[], loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[]) {
|
|
912
|
+
if (entities.length > 0) {
|
|
913
|
+
// create a matrix of queries, each row corresponding to a given entity
|
|
914
|
+
const queriesByEntity = entities.map((entity) => loadQueries!(entity));
|
|
915
|
+
|
|
916
|
+
// transpose the matrix so each row corresponds to all queries for the same query type
|
|
917
|
+
const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
|
|
918
|
+
|
|
919
|
+
// Process all query types concurrently
|
|
920
|
+
await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
|
|
921
|
+
// Seeing if we can optimize by collapsing equality queries into 'in' queries
|
|
922
|
+
const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);
|
|
923
|
+
|
|
924
|
+
// Process queries concurrently using Promise.all
|
|
925
|
+
await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
|
|
926
|
+
await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);
|
|
927
|
+
}));
|
|
928
|
+
}));
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
export class EntityLoadQuery<T> {
|
|
933
|
+
collection: string;
|
|
934
|
+
queryParams: QueryParams;
|
|
935
|
+
queryOptions: QueryOptions;
|
|
936
|
+
loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[];
|
|
937
|
+
store;
|
|
938
|
+
|
|
939
|
+
constructor(
|
|
940
|
+
collection: string,
|
|
941
|
+
store,
|
|
942
|
+
queryParams: QueryParams,
|
|
943
|
+
queryOptions: QueryOptions,
|
|
944
|
+
loadQueries?: (entity: T) => EntityLoadQuery<AnyEntity>[],
|
|
945
|
+
) {
|
|
946
|
+
this.collection = collection;
|
|
947
|
+
this.queryParams = queryParams;
|
|
948
|
+
this.queryOptions = queryOptions;
|
|
949
|
+
this.loadQueries = loadQueries;
|
|
950
|
+
this.store = store;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Checks if there is a single equality query of the same type
|
|
954
|
+
// that could be transformed into an 'in' query
|
|
955
|
+
static isEqualityQuery<T>(queries: EntityLoadQuery<T>[]): boolean {
|
|
956
|
+
if (queries.length === 0) return false;
|
|
957
|
+
|
|
958
|
+
// check if there is only one queryParam for each query
|
|
959
|
+
const hasSingleQueryParam = queries.every((q) => q.queryParams.length === 1);
|
|
960
|
+
|
|
961
|
+
if (!hasSingleQueryParam) return false;
|
|
962
|
+
|
|
963
|
+
// check if the field is the same and it is an equality query
|
|
964
|
+
const firstField = queries[0].queryParams[0][0];
|
|
965
|
+
return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// This currently only optimizes for N+1 queries, transforming input queries
|
|
969
|
+
// with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
|
|
970
|
+
// Transform this into 'in' queries, combining up to 30 equality clauses
|
|
971
|
+
// at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
|
|
972
|
+
static optimize<T>(queries: EntityLoadQuery<T>[]): EntityLoadQuery<T>[] {
|
|
973
|
+
// TODO: we are temporarily not doing any of these optimizations until we can
|
|
974
|
+
// figure out a better way to prevent reloading of duplicate queries. Right
|
|
975
|
+
// now we remember the load time of particular queries which allows us to
|
|
976
|
+
// only query for documents past a given time. However, by grouping them
|
|
977
|
+
// together into 'in' queries, we won't be able to take advantage of that since
|
|
978
|
+
// the grouping could be different as entities are added/deleted
|
|
979
|
+
return queries;
|
|
980
|
+
|
|
981
|
+
if (this.isEqualityQuery<T>(queries)) {
|
|
982
|
+
// get the field we are querying against
|
|
983
|
+
const collection: string = queries[0].collection;
|
|
984
|
+
const field: string = queries[0].queryParams[0][0];
|
|
985
|
+
const loadQs: (entity: T) => EntityLoadQuery<AnyEntity>[] = queries[0].loadQueries;
|
|
986
|
+
|
|
987
|
+
// chunk queries into chunks of 30
|
|
988
|
+
const chunkedQueries: EntityLoadQuery<T>[][] = [];
|
|
989
|
+
for (let i = 0; i < queries.length; i += 30) {
|
|
990
|
+
chunkedQueries.push(queries.slice(i, i + 30));
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// transform every 30 into an 'in' query
|
|
994
|
+
return chunkedQueries.map((queryChunk) => {
|
|
995
|
+
const ids = queryChunk.map((q) => q.queryParams[0][2]);
|
|
996
|
+
return new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs);
|
|
997
|
+
});
|
|
998
|
+
} else {
|
|
999
|
+
return queries;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
export class EntityStreamQuery<T> {
|
|
1005
|
+
collection: string;
|
|
1006
|
+
queryParams: QueryParams;
|
|
1007
|
+
queryOptions: QueryOptions;
|
|
1008
|
+
streamQueries: (entity: T) => EntityStreamQuery<AnyEntity>[];
|
|
1009
|
+
store;
|
|
1010
|
+
|
|
1011
|
+
constructor(
|
|
1012
|
+
collection: string,
|
|
1013
|
+
store,
|
|
1014
|
+
queryParams: QueryParams,
|
|
1015
|
+
queryOptions: QueryOptions,
|
|
1016
|
+
streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
|
|
1017
|
+
) {
|
|
1018
|
+
this.collection = collection;
|
|
1019
|
+
this.queryParams = queryParams;
|
|
1020
|
+
this.queryOptions = queryOptions;
|
|
1021
|
+
this.streamQueries = streamQueries;
|
|
1022
|
+
this.store = store;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// Checks if there is a single equality query of the same type
|
|
1026
|
+
// that could be transformed into an 'in' query
|
|
1027
|
+
static isEqualityQuery<T>(queries: EntityStreamQuery<T>[]): boolean {
|
|
1028
|
+
if (queries.length === 0) return false;
|
|
1029
|
+
|
|
1030
|
+
// check if there is only one queryParam for each query
|
|
1031
|
+
const hasSingleQueryParam = queries.every((q) => q.queryParams.length === 1);
|
|
1032
|
+
|
|
1033
|
+
if (!hasSingleQueryParam) return false;
|
|
1034
|
+
|
|
1035
|
+
// check if the field is the same and it is an equality query
|
|
1036
|
+
const firstField = queries[0].queryParams[0][0];
|
|
1037
|
+
return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
// This currently only optimizes for N+1 queries, transforming input queries
|
|
1041
|
+
// with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
|
|
1042
|
+
// Transform this into 'in' queries, combining up to 30 equality clauses
|
|
1043
|
+
// at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
|
|
1044
|
+
static optimize<T>(queries: EntityStreamQuery<T>[]): EntityStreamQuery<T>[] {
|
|
1045
|
+
// TODO: we are temporarily not doing any of these optimizations until we can
|
|
1046
|
+
// figure out a better way to prevent reloading of duplicate queries. Right
|
|
1047
|
+
// now we remember the load time of particular queries which allows us to
|
|
1048
|
+
// only query for documents past a given time. However, by grouping them
|
|
1049
|
+
// together into 'in' queries, we won't be able to take advantage of that since
|
|
1050
|
+
// the grouping could be different as entities are added/deleted
|
|
1051
|
+
return queries;
|
|
1052
|
+
|
|
1053
|
+
if (this.isEqualityQuery<T>(queries)) {
|
|
1054
|
+
// get the field we are querying against
|
|
1055
|
+
const collection: string = queries[0].collection;
|
|
1056
|
+
const field: string = queries[0].queryParams[0][0];
|
|
1057
|
+
const streamQs: (entity: T) => EntityStreamQuery<AnyEntity>[] = queries[0].streamQueries;
|
|
1058
|
+
|
|
1059
|
+
// chunk queries into chunks of 30
|
|
1060
|
+
const chunkedQueries: EntityStreamQuery<T>[][] = [];
|
|
1061
|
+
for (let i = 0; i < queries.length; i += 30) {
|
|
1062
|
+
chunkedQueries.push(queries.slice(i, i + 30));
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// transform every 30 into an 'in' query
|
|
1066
|
+
return chunkedQueries.map((queryChunk) => {
|
|
1067
|
+
const ids = queryChunk.map((q) => q.queryParams[0][2]);
|
|
1068
|
+
return new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs);
|
|
1069
|
+
});
|
|
1070
|
+
} else {
|
|
1071
|
+
return queries;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|