@tech4good/angular-schematics 13.3.0 → 13.4.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.
Files changed (53) hide show
  1. package/package.json +1 -1
  2. package/src/container/files/__name@dasherize__/+state/__name@dasherize__.actions.ts.template +2 -4
  3. package/src/container/files/__name@dasherize__/+state/__name@dasherize__.effects.ts.template +1 -1
  4. package/src/container/files/__name@dasherize__/__name@dasherize__.component.ts.template +2 -4
  5. package/src/init/files/src/app/app-routing.module.ts.template +19 -0
  6. package/src/init/files/src/app/{app.component.html → app.component.html.template} +0 -0
  7. package/src/init/files/src/app/{app.component.scss → app.component.scss.template} +0 -0
  8. package/src/init/files/src/app/app.component.ts.template +41 -0
  9. package/src/init/files/src/app/app.module.ts.template +34 -0
  10. package/src/init/files/src/app/core/analytics/log.service.ts.template +35 -0
  11. package/src/init/files/src/app/core/analytics/time-analytics.service.ts.template +223 -0
  12. package/src/init/files/src/app/core/core.module.ts.template +71 -0
  13. package/src/init/files/src/app/core/firebase/firebase.service.ts.template +284 -0
  14. package/src/init/files/src/app/core/router/routing-state.service.ts.template +28 -0
  15. package/src/init/files/src/app/core/setup/firebase-setup.ts.template +25 -0
  16. package/src/init/files/src/app/core/setup/module-import-guard.ts.template +5 -0
  17. package/src/init/files/src/app/core/snackbar/snackbar.actions.ts.template +24 -0
  18. package/src/init/files/src/app/core/snackbar/snackbar.effects.ts.template +41 -0
  19. package/src/init/files/src/app/core/store/app.actions.ts.template +92 -0
  20. package/src/init/files/src/app/core/store/app.effects.ts.template +167 -0
  21. package/src/init/files/src/app/core/store/app.reducer.ts.template +30 -0
  22. package/src/init/files/src/app/core/store/app.selectors.ts.template +30 -0
  23. package/src/init/files/src/app/core/store/auth/auth.actions.ts.template +75 -0
  24. package/src/init/files/src/app/core/store/auth/auth.effects.ts.template +164 -0
  25. package/src/init/files/src/app/core/store/auth/auth.reducer.spec.ts.template +13 -0
  26. package/src/init/files/src/app/core/store/auth/auth.reducer.ts.template +26 -0
  27. package/src/init/files/src/app/core/store/auth/auth.selectors.ts.template +21 -0
  28. package/src/init/files/src/app/core/store/cached-load-connections.service.ts.template +404 -0
  29. package/src/init/files/src/app/core/store/cached-selectors.service.ts.template +376 -0
  30. package/src/init/files/src/app/core/store/effects.helpers.ts.template +66 -0
  31. package/src/init/files/src/app/core/store/user/user.actions.ts.template +269 -0
  32. package/src/init/files/src/app/core/store/user/user.effects.ts.template +131 -0
  33. package/src/init/files/src/app/core/store/user/user.model.ts.template +15 -0
  34. package/src/init/files/src/app/core/store/user/user.reducer.spec.ts.template +13 -0
  35. package/src/init/files/src/app/core/store/user/user.reducer.ts.template +50 -0
  36. package/src/init/files/src/app/core/store/user/user.service.ts.template +50 -0
  37. package/src/init/files/src/app/core/utils/string-case.utils.ts.template +96 -0
  38. package/src/init/files/src/app/general/e404/{e404.component.html → e404.component.html.template} +0 -0
  39. package/src/init/files/src/app/general/e404/{e404.component.scss → e404.component.scss.template} +0 -0
  40. package/src/init/files/src/app/general/e404/e404.component.spec.ts.template +25 -0
  41. package/src/init/files/src/app/general/e404/e404.component.ts.template +28 -0
  42. package/src/init/files/src/app/general/general-routing.module.ts.template +21 -0
  43. package/src/init/files/src/app/general/general.module.spec.ts.template +13 -0
  44. package/src/init/files/src/app/general/general.module.ts.template +30 -0
  45. package/src/init/files/src/app/general/login/{login.component.html → login.component.html.template} +0 -0
  46. package/src/init/files/src/app/general/login/{login.component.scss → login.component.scss.template} +0 -0
  47. package/src/init/files/src/app/general/login/login.component.spec.ts.template +25 -0
  48. package/src/init/files/src/app/general/login/login.component.ts.template +72 -0
  49. package/src/init/files/src/app/shared/shared.module.ts.template +81 -0
  50. package/src/init/files/src/environments/environment.prod.ts.template +5 -0
  51. package/src/init/files/src/environments/environment.ts.template +18 -0
  52. /package/src/init/files/src/styles/{_variables.scss → _variables.scss.template} +0 -0
  53. /package/src/init/files/src/{styles.scss → styles.scss.template} +0 -0
@@ -0,0 +1,404 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { Subject, Observable, merge, forkJoin, of, from, pipe } from 'rxjs';
3
+ import { publishLast, publish, publishReplay, refCount, tap, pluck, mergeMap, filter, takeUntil, skipUntil, buffer, skip, switchMap, map, take } from 'rxjs/operators';
4
+ import { Actions, ofType } from '@ngrx/effects';
5
+ import { GeneralActionTypes, Unsubscribe, LoadAction } from './app.actions';
6
+ import { Action, Store, select } from '@ngrx/store';
7
+ import * as fromStore from '../../core/store/app.reducer';
8
+ import * as fromAuth from '../../core/store/auth/auth.reducer';
9
+ import { FirebaseService } from '../firebase/firebase.service';
10
+ import { lowerCamelCase } from '../utils/string-case.utils';
11
+
12
+ export interface CachedConnection {
13
+ loadKey: string;
14
+ loadStream: Observable<Action>;
15
+ correlationIds: string[];
16
+ }
17
+
18
+ @Injectable({
19
+ providedIn: 'root',
20
+ })
21
+ export class CachedLoadConnectionsService {
22
+ /** Cached connections by correlationId. */
23
+ private connectionsByCorrelationId: { [cId: string]: CachedConnection[]; } = {};
24
+
25
+ /** Cached connections by loadKey. */
26
+ private connectionByLoadKey: { [loadKey: string]: CachedConnection; } = {};
27
+
28
+ /** Close connection events. */
29
+ private closeConnection$: Subject<string> = new Subject<string>();
30
+
31
+ /** Load ready events. */
32
+ private loadReady$: Subject<string> = new Subject<string>();
33
+
34
+ /**
35
+ * Get entityName and collection from action.
36
+ * TODO: Fragile: depends on correct syntax for type
37
+ */
38
+ private getActionAttributes(action: LoadAction): [string, string] {
39
+ const l = action.type.indexOf('[');
40
+ const r = action.type.indexOf(']');
41
+ const entityName = action.type.slice(l + 1, r);
42
+ const collection = lowerCamelCase(entityName) + 's';
43
+ return [entityName, collection];
44
+ }
45
+
46
+ /**
47
+ * Function to determine whether it is a Stream action or a Load action.
48
+ * TODO: Fragile: depends on correct syntax for type
49
+ */
50
+ public isStream(action: LoadAction): boolean {
51
+ const [entityName, collection] = this.getActionAttributes(action);
52
+ if (action.type.indexOf(`[${entityName}] stream`) === -1) {
53
+ return false;
54
+ } else {
55
+ return true;
56
+ }
57
+ }
58
+
59
+ /** Define a unique key for each connection. */
60
+ private getLoadKey(action: LoadAction): string {
61
+ const queryOptionsString = '';
62
+ if (action.queryOptions) {
63
+ if (action.queryOptions.orderBy) {
64
+ queryOptionsString.concat(`${action.queryOptions.orderBy}`);
65
+ }
66
+ if (action.queryOptions.limit) {
67
+ queryOptionsString.concat(`${action.queryOptions.limit}`);
68
+ }
69
+ if (action.queryOptions.startAt) {
70
+ queryOptionsString.concat(`${action.queryOptions.startAt}`);
71
+ }
72
+ if (action.queryOptions.startAfter) {
73
+ queryOptionsString.concat(`${action.queryOptions.startAfter}`);
74
+ }
75
+ if (action.queryOptions.endAt) {
76
+ queryOptionsString.concat(`${action.queryOptions.endAt}`);
77
+ }
78
+ if (action.queryOptions.endBefore) {
79
+ queryOptionsString.concat(`${action.queryOptions.endBefore}`);
80
+ }
81
+ }
82
+ const [entityName, collection] = this.getActionAttributes(action);
83
+
84
+ return `${entityName}.${action.queryParams}.${queryOptionsString}`;
85
+ }
86
+
87
+ /** Gets a cached connection if one exists. */
88
+ private getConnection(action: LoadAction): CachedConnection {
89
+ const loadKey = this.getLoadKey(action);
90
+ return this.connectionByLoadKey[loadKey];
91
+ }
92
+
93
+ /**
94
+ * Disconnects all "virtual" connections with that correlationId.
95
+ * For connections where this correlationId was the only one, disconnect
96
+ * it in actuality.
97
+ */
98
+ public disconnect(action: Unsubscribe) {
99
+ // console.log("PROCESS DISCONNECT: " + action.correlationId);
100
+
101
+ // Add a 5-second delay so we don't have to reconnect multiple times
102
+ // if the next view happens to use the same loading
103
+ setTimeout(() => {
104
+ const correlationId = action.correlationId;
105
+ const connections = this.connectionsByCorrelationId[correlationId];
106
+
107
+ // If there are no connections, just return
108
+ if (!connections) {
109
+ return;
110
+ }
111
+
112
+ while (connections.length > 0) {
113
+ const c = connections.pop();
114
+
115
+ // Remove the correlationId from the list in that connection
116
+ const index = c.correlationIds.findIndex((cId) => cId === correlationId);
117
+ c.correlationIds.splice(index, 1);
118
+
119
+ // If there are no more correlationIds, then dispatch close connection for that particular connection
120
+ if (c.correlationIds.length === 0) {
121
+ this.closeConnection$.next(c.loadKey);
122
+
123
+ // Update connectionByLoadKey
124
+ this.connectionByLoadKey[c.loadKey] = undefined;
125
+ }
126
+ }
127
+ }, 5000);
128
+ }
129
+
130
+ /**
131
+ * Main function called by the outside. Some notes:
132
+ * -- followupActions are only computed for initial loads and adds. They
133
+ * are not recomputed if the fields that are being used change
134
+ */
135
+ public processLoadAction(action: LoadAction, isFollowup: boolean = false, initiatingAction?: LoadAction, loadWaitingQueue?: string[]): CachedConnection {
136
+ // console.log("PROCESS LOAD: " + this.getLoadKey(action));
137
+
138
+ // Check whether this action is to just load once or create an open connection
139
+ const keepConnected: boolean = this.isStream(action);
140
+
141
+ // Set initiating action if needed
142
+ if (!isFollowup) {
143
+ initiatingAction = action;
144
+ loadWaitingQueue = [];
145
+ }
146
+
147
+ let connection;
148
+
149
+ // If we're just loading once, then we don't need all the caching logic
150
+ if (!keepConnected) {
151
+ connection = this.createSingleLoadConnection(action, initiatingAction);
152
+ } else {
153
+ // get connection and process the immediate load connection required
154
+ connection = this.getConnection(action);
155
+
156
+ if (connection) {
157
+ // if the connection already exists, don't need to create a new load connection,
158
+ // but may need to add the correlationId if it doesn't already exist
159
+ if (!connection.correlationIds.some((cId) => cId === action.correlationId)) {
160
+ connection.correlationIds.push(action.correlationId);
161
+ this.connectionsByCorrelationId[action.correlationId] = this.connectionsByCorrelationId[action.correlationId] || [];
162
+ this.connectionsByCorrelationId[action.correlationId].push(connection);
163
+ }
164
+ } else {
165
+ // if the connection does not exist, create it
166
+ connection = this.createConnection(action, initiatingAction);
167
+ this.connectionByLoadKey[connection.loadKey] = connection;
168
+ this.connectionsByCorrelationId[action.correlationId] = this.connectionsByCorrelationId[action.correlationId] || [];
169
+ this.connectionsByCorrelationId[action.correlationId].push(connection);
170
+ }
171
+ }
172
+
173
+ // indicator that we're making another connection and waiting for firebase response
174
+ if (loadWaitingQueue) {
175
+ loadWaitingQueue.push('waiting');
176
+ }
177
+
178
+ let followupStream$;
179
+
180
+ if (!keepConnected) {
181
+ followupStream$ = connection.loadStream.pipe(
182
+ take(1),
183
+ );
184
+ } else {
185
+ followupStream$ = connection.loadStream;
186
+ }
187
+ followupStream$.subscribe((fbPayload: any) => {
188
+ if (fbPayload.type === 'initial' || fbPayload.type === 'load') {
189
+ // process the followupActions
190
+ if (action.followupActions) {
191
+ for (const entity of fbPayload.results) {
192
+ const followupLoadActions = action.followupActions(entity);
193
+ for (const fAction of followupLoadActions) {
194
+ this.processLoadAction(fAction, true, initiatingAction, loadWaitingQueue);
195
+ }
196
+ }
197
+ }
198
+ if (fbPayload.type === 'initial' && loadWaitingQueue) {
199
+ loadWaitingQueue.pop();
200
+ if (loadWaitingQueue.length === 0) {
201
+ console.log('READY!');
202
+ // Note: if there's some strange reason you have a nested query that
203
+ // is exactly the same as the original query, it could trigger early
204
+ this.loadReady$.next(this.getLoadKey(initiatingAction));
205
+ }
206
+ }
207
+ } else if (fbPayload.type === 'added') {
208
+ if (action.followupActions) {
209
+ const entity = fbPayload.result;
210
+ const followupLoadActions = action.followupActions(entity);
211
+ for (const fAction of followupLoadActions) {
212
+ this.processLoadAction(fAction, true, initiatingAction, loadWaitingQueue);
213
+ }
214
+ }
215
+ }
216
+ });
217
+
218
+ return connection;
219
+ }
220
+
221
+ private createSingleLoadConnection(action: LoadAction, initiatingAction: LoadAction): CachedConnection {
222
+ // Unlike the createConnection logic, we don't need a disconnectObs$ since
223
+ // we aren't keeping a persistent stream
224
+
225
+ // ------------ DISPATCH ACTIONS ONLY AFTER START DISPATCH EMITS ------------------
226
+
227
+ // When loadReady$ for the initiatingAction, we can startDispatching$ since all connections
228
+ // have had responses from Firebase
229
+ const initiatingLoadKey = this.getLoadKey(initiatingAction);
230
+ const startDispatching$ = this.loadReady$.pipe(
231
+ filter((lk) => lk === initiatingLoadKey),
232
+ take(1),
233
+ );
234
+
235
+ // Define the raw stream
236
+ const [entityName, collection] = this.getActionAttributes(action);
237
+ const rawStream$ = this.db.queryListValueChanges(collection, action.queryParams, action.queryOptions).pipe(
238
+ map((results) => {
239
+ return { type: 'initial', results };
240
+ }),
241
+ // Is this 2 or 1? There is that issue with cached values that could be a problem still...
242
+ take(1),
243
+ );
244
+
245
+ // Once startDispatching emits, we can start dispatching
246
+ forkJoin([startDispatching$, rawStream$]).pipe(
247
+ map(([_, fbPayload]) => {
248
+ return fbPayload;
249
+ }),
250
+ take(1),
251
+ ).subscribe((fbPayload) => {
252
+ this.store.dispatch( {
253
+ type: `[${entityName}] loaded`,
254
+ payload: fbPayload.results,
255
+ correlationId: action.correlationId,
256
+ } );
257
+ });
258
+
259
+ // Return a replayed version for followupActions
260
+ const stream$ = rawStream$.pipe(
261
+ publishReplay(1),
262
+ refCount(),
263
+ );
264
+
265
+ // We're returning it in this form just so processLoadAction can be defined generally
266
+ return {
267
+ loadKey: null,
268
+ loadStream: stream$,
269
+ correlationIds: [],
270
+ };
271
+ }
272
+
273
+ private createConnection(action: LoadAction, initiatingAction: LoadAction): CachedConnection {
274
+ // console.log("CONNECT " + this.getLoadKey(action));
275
+
276
+ // ------------ DEFINE OBSERVABLES FOR DISCONNECTING AND DISPATCHING --------------
277
+
278
+ const loadKey = this.getLoadKey(action);
279
+ const disconnectObs$ = this.closeConnection$.pipe(
280
+ filter((lk) => lk === loadKey),
281
+ take(1),
282
+ // tap(a => { console.log("DISCONNECT: " + loadKey) }),
283
+ publish(),
284
+ refCount(),
285
+ );
286
+
287
+ // When loadReady$ for the initiatingAction, we can startDispatching$ since all connections
288
+ // have had responses from Firebase
289
+ const initiatingLoadKey = this.getLoadKey(initiatingAction);
290
+ const startDispatching$ = this.loadReady$.pipe(
291
+ filter((lk) => lk === initiatingLoadKey),
292
+ take(1),
293
+ // tap(a => { console.log("START DISPATCHING: " + initiatingLoadKey) }),
294
+ publish(),
295
+ refCount(),
296
+ );
297
+
298
+ // ------------ MULTICAST THE RAW ACTION STREAM -----------------------------------
299
+
300
+ const [entityName, collection] = this.getActionAttributes(action);
301
+
302
+ // Create a multicasted stream emitting until disonnectObs$ fires
303
+ const rawStream$ = this.loadStream(collection, action).pipe(
304
+ takeUntil(disconnectObs$),
305
+ publishReplay(1),
306
+ refCount(),
307
+ );
308
+
309
+ // ------------ DISPATCH ACTIONS ONLY AFTER START DISPATCH EMITS ------------------
310
+
311
+ // This buffers the stream of actions until startDispatching$ fires
312
+ const bufferedStream$ = rawStream$.pipe(
313
+ buffer(startDispatching$),
314
+ take(1),
315
+ mergeMap((array) => array),
316
+ takeUntil(disconnectObs$),
317
+ );
318
+
319
+ // This stores the stream of actions after buffering is finished
320
+ const postBufferedStream$ = rawStream$.pipe(
321
+ skipUntil(startDispatching$),
322
+ takeUntil(disconnectObs$),
323
+ );
324
+
325
+ // Merge the buffered and post-buffered streams together and dispatch actions
326
+ merge(bufferedStream$, postBufferedStream$).pipe(
327
+ takeUntil(disconnectObs$),
328
+ ).subscribe((fbPayload) => {
329
+ if (fbPayload.type === 'initial' || fbPayload.type === 'load') {
330
+ this.store.dispatch( {
331
+ type: `[${entityName}] loaded`,
332
+ payload: fbPayload.results,
333
+ correlationId: action.correlationId,
334
+ } );
335
+ } else {
336
+ this.store.dispatch( {
337
+ type: `[${entityName}] ${fbPayload.type}`,
338
+ payload: fbPayload.result,
339
+ correlationId: action.correlationId,
340
+ } );
341
+ }
342
+ });
343
+
344
+ // ------------ REPLAY ONLY THE INITIAL/LOAD/ADD ACTIONS --------------------------
345
+
346
+ // multicast the WHOLE stream of initial and added actions. This is so that "followupActions" in future
347
+ // loads also works. Don't need to replay "modify" actions since this will store way too many actions.
348
+ // takeUntil is required both before (defined in rawStream$) and after publishReplay
349
+ // to make sure both the connection to firebase stops as well as subscriptions to the multicasted observable
350
+ const stream$ = rawStream$.pipe(
351
+ filter((fbPayload: any) => fbPayload.type === 'initial' || fbPayload.type === 'load' || fbPayload.type === 'added'),
352
+ publishReplay(),
353
+ refCount(),
354
+ takeUntil(disconnectObs$),
355
+ );
356
+
357
+ return {
358
+ loadKey: this.getLoadKey(action),
359
+ loadStream: stream$,
360
+ correlationIds: [action.correlationId],
361
+ };
362
+ }
363
+
364
+ // Returns an observable with the initial as a list
365
+ // and the remainder as deltas
366
+ private loadStream = (collection: string, action: LoadAction): Observable<{ type: string; results?: any; result?: any; }> => {
367
+ const queryParams = action.queryParams;
368
+ const queryOptions = action.queryOptions;
369
+
370
+ const loadKey = this.getLoadKey(action);
371
+ const disconnectObs$ = this.closeConnection$.pipe(
372
+ filter((lk) => lk === loadKey),
373
+ take(1),
374
+ );
375
+ return this.db.queryListValueChanges(collection, queryParams, queryOptions).pipe(
376
+ take(1),
377
+ mergeMap((results) => {
378
+ return merge(
379
+ of({ type: 'initial', results }),
380
+ this.db.queryListStateChanges(collection, queryParams, queryOptions).pipe(
381
+ skip(1),
382
+ // results is an array of state changes.
383
+ mergeMap((changeResults: any[]) => {
384
+ // group 'added' actions together to load simultaneously into store
385
+ const addedResults = changeResults.filter((r) => r.type === 'added').map((r) => r.result);
386
+
387
+ // group remaining actions together
388
+ const otherResults = changeResults.filter((r) => r.type !== 'added');
389
+
390
+ return [{ type: 'load', results: addedResults }, ...otherResults];
391
+ }),
392
+ ) as Observable<{ type: string; results?: any; result?: any; }>,
393
+ );
394
+ }),
395
+ takeUntil(disconnectObs$),
396
+ );
397
+ };
398
+
399
+ constructor(
400
+ private actions$: Actions,
401
+ private store: Store<fromStore.State>,
402
+ private db: FirebaseService,
403
+ ) { }
404
+ }