@tech4good/angular-schematics 21.6.0 → 21.7.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 (229) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +266 -1
  3. package/package.json +34 -7
  4. package/src/component/files/__name@dasherize__/__name@dasherize__.component.spec.ts.template +4 -5
  5. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -1
  6. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +14 -6
  7. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +12 -6
  8. package/src/entity/files/__name@dasherize__/__name@dasherize__.store.ts.template +18 -10
  9. package/src/entity/index.js +4 -49
  10. package/src/entity/index.js.map +1 -1
  11. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +0 -1
  12. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +3 -0
  13. package/src/ng-add/files/.gitignore.template +3 -0
  14. package/src/ng-add/files/analytics/datasets.js.template +206 -0
  15. package/src/ng-add/files/analytics/entity_sources.js.template +58 -0
  16. package/src/ng-add/files/analytics/entity_sources.test.js.template +57 -0
  17. package/src/ng-add/files/analytics/lib/api_query.js.template +87 -0
  18. package/src/ng-add/files/analytics/lib/api_query.test.js.template +84 -0
  19. package/src/ng-add/files/analytics/lib/bigquery_query_compatibility.test.js.template +53 -0
  20. package/src/ng-add/files/analytics/lib/dataset_schema.js.template +53 -0
  21. package/src/ng-add/files/analytics/lib/dataset_schema.test.js.template +34 -0
  22. package/src/ng-add/files/analytics/lib/entity_sync.js.template +397 -0
  23. package/src/ng-add/files/analytics/lib/entity_sync.test.js.template +212 -0
  24. package/src/ng-add/files/analytics/lib/identifier_salt.js.template +57 -0
  25. package/src/ng-add/files/analytics/lib/identifier_salt.test.js.template +36 -0
  26. package/src/ng-add/files/analytics/lib/snapshot_files.js.template +46 -0
  27. package/src/ng-add/files/analytics/lib/snapshot_files.test.js.template +67 -0
  28. package/src/ng-add/files/analytics/lib/sqlite.js.template +92 -0
  29. package/src/ng-add/files/analytics/lib/upload_entities.js.template +81 -0
  30. package/src/ng-add/files/analytics/lib/upload_entities.test.js.template +86 -0
  31. package/src/ng-add/files/analytics/proxy.conf.json.template +7 -0
  32. package/src/ng-add/files/analytics/scripts/refresh_snapshot.js.template +518 -0
  33. package/src/ng-add/files/analytics/scripts/start.js.template +88 -0
  34. package/src/ng-add/files/analytics/server/server.js.template +212 -0
  35. package/src/ng-add/files/angular.json.template +80 -1
  36. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +27 -8
  37. package/src/ng-add/files/bigquery/queries/active_user_windows.sql.template +67 -0
  38. package/src/ng-add/files/bigquery/queries/dashboard_route_visits.sql.template +47 -0
  39. package/src/ng-add/files/bigquery/queries/data_quality.sql.template +323 -0
  40. package/src/ng-add/files/bigquery/queries/onboarding_funnel.sql.template +512 -0
  41. package/src/ng-add/files/bigquery/queries/onboarding_stage_observations.sql.template +134 -0
  42. package/src/ng-add/files/bigquery/queries/weekly_retention_cohorts.sql.template +90 -0
  43. package/src/ng-add/files/bigquery/scripts/export_entities.js.template +120 -0
  44. package/src/ng-add/files/bigquery/scripts/init_views.js.template +57 -0
  45. package/src/ng-add/files/bigquery/scripts/run_query.js.template +141 -0
  46. package/src/ng-add/files/bigquery/views/events_flat.sql.template +27 -12
  47. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +16 -3
  48. package/src/ng-add/files/docs-infra/analytics-guide.md.template +270 -25
  49. package/src/ng-add/files/docs-infra/analytics-workbench-guide.md.template +307 -0
  50. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +54 -24
  51. package/src/ng-add/files/docs-infra/email-infrastructure.md.template +43 -0
  52. package/src/ng-add/files/docs-infra/firestore-index-checker.md.template +87 -0
  53. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +108 -29
  54. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +15 -1
  55. package/src/ng-add/files/docs-infra/querying-strategy.md.template +14 -0
  56. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +21 -7
  57. package/src/ng-add/files/eslint.config.js.template +22 -3
  58. package/src/ng-add/files/functions/package.json.template +1 -0
  59. package/src/ng-add/files/functions/src/email.ts.template +23 -0
  60. package/src/ng-add/files/jest.config.ts.template +3 -2
  61. package/src/ng-add/files/package.json.template +39 -16
  62. package/src/ng-add/files/projects/analytics/src/app/analytics-api.service.ts.template +130 -0
  63. package/src/ng-add/files/projects/analytics/src/app/app.component.html.template +77 -0
  64. package/src/ng-add/files/projects/analytics/src/app/app.component.scss.template +240 -0
  65. package/src/ng-add/files/projects/analytics/src/app/app.component.ts.template +96 -0
  66. package/src/ng-add/files/projects/analytics/src/app/app.routes.ts.template +11 -0
  67. package/src/ng-add/files/projects/analytics/src/app/dashboard-pages.spec.ts.template +151 -0
  68. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.html.template +39 -0
  69. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.scss.template +1 -0
  70. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.ts.template +95 -0
  71. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.html.template +47 -0
  72. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.scss.template +1 -0
  73. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.ts.template +120 -0
  74. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.html.template +40 -0
  75. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.scss.template +1 -0
  76. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.ts.template +98 -0
  77. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.html.template +35 -0
  78. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.scss.template +1 -0
  79. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.ts.template +84 -0
  80. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.html.template +42 -0
  81. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.scss.template +1 -0
  82. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.ts.template +110 -0
  83. package/src/ng-add/files/projects/analytics/src/app/shared/analytics-utils.ts.template +43 -0
  84. package/src/ng-add/files/projects/analytics/src/app/shared/chart-theme.ts.template +42 -0
  85. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-layout.scss.template +239 -0
  86. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.html.template +76 -0
  87. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.scss.template +128 -0
  88. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.spec.ts.template +31 -0
  89. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.ts.template +153 -0
  90. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.html.template +16 -0
  91. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.scss.template +63 -0
  92. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.ts.template +52 -0
  93. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.html.template +5 -0
  94. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.scss.template +56 -0
  95. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.spec.ts.template +30 -0
  96. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.ts.template +15 -0
  97. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.html.template +9 -0
  98. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.scss.template +43 -0
  99. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.ts.template +62 -0
  100. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.html.template +9 -0
  101. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.scss.template +33 -0
  102. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.ts.template +82 -0
  103. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.html.template +15 -0
  104. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.scss.template +45 -0
  105. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.ts.template +55 -0
  106. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.html.template +18 -0
  107. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.scss.template +45 -0
  108. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.ts.template +15 -0
  109. package/src/ng-add/files/projects/analytics/src/app/vega-chart/vega-chart.component.ts.template +121 -0
  110. package/src/ng-add/files/projects/analytics/src/index.html.template +19 -0
  111. package/src/ng-add/files/projects/analytics/src/main.ts.template +16 -0
  112. package/src/ng-add/files/projects/analytics/src/styles.scss.template +28 -0
  113. package/src/ng-add/files/projects/analytics/tsconfig.app.json.template +13 -0
  114. package/src/ng-add/files/projects/analytics/tsconfig.spec.json.template +15 -0
  115. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +4 -5
  116. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +4 -5
  117. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +11 -12
  118. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +7 -7
  119. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +8 -10
  120. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +3 -2
  121. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  122. package/src/ng-add/files/src/app/app.component.scss.template +1 -1
  123. package/src/ng-add/files/src/app/app.component.spec.ts.template +4 -5
  124. package/src/ng-add/files/src/app/app.component.ts.template +1 -2
  125. package/src/ng-add/files/src/app/app.config.ts.template +21 -15
  126. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +4 -5
  127. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +46 -29
  128. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +27 -18
  129. package/src/ng-add/files/src/app/core/auth/auth.providers.spec.ts.template +112 -0
  130. package/src/ng-add/files/src/app/core/auth/auth.providers.ts.template +48 -0
  131. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +9 -23
  132. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +3 -14
  133. package/src/ng-add/files/src/app/core/firebase/data.providers.prod.ts.template +21 -0
  134. package/src/ng-add/files/src/app/core/firebase/data.providers.ts.template +13 -0
  135. package/src/ng-add/files/src/app/core/local-storage/session.service.spec.ts.template +43 -0
  136. package/src/ng-add/files/src/app/core/local-storage/session.service.ts.template +7 -0
  137. package/src/ng-add/files/src/app/core/store/app-data.spec.ts.template +76 -0
  138. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +19 -67
  139. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +102 -12
  140. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +32 -237
  141. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +17 -12
  142. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +6 -7
  143. package/src/ng-add/files/src/app/core/store/user/user.store.ts.template +14 -10
  144. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +20 -8
  145. package/src/ng-add/files/src/app/core/store/user-context/user-context.model.ts.template +5 -6
  146. package/src/ng-add/files/src/app/core/store/user-context/user-context.store.ts.template +14 -10
  147. package/src/ng-add/files/src/app/core/store/user-private/user-private.mock.ts.template +20 -7
  148. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +5 -6
  149. package/src/ng-add/files/src/app/core/store/user-private/user-private.store.ts.template +14 -10
  150. package/src/ng-add/files/src/app/core/testing/app-mocks.ts.template +42 -0
  151. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +2 -1
  152. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +7 -3
  153. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -11
  154. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +16 -1
  155. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +15 -15
  156. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +11 -3
  157. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +2 -1
  158. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +7 -3
  159. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +20 -6
  160. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +2 -0
  161. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +4 -5
  162. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +17 -1
  163. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +15 -0
  164. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +4 -5
  165. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +15 -0
  166. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +2 -0
  167. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +21 -3
  168. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +26 -0
  169. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +4 -2
  170. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -1
  171. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +2 -2
  172. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +2 -2
  173. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +4 -4
  174. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +2 -2
  175. package/src/ng-add/files/src/app/main/home/home.component.spec.ts.template +4 -5
  176. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -1
  177. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +4 -4
  178. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +2 -2
  179. package/src/ng-add/files/tsconfig.spec.json.template +3 -1
  180. package/src/ng-add/index.js +7 -0
  181. package/src/ng-add/index.js.map +1 -1
  182. package/src/shared/entity-registry.d.ts +8 -0
  183. package/src/shared/entity-registry.js +28 -0
  184. package/src/shared/entity-registry.js.map +1 -0
  185. package/.agents/skills/publish-npm/SKILL.md +0 -37
  186. package/.agents/skills/publish-npm/eval.yaml +0 -32
  187. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +0 -8
  188. package/.husky/commit-msg +0 -1
  189. package/.husky/pre-commit +0 -1
  190. package/.t4g/agent-memory.db +0 -0
  191. package/src/component/index_spec.d.ts +0 -1
  192. package/src/component/index_spec.js +0 -68
  193. package/src/component/index_spec.js.map +0 -1
  194. package/src/entity/index_spec.d.ts +0 -1
  195. package/src/entity/index_spec.js +0 -153
  196. package/src/entity/index_spec.js.map +0 -1
  197. package/src/guard/index_spec.d.ts +0 -1
  198. package/src/guard/index_spec.js +0 -64
  199. package/src/guard/index_spec.js.map +0 -1
  200. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +0 -143
  201. package/src/ng-add/files/bigquery/scripts/run_query.py.template +0 -167
  202. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +0 -500
  203. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +0 -73
  204. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +0 -59
  205. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +0 -147
  206. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +0 -453
  207. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +0 -116
  208. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +0 -639
  209. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +0 -104
  210. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +0 -127
  211. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +0 -38
  212. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +0 -445
  213. package/src/ng-add/files/src/app/core/logging/logging.service.spec.ts.template +0 -118
  214. package/src/ng-add/files/src/app/core/logging/logging.service.ts.template +0 -168
  215. package/src/ng-add/files/src/app/core/store/app.model.ts.template +0 -21
  216. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +0 -920
  217. package/src/ng-add/files/src/app/core/store/app.store.ts.template +0 -1320
  218. package/src/ng-add/files/src/app/core/store/batch-write.firebase.service.ts.template +0 -58
  219. package/src/ng-add/files/src/app/core/store/batch-write.mock.service.ts.template +0 -105
  220. package/src/ng-add/files/src/app/core/store/batch-write.service.ts.template +0 -126
  221. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +0 -9
  222. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.scss.template +0 -46
  223. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +0 -69
  224. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +0 -39
  225. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +0 -122
  226. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +0 -88
  227. package/src/ng-add/index_spec.d.ts +0 -1
  228. package/src/ng-add/index_spec.js +0 -108
  229. package/src/ng-add/index_spec.js.map +0 -1
@@ -1,1320 +0,0 @@
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, setAllEntities } from '@ngrx/signals/entities';
5
- import { SelectEntityId } from '@ngrx/signals/entities';
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
- import { environment } from '../../../environments/environment';
12
- import { LoggingService, getLogger } from '../logging/logging.service';
13
-
14
- const queryLogger = getLogger('query');
15
-
16
- const selectId: SelectEntityId<AnyEntity> = (entity) => entity?.__id ?? '';
17
-
18
- export function openSnackBarWithUndoOption(
19
- snackBar: MatSnackBar,
20
- snackBarConfig: {
21
- successMessage: string,
22
- failureMessage: string,
23
- undoOnAction?: boolean,
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
- config?: MatSnackBarConfig<any>,
26
- },
27
- revertFns: Array<() => void>,
28
- dbRevertFns: Array<() => void>,
29
- revertBatch?: WriteBatchI,
30
- ) {
31
- const snackBarRef = snackBar.open(
32
- snackBarConfig.successMessage,
33
- snackBarConfig.undoOnAction ? 'Undo' : '',
34
- snackBarConfig.config,
35
- );
36
- // if there is an undo option for the snackbar, then we should
37
- // revert both local and database changes if the undo was clicked
38
- if (snackBarConfig.undoOnAction) {
39
- snackBarRef.onAction().subscribe(async () => {
40
- try {
41
- // first try to undo changes on the database
42
- // dbRevertFns will directly remove from DB if not in the batch setting.
43
- // if it is a batch setting, it will do revertBatch.set to prepare
44
- // revertBatch for a commit
45
- await Promise.all(dbRevertFns.map((dbRevertFn) => dbRevertFn()));
46
- if (revertBatch) {
47
- await revertBatch.commit();
48
- }
49
- // if successful, then undo changes locally too
50
- revertFns.forEach((revertFn) => revertFn());
51
- } catch (e) {
52
- console.error(e);
53
- snackBar.open('Failed to undo', '', {
54
- duration: 3000,
55
- });
56
- }
57
- });
58
- }
59
- }
60
-
61
- export function withEntitiesAndSelectMethods<S extends AnyEntity>() {
62
- return signalStoreFeature(
63
- withEntities<S>(),
64
- withMethods((store) => {
65
- const queryCache = new Map<string, S[]>();
66
- return {
67
- handleStreamChanges(entitiesToAdd: S[], entitiesToModify: S[], entitiesToRemove: string[]) {
68
- patchState(store, setEntities(entitiesToAdd, { selectId }));
69
- patchState(store, setEntities(entitiesToModify, { selectId }));
70
- patchState(store, removeEntities(entitiesToRemove));
71
- },
72
- selectEntity(id: string): S {
73
- const result = store.entityMap()[id];
74
-
75
- if (result && !result['_deleted']) {
76
- return result;
77
- } else {
78
- return null;
79
- }
80
- },
81
- selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S {
82
- // Note: selectEntities already filters out _deleted
83
- const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
84
- if (entities && entities.length > 0) {
85
- return entities[0];
86
- } else {
87
- return null;
88
- }
89
- },
90
- selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {
91
- // Note: The global standalone selectEntities function already filters out entities with _deleted: true
92
- const result = selectEntities<S>(store.entityMap(), queryParams, queryOptions);
93
- const key = JSON.stringify({ queryParams, queryOptions });
94
-
95
- // CRITICAL: Angular's computed() signals rely on strict referential equality (===).
96
- // Because Object.values().filter() creates a brand new array reference every time it is called,
97
- // any computed signal that calls selectEntities() would trigger an update even if the contents
98
- // of the array are identical. This led to infinite loops and massive memory leaks in nested streams.
99
- // By memoizing the array reference here, we ensure that if the query results are strictly identical
100
- // (same length, same entity references in the exact same order), we return the exact same array reference.
101
- const lastResult = queryCache.get(key);
102
- if (lastResult && lastResult.length === result.length && lastResult.every((v, i) => v === result[i])) {
103
- return lastResult;
104
- }
105
-
106
- queryCache.set(key, result);
107
-
108
- // Simple bounded LRU cache (max 50 unique queries per store) to prevent memory ballooning
109
- if (queryCache.size > 50) {
110
- const firstKey = queryCache.keys().next().value;
111
- if (firstKey) queryCache.delete(firstKey);
112
- }
113
- return result;
114
- },
115
- };
116
- }),
117
- );
118
- }
119
-
120
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
- function serializeMockDBData(data: any): string {
122
- return JSON.stringify(data, (key, value) => {
123
- if (value && typeof value === 'object' && 'seconds' in value && 'nanoseconds' in value) {
124
- return { __type: 'Timestamp', seconds: value.seconds, nanoseconds: value.nanoseconds };
125
- }
126
- return value;
127
- });
128
- }
129
-
130
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
131
- function deserializeMockDBData(jsonString: string): any {
132
- return JSON.parse(jsonString, (key, value) => {
133
- if (value && typeof value === 'object' && value.__type === 'Timestamp') {
134
- return new Timestamp(value.seconds, value.nanoseconds);
135
- }
136
- return value;
137
- });
138
- }
139
-
140
- export function withEntitiesForMockDB<S extends AnyEntity>(collectionName: string) {
141
- return signalStoreFeature(
142
- withEntitiesAndSelectMethods<S>(),
143
- withMethods((store) => ({
144
- init(entities: S[]) {
145
- const saved = environment.cacheMockData ? localStorage.getItem(`mockDB_${collectionName}`) : null;
146
- if (saved) {
147
- patchState(store, setAllEntities<S>(deserializeMockDBData(saved), { selectId }));
148
- } else {
149
- patchState(store, setAllEntities<S>(entities, { selectId }));
150
- }
151
-
152
- // Listen for changes from other tabs to keep mockDB in sync
153
- window.addEventListener('storage', (event) => {
154
- if (event.key === `mockDB_${collectionName}` && event.newValue) {
155
- patchState(store, setAllEntities<S>(deserializeMockDBData(event.newValue), { selectId }));
156
- }
157
- });
158
- },
159
- add(entity: S) {
160
- patchState(store, setEntity<S>(entity, { selectId }));
161
- if (environment.cacheMockData) {
162
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
163
- }
164
- },
165
- update(id: string, changes: Partial<S>) {
166
- patchState(store, updateEntity({ id, changes }, { selectId }));
167
- if (environment.cacheMockData) {
168
- localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
169
- }
170
- },
171
- })),
172
- );
173
- }
174
-
175
-
176
- export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: string) {
177
- return signalStoreFeature(
178
- withEntitiesAndSelectMethods<S>(),
179
- withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATABASE_SERVICE), snackBar = inject(MatSnackBar), logger = inject(LoggingService)) => ({
180
- init(entities: S[]) {
181
- patchState(store, setAllEntities<S>(entities, { selectId }));
182
- },
183
- reset() {
184
- patchState(store, setAllEntities<S>([], { selectId }));
185
- },
186
- // streaming tries to reduce redundant loads through the following:
187
- // - caching listeners and reusing them with a 5-second delay after moving to a new container before unsubscribing
188
- // additionally, it has the following constraints:
189
- // - nested loadQueries are only loaded, not streamed, to prevent huge numbers of listeners.
190
- // - nested loadQueries can only be made based on the id of retrieved entities to ensure we only need to replay loads/adds
191
- // - containers pass in an id for loads, then onDestroy, they call cachedListeners.disconnect(id)
192
- async stream(
193
- queryParams: QueryParams,
194
- queryOptions: QueryOptions,
195
- injector,
196
- streamQueries?: (entity: S) => EntityStreamQuery<AnyEntity>[],
197
- options?: {
198
- loading?: WritableSignal<boolean>, // set to true on start, set to false once all are complete
199
- },
200
- ) {
201
- try {
202
- // start loading icon if available
203
- options?.loading?.set(true);
204
-
205
- const isSimpleEqualityQuery = (!queryOptions || Object.keys(queryOptions).length === 0) &&
206
- queryParams.length === 1 &&
207
- (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
208
-
209
- if (isSimpleEqualityQuery) {
210
- const field = queryParams[0][0];
211
- const ids = queryParams[0][1] === 'in' ? queryParams[0][2] : [queryParams[0][2]];
212
- await cachedLoads.processSimpleStreamQuery(collectionName, field, ids, store, injector, streamQueries, options);
213
- } else {
214
- await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);
215
- }
216
- } catch (e) {
217
- console.error(e);
218
-
219
- // stop loading icon. when no error, loading icon is stopped
220
- // upon the initial payload coming through the stream and the
221
- // loadQueries being processed
222
- options?.loading?.set(false);
223
- throw e;
224
- }
225
- },
226
- // loading tries to reduce redundant loads through the following:
227
- // - below only applies when there are no queryOptions
228
- // - only loads (not deleted) entities since the last time this query was made and when there is not already an active stream for that
229
- // - 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)
230
- // - to calculate loadQueries, use the entities within the store (to get both the deltas and the things already loaded)
231
- async load(
232
- queryParams: QueryParams,
233
- queryOptions: QueryOptions,
234
- loadQueries?: (entity: S) => EntityLoadQuery<AnyEntity>[],
235
- options?: {
236
- loading?: WritableSignal<boolean>,
237
- },
238
- ) {
239
- try {
240
- // start loading icon if available
241
- options?.loading?.set(true);
242
-
243
- const isBatchableEqualityOrIn =
244
- (!queryOptions || Object.keys(queryOptions).length === 0) &&
245
- queryParams.length === 1 &&
246
- (queryParams[0][1] === '==' || queryParams[0][1] === 'in');
247
-
248
- if (!isBatchableEqualityOrIn) {
249
- // ---------------------------------------------------------
250
- // LEGACY PATH: Non-equality queries use full query-string tracking
251
- // ---------------------------------------------------------
252
- // only load if there is not already a listener for the same query
253
- if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {
254
- // get the last load time and next load time
255
- const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);
256
- const newLoadTime = Timestamp.now().toMillis();
257
-
258
- // load entities since last load that are not deleted
259
- // note that we always load all entities if there exist queryOptions since adding
260
- // the _updatedAt filter will change queries with limit
261
- let queryParamsWithTime;
262
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
263
- queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];
264
- } else {
265
- queryParamsWithTime = [
266
- ...queryParams,
267
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
268
- ['_deleted', '==', false],
269
- ];
270
- }
271
-
272
- // get entities that have been added or updated since last load
273
- const entitiesDelta: S[] = await db.getEntities(
274
- collectionName,
275
- queryParamsWithTime,
276
- queryOptions,
277
- );
278
- patchState(store, setEntities<S>(entitiesDelta, { selectId }));
279
-
280
- // delete any new deleted entities
281
- if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {
282
- const entitiesDeletedDelta: S[] = await db.getEntities(
283
- collectionName,
284
- [...queryParams, ['_deleted', '==', true]],
285
- queryOptions,
286
- );
287
- patchState(store, removeEntities(
288
- entitiesDeletedDelta.map((e) => e.__id),
289
- ));
290
- } else {
291
- const entitiesDeletedDelta: S[] = await db.getEntities(
292
- collectionName,
293
- [...queryParams,
294
- ['_updatedAt', '>', Timestamp.fromMillis(lastLoadTime)],
295
- ['_deleted', '==', true]],
296
- queryOptions,
297
- );
298
- patchState(store, removeEntities(
299
- entitiesDeletedDelta.map((e) => e.__id),
300
- ));
301
- }
302
-
303
- // save a new lastLoadTime for this query
304
- cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);
305
- }
306
- } else {
307
- // ---------------------------------------------------------
308
- // OPTIMIZED PATH: Per-entity tracking for == and in queries
309
- // ---------------------------------------------------------
310
- const field = queryParams[0][0] as string;
311
- const operator = queryParams[0][1];
312
- const rawValues = operator === '==' ? [queryParams[0][2] as string] : queryParams[0][2] as string[];
313
-
314
- // 1. Remove IDs already covered by active streams
315
- const valuesToLoad = rawValues.filter((v) => {
316
- // Check if it's covered by a multiplexer stream
317
- if (cachedLoads.isIdStreamed(collectionName, field, v)) return false;
318
- return true;
319
- });
320
-
321
- if (valuesToLoad.length > 0) {
322
- const newLoadTime = Timestamp.now().toMillis();
323
-
324
- if (field === '__id' && valuesToLoad.length === 1) {
325
- const idToFetch = valuesToLoad[0];
326
- queryLogger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', fetching single ID using getDoc.`);
327
-
328
- const entity = await db.getEntity<S>(collectionName, idToFetch);
329
-
330
- if (entity) {
331
- if (entity._deleted) {
332
- patchState(store, removeEntities([idToFetch]));
333
- } else {
334
- patchState(store, setEntities<S>([entity], { selectId }));
335
- }
336
- } else {
337
- patchState(store, removeEntities([idToFetch]));
338
- }
339
-
340
- cachedLoads.setEntityLoadTime(collectionName, field, idToFetch, newLoadTime);
341
- } else {
342
- // 2. Group values by their entityLoadTime (Time Bucketing Strategy)
343
- // To prevent the N+1 problem of issuing dozens of queries for items with slightly
344
- // different load times, we group loaded items into 5-minute buckets.
345
- // Unloaded items (-1) are strictly kept in their own bucket to prevent over-fetching.
346
- const BUCKET_MS = 5 * 60 * 1000;
347
-
348
- // Map bucket index to the exact minimum time in that bucket and its values
349
- const groupsByBucket: Map<number, { minTime: number, values: string[] }> = new Map();
350
-
351
- queryLogger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', tracking ${valuesToLoad.length} IDs.`);
352
-
353
- valuesToLoad.forEach((val) => {
354
- const time = cachedLoads.getEntityLoadTime(collectionName, field, val);
355
- const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);
356
-
357
- if (!groupsByBucket.has(bucketIndex)) {
358
- groupsByBucket.set(bucketIndex, { minTime: time, values: [] });
359
- }
360
-
361
- const group = groupsByBucket.get(bucketIndex)!;
362
- // Track the earliest load time in this bucket
363
- if (time !== -1 && time < group.minTime) {
364
- group.minTime = time;
365
- }
366
- group.values.push(val);
367
- });
368
-
369
- // 3. For each group, execute DB fetches
370
- queryLogger.log(`[Store] Grouped ${valuesToLoad.length} IDs into ${groupsByBucket.size} time bucket(s).`);
371
- await Promise.all(Array.from(groupsByBucket.entries()).map(async ([bucketIndex, group]) => {
372
- const lastTime = group.minTime;
373
- const groupValues = group.values;
374
- queryLogger.log(`[Store] Bucket ${bucketIndex === -1 ? '(-1: Never Loaded)' : bucketIndex} (minTime: ${lastTime === -1 ? 'Never' : new Date(lastTime).toISOString()}) fetching ${groupValues.length} IDs.`);
375
- // Chunk into 30s
376
- for (let i = 0; i < groupValues.length; i += 30) {
377
- const chunk = groupValues.slice(i, i + 30);
378
- const batchedParams: QueryParams = [[field, 'in', chunk]];
379
- queryLogger.log(`[Store] -> Fetching chunk of ${chunk.length} IDs...`);
380
-
381
- // Fetch changed entities
382
- let queryParamsWithTime: QueryParams;
383
- if (lastTime === -1) {
384
- queryParamsWithTime = [...batchedParams, ['_deleted', '==', false]];
385
- } else {
386
- queryParamsWithTime = [
387
- ...batchedParams,
388
- ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
389
- ['_deleted', '==', false],
390
- ];
391
- }
392
- const entitiesDelta: S[] = await db.getEntities(collectionName, queryParamsWithTime, {});
393
- if (entitiesDelta.length > 0) {
394
- queryLogger.log(`[Store] -> Loaded ${entitiesDelta.length} updated/new entities from chunk.`);
395
- }
396
- patchState(store, setEntities<S>(entitiesDelta, { selectId }));
397
-
398
- // Fetch soft-deleted entities
399
- let deletedParamsWithTime: QueryParams;
400
- if (lastTime === -1) {
401
- deletedParamsWithTime = [...batchedParams, ['_deleted', '==', true]];
402
- } else {
403
- deletedParamsWithTime = [
404
- ...batchedParams,
405
- ['_updatedAt', '>', Timestamp.fromMillis(lastTime)],
406
- ['_deleted', '==', true],
407
- ];
408
- }
409
- const entitiesDeletedDelta: S[] = await db.getEntities(collectionName, deletedParamsWithTime, {});
410
- if (entitiesDeletedDelta.length > 0) {
411
- queryLogger.log(`[Store] -> Removed ${entitiesDeletedDelta.length} soft-deleted entities from chunk.`);
412
- }
413
- patchState(store, removeEntities(entitiesDeletedDelta.map(selectId) as string[]));
414
- }
415
- }));
416
-
417
- // 4. Update entityLoadTime for all fetched values to the unified newLoadTime
418
- valuesToLoad.forEach((val) => cachedLoads.setEntityLoadTime(collectionName, field, val, newLoadTime));
419
- }
420
- }
421
- }
422
-
423
- if (loadQueries) {
424
- // retrieve entities from store for loading queries
425
- // note we cannot simply use entities from load since it may not be all entities (only those for which updatedAt > lastLoadTime)
426
- const allQueriedEntities = store.selectEntities(queryParams, queryOptions);
427
- await processLoadQueries<S>(allQueriedEntities, loadQueries);
428
- }
429
- } catch (e) {
430
- console.error(e);
431
- throw e;
432
- } finally {
433
- // stop loading icon
434
- options?.loading?.set(false);
435
- }
436
- },
437
- async count(
438
- queryParams: QueryParams,
439
- queryOptions: QueryOptions,
440
- options?: {
441
- loading?: WritableSignal<boolean>,
442
- },
443
- ): Promise<number> {
444
- try {
445
- // start loading icon if available
446
- options?.loading?.set(true);
447
-
448
- const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
449
- return await db.count(collectionName, queryParamsNotDeleted, queryOptions);
450
- } catch (e) {
451
- console.error(e);
452
- throw e;
453
- } finally {
454
- // stop loading icon
455
- options?.loading?.set(false);
456
- }
457
- },
458
- async aggregate<T extends { [k: string]: number }>(
459
- queryParams: QueryParams,
460
- queryOptions: QueryOptions,
461
- aggregateParams: { [K in keyof T]: [string] | [string, string] },
462
- options?: {
463
- loading?: WritableSignal<boolean>,
464
- },
465
- ): Promise<{ [K in keyof T]: number }> {
466
- try {
467
- // start loading icon if available
468
- options?.loading?.set(true);
469
-
470
- const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];
471
- return await db.aggregate<T>(
472
- collectionName, queryParamsNotDeleted, queryOptions, aggregateParams,
473
- );
474
- } catch (e) {
475
- console.error(e);
476
- throw e;
477
- } finally {
478
- // stop loading icon
479
- options?.loading?.set(false);
480
- }
481
- },
482
- async increment(id: string, field: string, delta: number, options?: {
483
- loading?: WritableSignal<boolean>,
484
- optimistic?: boolean
485
- }) {
486
- // get current value
487
- const currEntityValue = store.entityMap()[id];
488
- const changes = {};
489
- changes[field] = (currEntityValue[field] || 0) + delta;
490
- changes['_updatedAt'] = Timestamp.now();
491
-
492
- if (options?.optimistic) {
493
- try {
494
- // optimistically set then query backend
495
- patchState(store, updateEntity({
496
- id,
497
- changes: Object.assign({}, changes, {
498
- _updatedAt: Timestamp.now(),
499
- }) as Partial<NoInfer<S>>,
500
- }, { selectId }));
501
- await db.incrementEntityField(collectionName, id, field, delta);
502
- } catch (e) {
503
- // undo ngrx store value
504
- if (currEntityValue) {
505
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
506
- } else {
507
- patchState(store, removeEntity(id));
508
- }
509
- console.error(e);
510
- throw e;
511
- }
512
- } else {
513
- try {
514
- // start loading icon
515
- options?.loading?.set(true);
516
-
517
- // update entity
518
- await db.incrementEntityField(collectionName, id, field, delta);
519
- patchState(store, updateEntity({
520
- id,
521
- changes: Object.assign({}, changes, {
522
- _updatedAt: Timestamp.now(),
523
- }) as Partial<NoInfer<S>>,
524
- }, { selectId }));
525
- } catch (e) {
526
- console.error(e);
527
- throw e;
528
- } finally {
529
- // stop loading icon
530
- options?.loading?.set(false);
531
- }
532
- }
533
- },
534
- async add(
535
- entityOpId: S | Omit<S, '__id'>,
536
- options?: {
537
- optimistic?: boolean,
538
- loading?: WritableSignal<boolean>,
539
- snackBarConfig?: {
540
- successMessage: string,
541
- failureMessage: string,
542
- undoOnAction?: boolean,
543
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
544
- config?: MatSnackBarConfig<any>,
545
- },
546
- batchConfig?: {
547
- batch: WriteBatchI,
548
- revertBatch: WriteBatchI,
549
- patchFns: Array<() => void>,
550
- revertFns: Array<() => void>,
551
- dbRevertFns: Array<() => void>,
552
- optimistic?: boolean,
553
- }
554
- },
555
- ) {
556
- // Create an __id if one was not provided
557
- const entity: S = Object.assign({}, entityOpId, {
558
- __id: entityOpId['__id'] || db.createId(),
559
- }) as S;
560
-
561
- // Function for setting the entity locally
562
- const patchFn = () => {
563
- patchState(store, setEntity<S>(
564
- Object.assign({}, entity, {
565
- _updatedAt: Timestamp.now(),
566
- _createdAt: Timestamp.now(),
567
- _deleted: false,
568
- }),
569
- { selectId },
570
- ));
571
- };
572
-
573
- // Function for reverting changes for optimistic adds
574
- const currEntityValue = store.entityMap()[entity.__id];
575
- const revertFn = () => {
576
- if (currEntityValue) {
577
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
578
- } else {
579
- patchState(store, removeEntity(entity.__id));
580
- }
581
- };
582
-
583
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
584
- const dbRevertFn = async () => {
585
- try {
586
- if (currEntityValue) {
587
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
588
- } else {
589
- await db.removeEntity(collectionName, entity.__id, options?.batchConfig?.revertBatch);
590
- }
591
- } catch (e) {
592
- console.error(e);
593
- throw e;
594
- }
595
- };
596
-
597
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
598
- options?.batchConfig?.patchFns?.push(patchFn);
599
- options?.batchConfig?.revertFns?.push(revertFn);
600
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
601
-
602
-
603
- // optimistically set locally, then in backend and revert if needed
604
- if (options?.optimistic || options?.batchConfig?.optimistic) {
605
- patchFn();
606
- try {
607
- await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
608
- // it will only go into here when not in a batch setting
609
- // since there is no snackBarConfig in the a batch seting
610
- if (options?.snackBarConfig) {
611
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
612
- }
613
- } catch (e) {
614
- // will only get here when it's not a batch
615
- revertFn();
616
- console.error(e);
617
- if (options?.snackBarConfig) {
618
- snackBar.open(
619
- options.snackBarConfig.failureMessage,
620
- '',
621
- options.snackBarConfig.config,
622
- );
623
- }
624
- throw e;
625
- }
626
- // set in backend and then locally if successful
627
- } else {
628
- // start loading icon
629
- options?.loading?.set(true);
630
- try {
631
- await db.addEntity(collectionName, entity, options?.batchConfig?.batch);
632
- // only patch if not using batch writes since if we're using
633
- // batch writes, we should be patching after the batch write
634
- // is successful
635
- if (!options?.batchConfig?.batch) {
636
- patchFn();
637
- if (options?.snackBarConfig) {
638
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
639
- }
640
- }
641
- } catch (e) {
642
- console.error(e);
643
- // will only get here when it's not a batch
644
- if (options?.snackBarConfig) {
645
- snackBar.open(
646
- options.snackBarConfig.failureMessage,
647
- '',
648
- options.snackBarConfig.config,
649
- );
650
- }
651
- throw e;
652
- } finally {
653
- // stop loading icon
654
- options?.loading?.set(false);
655
- }
656
- }
657
- },
658
- async update(
659
- id: string,
660
- changes: Partial<S>,
661
- options?: {
662
- optimistic?: boolean,
663
- loading?: WritableSignal<boolean>,
664
- snackBarConfig?: {
665
- successMessage: string,
666
- failureMessage: string,
667
- undoOnAction?: boolean,
668
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
669
- config?: MatSnackBarConfig<any>,
670
- },
671
- batchConfig?: {
672
- batch: WriteBatchI,
673
- revertBatch: WriteBatchI,
674
- patchFns?: Array<() => void>,
675
- revertFns: Array<() => void>,
676
- dbRevertFns: Array<() => void>,
677
- optimistic?: boolean,
678
- }
679
- },
680
- ) {
681
- // Function for updating the entity locally
682
- const patchFn = () => {
683
- patchState(store, updateEntity({
684
- id,
685
- changes: Object.assign({}, changes, {
686
- _updatedAt: Timestamp.now(),
687
- }) as Partial<NoInfer<S>>,
688
- }, { selectId }));
689
- };
690
-
691
- // Function for reverting changes for optimistic updates
692
- const currEntityValue = store.entityMap()[id];
693
- const revertFn = () => {
694
- if (currEntityValue) {
695
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
696
- } else {
697
- patchState(store, removeEntity(id));
698
- }
699
- };
700
-
701
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
702
- const dbRevertFn = async () => {
703
- try {
704
- if (currEntityValue) {
705
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
706
- } else {
707
- await db.removeEntity(collectionName, id, options?.batchConfig?.revertBatch);
708
- }
709
- } catch (e) {
710
- console.error(e);
711
- throw e;
712
- }
713
- };
714
-
715
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
716
- options?.batchConfig?.patchFns?.push(patchFn);
717
- options?.batchConfig?.revertFns?.push(revertFn);
718
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
719
-
720
- // optimistically update locally, then in backend and revert if needed
721
- if (options?.optimistic || options?.batchConfig?.optimistic) {
722
- patchFn();
723
- try {
724
- await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
725
- // it will only go into here when not in a batch setting
726
- // since there is no snackBarConfig in the a batch seting
727
- if (options?.snackBarConfig) {
728
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
729
- }
730
- } catch (e) {
731
- // will only get here when it's not a batch
732
- revertFn();
733
- console.error(e);
734
- if (options?.snackBarConfig) {
735
- snackBar.open(
736
- options.snackBarConfig.failureMessage,
737
- '',
738
- options.snackBarConfig.config,
739
- );
740
- }
741
- throw e;
742
- }
743
- // update in backend and then locally if successful
744
- } else {
745
- // start loading icon
746
- options?.loading?.set(true);
747
- try {
748
- await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);
749
- // only patch if not using batch writes since if we're using
750
- // batch writes, we should be patching after the batch write
751
- // is successful
752
- if (!options?.batchConfig?.batch) {
753
- patchFn();
754
- if (options?.snackBarConfig) {
755
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
756
- }
757
- }
758
- } catch (e) {
759
- console.error(e);
760
- // will only get here when it's not a batch
761
- if (options?.snackBarConfig) {
762
- snackBar.open(
763
- options.snackBarConfig.failureMessage,
764
- '',
765
- options.snackBarConfig.config,
766
- );
767
- }
768
- throw e;
769
- } finally {
770
- // stop loading icon
771
- options?.loading?.set(false);
772
- }
773
- }
774
- },
775
- async remove(
776
- id: string,
777
- options?: {
778
- optimistic?: boolean,
779
- loading?: WritableSignal<boolean>,
780
- snackBarConfig?: {
781
- successMessage: string,
782
- failureMessage: string,
783
- undoOnAction?: boolean,
784
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
785
- config?: MatSnackBarConfig<any>,
786
- },
787
- batchConfig?: {
788
- batch: WriteBatchI,
789
- revertBatch: WriteBatchI,
790
- patchFns?: Array<() => void>,
791
- revertFns: Array<() => void>,
792
- dbRevertFns: Array<() => void>,
793
- optimistic?: boolean,
794
- }
795
- },
796
- ) {
797
- // Function for updating the entity locally
798
- const patchFn = () => {
799
- patchState(store, removeEntity(id));
800
- };
801
-
802
- // Function for reverting changes for optimistic deletes
803
- const currEntityValue = store.entityMap()[id];
804
- const revertFn = () => {
805
- if (currEntityValue) {
806
- patchState(store, setEntity<S>(currEntityValue, { selectId }));
807
- }
808
- };
809
-
810
- // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar
811
- const dbRevertFn = async () => {
812
- try {
813
- if (currEntityValue) {
814
- await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);
815
- }
816
- } catch (e) {
817
- console.error(e);
818
- throw e;
819
- }
820
- };
821
-
822
- // Add the patchFn, revertFn, dbRevertFn if this is a batch write
823
- options?.batchConfig?.patchFns?.push(patchFn);
824
- options?.batchConfig?.revertFns?.push(revertFn);
825
- options?.batchConfig?.dbRevertFns?.push(dbRevertFn);
826
-
827
- // optimistically remove locally, then in backend and revert if needed
828
- if (options?.optimistic || options?.batchConfig?.optimistic) {
829
- patchFn();
830
- try {
831
- await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
832
- // it will only go into here when not in a batch setting
833
- // since there is no snackBarConfig in the a batch seting
834
- if (options?.snackBarConfig) {
835
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
836
- }
837
- } catch (e) {
838
- // will only get here when it's not a batch
839
- revertFn();
840
- console.error(e);
841
- if (options?.snackBarConfig) {
842
- snackBar.open(
843
- options.snackBarConfig.failureMessage,
844
- '',
845
- options.snackBarConfig.config,
846
- );
847
- }
848
- throw e;
849
- }
850
- // update in backend and then locally if successful
851
- } else {
852
- // start loading icon
853
- options?.loading?.set(true);
854
- try {
855
- await db.removeEntity(collectionName, id, options?.batchConfig?.batch);
856
- // only patch if not using batch writes since if we're using
857
- // batch writes, we should be patching after the batch write
858
- // is successful
859
- if (!options?.batchConfig?.batch) {
860
- patchFn();
861
- if (options?.snackBarConfig) {
862
- openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);
863
- }
864
- }
865
- } catch (e) {
866
- console.error(e);
867
- // will only get here when it's not a batch
868
- if (options?.snackBarConfig) {
869
- snackBar.open(
870
- options.snackBarConfig.failureMessage,
871
- '',
872
- options.snackBarConfig.config,
873
- );
874
- }
875
- throw e;
876
- } finally {
877
- // stop loading icon
878
- options?.loading?.set(false);
879
- }
880
- }
881
- },
882
- })),
883
- );
884
- }
885
-
886
- /**
887
- * Select entities from store given the entityMap and queries.
888
- * Filters out any entities that have '_deleted' === true. In general
889
- * this shouldn't matter, but in case someone intentionally sets
890
- * the _deleted parameter, this adds more robustness.
891
- * Note: firestore supports setting and querying for null, but not
892
- * undefined. We filter out cases where the value is undefined
893
- * to protect against cases when people are doing a nested query
894
- * and some entity does not have a particular field, e.g.
895
- * [['__hashtagId', '==', q.__hashtagId]] when __hashtagId is
896
- * an optional parameter
897
- */
898
- export function selectEntities<T>(entityMap: Record<string, T>, queryParams: QueryParams, queryOptions: QueryOptions): T[] {
899
- let filteredEntities = [];
900
-
901
- // APPLY '__id', '=='/in FILTERS
902
- const selectIdEqQueries = queryParams.filter((q) => q[0] === '__id' && q[1] === '==' && q[2] !== undefined);
903
- const uniqSelectEqIds = selectIdEqQueries.map((q) => q[2]).filter((q, i, a) => a.indexOf(q) === i);
904
- const selectIdInQueries = queryParams
905
- .filter((q) => q[0] === '__id' && q[1] === 'in' && q[2] !== undefined)
906
- .map((q) => [q[0], q[1], q[2].filter((v) => v !== undefined)])
907
- .filter((q) => q[2].length > 0);
908
-
909
- if (uniqSelectEqIds.length === 1 && entityMap[uniqSelectEqIds[0]] && !entityMap[uniqSelectEqIds[0]]['_deleted']) {
910
- // If there is exactly one '__id', we can start with that to filter
911
- filteredEntities.push(entityMap[uniqSelectEqIds[0]]);
912
- } else if (uniqSelectEqIds.length > 1) {
913
- // If there are more than one select id ==, then there cannot be any matches
914
- return [];
915
- } else if (selectIdInQueries.length > 0) {
916
- // If there is at least one 'in' query, start with that.
917
- const firstInIds = selectIdInQueries[0][2];
918
- filteredEntities = firstInIds.map((id) => entityMap[id]).filter((e) => e && !e['_deleted']);
919
-
920
- // Then apply remaining 'in' filters. See general filter section
921
- // for comments since this is just copied from that.
922
- if (selectIdInQueries.length > 1) {
923
- filteredEntities = filteredEntities.filter((e) => {
924
- return !selectIdInQueries.slice(1).find((f) => {
925
- const [key, rel, val] = f;
926
- return !(val.includes(e[key]));
927
- });
928
- });
929
- }
930
- } else {
931
- // Otherwise, start with the full list and filter further.
932
- filteredEntities = Object.keys(entityMap)
933
- .map((id) => entityMap[id])
934
- .filter((e) => e && !e['_deleted']);
935
- }
936
-
937
- // APPLY REMAINING FILTERS
938
- if (queryParams) {
939
- filteredEntities = filteredEntities.filter((e) => {
940
- // Looks for the first failed filter. If there exists any,
941
- // return false (filter it out)
942
- const filterValue = !queryParams.find((f) => {
943
- const [key, rel, val] = f;
944
-
945
- // already processed '__id', '=='/'in', so always passes this filter
946
- if (key === '__id' && (rel === '==' || rel === 'in')) {
947
- return false;
948
- }
949
-
950
- // value cannot be undefined. if it is, we ignore this query
951
- // parameter (so it always passes)
952
- if (val === undefined) {
953
- return false;
954
- }
955
-
956
- // we try to handle the same operations as Firestore for consistency
957
- switch (rel) {
958
- case '==':
959
- return !(e[key] === val);
960
-
961
- case '!=':
962
- return !(e[key] !== val);
963
-
964
- case '>=':
965
- return !(e[key] >= val);
966
-
967
- case '<=':
968
- return !(e[key] <= val);
969
-
970
- case '>':
971
- return !(e[key] > val);
972
-
973
- case '<':
974
- return !(e[key] < val);
975
-
976
- case 'array-contains':
977
- // If the parameter in question is optional, it should be filtered out
978
- return e[key] ? !e[key].includes(val) : true;
979
-
980
- case 'array-contains-any':
981
- // If the parameter in question is optional, it should be filtered out
982
- return e[key] ? !val.some((v) => e[key].includes(v)) : true;
983
-
984
- case 'in':
985
- return val.length > 0 && !val.includes(e[key]);
986
-
987
- case 'not-in':
988
- return val.includes(e[key]);
989
-
990
- default:
991
- return false;
992
- }
993
- });
994
- return filterValue;
995
- });
996
- }
997
-
998
- // Sort based on orderBy
999
- if (queryOptions?.orderBy) {
1000
- // If orderBy is provided, will only return entities with that property
1001
- // just like the Firestore API
1002
-
1003
- let orderings: [string, string][] = [];
1004
- if (Array.isArray(queryOptions.orderBy)) {
1005
- if (Array.isArray(queryOptions.orderBy[0])) {
1006
- orderings = queryOptions.orderBy as [string, string][];
1007
- } else {
1008
- orderings = [queryOptions.orderBy as [string, string]];
1009
- }
1010
- } else {
1011
- orderings = [[queryOptions.orderBy as string, 'asc']];
1012
- }
1013
-
1014
- // Filter out entities missing any of the orderBy fields
1015
- for (const [field] of orderings) {
1016
- filteredEntities = filteredEntities.filter((e) => e[field] !== undefined && e[field] !== null);
1017
- }
1018
-
1019
- filteredEntities.sort((a, b) => {
1020
- for (const [field, order] of orderings) {
1021
- if (a[field] < b[field]) return order === 'desc' ? 1 : -1;
1022
- if (a[field] > b[field]) return order === 'desc' ? -1 : 1;
1023
- }
1024
- return 0;
1025
- });
1026
- }
1027
-
1028
- // Filter based on startAt/startAfter/endAt/endAfter
1029
- // Note: Only supports single field orderBy for cursor pagination in local store mock for now
1030
- if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
1031
- queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
1032
- let primaryField = '';
1033
- if (Array.isArray(queryOptions.orderBy)) {
1034
- if (Array.isArray(queryOptions.orderBy[0])) {
1035
- primaryField = queryOptions.orderBy[0][0];
1036
- } else {
1037
- primaryField = queryOptions.orderBy[0] as string;
1038
- }
1039
- } else {
1040
- primaryField = queryOptions.orderBy as string;
1041
- }
1042
-
1043
- filteredEntities = filteredEntities.filter((e) => {
1044
- const value = e[primaryField];
1045
- if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
1046
- return false;
1047
- }
1048
- if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
1049
- return false;
1050
- }
1051
- if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
1052
- return false;
1053
- }
1054
- if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
1055
- return false;
1056
- }
1057
- return true;
1058
- });
1059
- }
1060
-
1061
- // Limit based on limit
1062
- if (queryOptions?.limit !== undefined) {
1063
- filteredEntities = filteredEntities.slice(0, queryOptions.limit);
1064
- }
1065
-
1066
- return filteredEntities;
1067
- }
1068
-
1069
- /**
1070
- * Check whether the entity satisfies the query results.
1071
- * We use this to double-check whether a 'removed' change was truly
1072
- * removed from the backend or whether it just doesn't match
1073
- * the query anymore.
1074
- */
1075
- export function entityInQueryResults<T>(e: T, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
1076
- if (queryParams) {
1077
- // Looks for the first failed filter. If there exists any,
1078
- // return false
1079
- const inQueryParams = !queryParams.find((f) => {
1080
- const [key, rel, val] = f;
1081
-
1082
- // value cannot be undefined. if it is, we ignore this query
1083
- // parameter (so it always passes)
1084
- if (val === undefined) {
1085
- return false;
1086
- }
1087
-
1088
- // we try to handle the same operations as Firestore for consistency
1089
- switch (rel) {
1090
- case '==':
1091
- return !(e[key] === val);
1092
-
1093
- case '!=':
1094
- return !(e[key] !== val);
1095
-
1096
- case '>=':
1097
- return !(e[key] >= val);
1098
-
1099
- case '<=':
1100
- return !(e[key] <= val);
1101
-
1102
- case '>':
1103
- return !(e[key] > val);
1104
-
1105
- case '<':
1106
- return !(e[key] < val);
1107
-
1108
- case 'array-contains':
1109
- // If the parameter in question is optional, it should be filtered out
1110
- return e[key] ? !e[key].includes(val) : true;
1111
-
1112
- case 'array-contains-any':
1113
- // If the parameter in question is optional, it should be filtered out
1114
- return e[key] ? !val.some((v) => e[key].includes(v)) : true;
1115
-
1116
- case 'in':
1117
- return !val.includes(e[key]);
1118
-
1119
- case 'not-in':
1120
- return val.includes(e[key]);
1121
-
1122
- default:
1123
- return false;
1124
- }
1125
- });
1126
-
1127
- if (!inQueryParams) {
1128
- return false;
1129
- }
1130
- }
1131
-
1132
- // Filter based on startAt/startAfter/endAt/endAfter
1133
- if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
1134
- queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
1135
- const value = e[queryOptions.orderBy as string];
1136
- if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
1137
- return false;
1138
- }
1139
- if (queryOptions.startAfter !== undefined && value <= queryOptions.startAfter) {
1140
- return false;
1141
- }
1142
- if (queryOptions.endAt !== undefined && value > queryOptions.endAt) {
1143
- return false;
1144
- }
1145
- if (queryOptions.endBefore !== undefined && value >= queryOptions.endBefore) {
1146
- return false;
1147
- }
1148
- }
1149
-
1150
- return true;
1151
- }
1152
-
1153
- export async function processLoadQueries<T extends { __id: string }>(entities: T[], loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[]) {
1154
- if (entities.length > 0) {
1155
- // create a matrix of queries, each row corresponding to a given entity
1156
- const queriesByEntity = entities.map((entity) => loadQueries!(entity));
1157
-
1158
- // transpose the matrix so each row corresponds to all queries for the same query type
1159
- const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
1160
-
1161
- // Process all query types concurrently
1162
- await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
1163
- // Seeing if we can optimize by collapsing equality queries into 'in' queries
1164
- const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);
1165
-
1166
- // Process queries concurrently using Promise.all
1167
- await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
1168
- // Firestore throws an error if an 'in' query is executed with an empty array.
1169
- // Therefore, we skip executing any queries that have an 'in' clause with an empty array.
1170
- // Example: ['__id', 'in', []]
1171
- if (!query.queryParams.some((param) => Array.isArray(param[2]) && param[2].length === 0 && param[1] === 'in')) {
1172
- await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);
1173
- }
1174
- }));
1175
- }));
1176
- }
1177
- }
1178
-
1179
- export class EntityLoadQuery<T> {
1180
- collection: string;
1181
- queryParams: QueryParams;
1182
- queryOptions: QueryOptions;
1183
- loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[];
1184
- store;
1185
-
1186
- constructor(
1187
- collection: string,
1188
- store,
1189
- queryParams: QueryParams,
1190
- queryOptions: QueryOptions,
1191
- loadQueries?: (entity: T) => EntityLoadQuery<AnyEntity>[],
1192
- ) {
1193
- this.collection = collection;
1194
- this.queryParams = queryParams;
1195
- this.queryOptions = queryOptions;
1196
- this.loadQueries = loadQueries;
1197
- this.store = store;
1198
- }
1199
-
1200
- // Checks if there is a single equality query of the same type
1201
- // that could be transformed into an 'in' query
1202
- static areBatchableEqualityQueries<T>(queries: EntityLoadQuery<T>[]): boolean {
1203
- if (queries.length === 0) return false;
1204
-
1205
- // check if there is only one queryParam for each query and no queryOptions
1206
- const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1207
- return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1208
- });
1209
-
1210
- if (!hasSingleQueryParamAndNoOptions) return false;
1211
-
1212
- // Finally, verify that every query is filtering on the exact same field
1213
- // (e.g., they are all querying '__userId') AND that they are all using the
1214
- // exact equality operator ('=='). This ensures they can be safely collapsed
1215
- // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1216
- const firstField = queries[0].queryParams[0][0];
1217
- return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1218
- }
1219
-
1220
- // This currently only optimizes for N+1 queries, transforming input queries
1221
- // with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
1222
- // Transform this into 'in' queries, combining up to 30 equality clauses
1223
- // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1224
- static optimize<T>(queries: EntityLoadQuery<T>[]): EntityLoadQuery<T>[] {
1225
- // Optimization: batch N individual equality queries (e.g. [['__userId', '==', x]])
1226
- // into ceil(N/30) Firestore 'in' queries. This solves the N+1 problem where
1227
- // streaming N parent entities would otherwise create N individual child listeners.
1228
- //
1229
- // Tradeoff: batching changes the query key, which means per-query lastLoadTime
1230
- // tracking cannot efficiently provide incremental (delta-only) loads when the
1231
- // batch composition changes (entity added/removed). However, the reduction from
1232
- // N separate DB reads to 1 batched read far outweighs the cost of occasionally
1233
- // re-fetching already-loaded child documents.
1234
-
1235
- if (this.areBatchableEqualityQueries<T>(queries)) {
1236
- // get the field we are querying against
1237
- const collection: string = queries[0].collection;
1238
- const field: string = queries[0].queryParams[0][0];
1239
- const loadQs: (entity: T) => EntityLoadQuery<AnyEntity>[] = queries[0].loadQueries;
1240
-
1241
- // We no longer chunk into groups of 30 here. Instead, we bundle ALL IDs into a single 'in'
1242
- // query. The `load()` method will intercept this unified query, generate a single `newLoadTime`,
1243
- // and perform the 30-item chunking internally. This guarantees that all entities requested
1244
- // together receive the exact same timestamp.
1245
- const ids = queries.map((q) => q.queryParams[0][2]);
1246
- return [new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs)];
1247
- } else {
1248
- return queries;
1249
- }
1250
- }
1251
- }
1252
-
1253
- export class EntityStreamQuery<T> {
1254
- collection: string;
1255
- queryParams: QueryParams;
1256
- queryOptions: QueryOptions;
1257
- streamQueries: (entity: T) => EntityStreamQuery<AnyEntity>[];
1258
- store;
1259
-
1260
- constructor(
1261
- collection: string,
1262
- store,
1263
- queryParams: QueryParams,
1264
- queryOptions: QueryOptions,
1265
- streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
1266
- ) {
1267
- this.collection = collection;
1268
- this.queryParams = queryParams;
1269
- this.queryOptions = queryOptions;
1270
- this.streamQueries = streamQueries;
1271
- this.store = store;
1272
- }
1273
-
1274
- // Checks if there is a single equality query of the same type
1275
- // that could be transformed into an 'in' query
1276
- static areBatchableEqualityQueries<T>(queries: EntityStreamQuery<T>[]): boolean {
1277
- if (queries.length === 0) return false;
1278
-
1279
- // check if there is only one queryParam for each query and no queryOptions
1280
- const hasSingleQueryParamAndNoOptions = queries.every((q) => {
1281
- return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);
1282
- });
1283
-
1284
- if (!hasSingleQueryParamAndNoOptions) return false;
1285
-
1286
- // Finally, verify that every query is filtering on the exact same field
1287
- // (e.g., they are all querying '__userId') AND that they are all using the
1288
- // exact equality operator ('=='). This ensures they can be safely collapsed
1289
- // into a single 'in' query (e.g., '__userId in [1, 2, 3]').
1290
- const firstField = queries[0].queryParams[0][0];
1291
- return queries.every((q) => q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');
1292
- }
1293
-
1294
- // This currently only optimizes for N+1 queries, transforming input queries
1295
- // with a single where equality query (e.g. [['__postId', '==', x]]) and no queryParams.
1296
- // Transform this into 'in' queries, combining up to 30 equality clauses
1297
- // at the same time, https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.
1298
- static optimize<T>(queries: EntityStreamQuery<T>[]): EntityStreamQuery<T>[] {
1299
- // Optimization: batch N individual equality queries into ceil(N/30) Firestore
1300
- // 'in' queries. For streams, the pairwise() diffing in processStreamQuery()
1301
- // ensures that only changed parent entities trigger nested queries. This means
1302
- // the initial batch of N entities gets optimally collapsed, while subsequent
1303
- // individual changes create small (typically 1-element) listeners.
1304
- //
1305
- // Listener lifecycle: batched 'in' listeners share the parent component's
1306
- // DestroyRef for cleanup, matching the behavior of individual listeners.
1307
-
1308
- if (this.areBatchableEqualityQueries<T>(queries)) {
1309
- // get the field we are querying against
1310
- const collection: string = queries[0].collection;
1311
- const field: string = queries[0].queryParams[0][0];
1312
- const streamQs: (entity: T) => EntityStreamQuery<AnyEntity>[] = queries[0].streamQueries;
1313
-
1314
- const ids = queries.map((q) => q.queryParams[0][2]);
1315
- return [new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs)];
1316
- } else {
1317
- return queries;
1318
- }
1319
- }
1320
- }