@hyper-fetch/firebase-admin 10.0.0 → 10.1.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 (62) hide show
  1. package/README.md +111 -63
  2. package/__tests__/features/constraints/constraints.base.spec.ts +44 -0
  3. package/__tests__/features/constraints/listener-extra.types.spec.ts +14 -0
  4. package/__tests__/features/constraints/query-params.types.spec.ts +83 -0
  5. package/__tests__/features/firestore/admin/constraints.admin.spec.ts +1 -0
  6. package/__tests__/features/firestore/admin/sockets.base.spec.ts +4 -1
  7. package/__tests__/features/firestore/shared/constraints.shared.tests.ts +87 -6
  8. package/__tests__/features/firestore/shared/methods/get-doc.test.suite.ts +15 -0
  9. package/__tests__/features/firestore/shared/methods/get-docs.test.suite.ts +1 -1
  10. package/__tests__/features/firestore/shared/methods/on-snapshot.test.suite.ts +79 -5
  11. package/__tests__/features/firestore/shared/methods/update-doc.test.suite.ts +1 -0
  12. package/__tests__/features/firestore/shared/methods.shared.tests.ts +2 -2
  13. package/__tests__/features/realtime/shared/constraints.shared.tests.ts +58 -8
  14. package/__tests__/features/realtime/shared/methods/get.test.suite.ts +23 -0
  15. package/__tests__/features/realtime/shared/methods/on-value.test.suite.ts +108 -5
  16. package/__tests__/features/realtime/shared/methods/push.test.suite.ts +3 -3
  17. package/__tests__/features/realtime/shared/methods/remove.test.suite.ts +3 -3
  18. package/__tests__/features/realtime/shared/methods/update.test.suite.ts +3 -3
  19. package/__tests__/shared/request-events.shared.ts +1 -4
  20. package/dist/adapter/adapter.d.ts +19 -0
  21. package/dist/adapter/adapter.d.ts.map +1 -1
  22. package/dist/adapter/adapter.sockets.d.ts +17 -0
  23. package/dist/adapter/adapter.sockets.d.ts.map +1 -1
  24. package/dist/adapter/types/adapter.firestore.types.d.ts +28 -6
  25. package/dist/adapter/types/adapter.firestore.types.d.ts.map +1 -1
  26. package/dist/adapter/types/adapter.realtime.types.d.ts +26 -6
  27. package/dist/adapter/types/adapter.realtime.types.d.ts.map +1 -1
  28. package/dist/adapter/types/firestore.socket.types.d.ts +6 -4
  29. package/dist/adapter/types/firestore.socket.types.d.ts.map +1 -1
  30. package/dist/adapter/types/realtime.socket.types.d.ts +2 -4
  31. package/dist/adapter/types/realtime.socket.types.d.ts.map +1 -1
  32. package/dist/constraints/constraints.builder.d.ts +98 -0
  33. package/dist/constraints/constraints.builder.d.ts.map +1 -0
  34. package/dist/constraints/firebase.constraints.d.ts +109 -1
  35. package/dist/constraints/firebase.constraints.d.ts.map +1 -1
  36. package/dist/constraints/index.d.ts +1 -0
  37. package/dist/constraints/index.d.ts.map +1 -1
  38. package/dist/firestore/firestore.sockets.d.ts.map +1 -1
  39. package/dist/index.mjs +277 -94
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/realtime/realtime.methods.d.ts +7 -5
  42. package/dist/realtime/realtime.methods.d.ts.map +1 -1
  43. package/dist/realtime/realtime.sockets.d.ts.map +1 -1
  44. package/dist/utils/misc.d.ts.map +1 -1
  45. package/package.json +1 -1
  46. package/src/adapter/adapter.sockets.ts +17 -0
  47. package/src/adapter/adapter.ts +77 -46
  48. package/src/adapter/types/adapter.firestore.types.ts +40 -7
  49. package/src/adapter/types/adapter.realtime.types.ts +39 -7
  50. package/src/adapter/types/firestore.socket.types.ts +10 -2
  51. package/src/adapter/types/realtime.socket.types.ts +6 -3
  52. package/src/constraints/constraints.builder.ts +214 -0
  53. package/src/constraints/firebase.constraints.ts +111 -3
  54. package/src/constraints/index.ts +1 -0
  55. package/src/firestore/firestore.methods.ts +8 -8
  56. package/src/firestore/firestore.sockets.ts +65 -56
  57. package/src/firestore/utils/constraints.utils.ts +4 -4
  58. package/src/realtime/realtime.methods.ts +19 -20
  59. package/src/realtime/realtime.sockets.ts +57 -52
  60. package/src/realtime/utils/constraints.utils.ts +10 -10
  61. package/src/utils/misc.ts +1 -1
  62. package/vite.config.ts +2 -0
@@ -1,16 +1,24 @@
1
+ import type { DefaultMapperType } from "@hyper-fetch/core";
1
2
  import type { SocketAdapter } from "@hyper-fetch/sockets";
2
- import type { FirestoreQueryParams } from "adapter";
3
+ import type { FirestoreListenerOptions, FirestoreListenerQueryParams, FirestoreStatuses } from "adapter";
3
4
  import type { DocumentReference, DocumentSnapshot, DocumentData, Query, QuerySnapshot } from "firebase-admin/firestore";
4
5
 
5
6
  export type FirestoreAdminSocketAdapterType = SocketAdapter<
6
7
  FirestoreAdminOnSnapshotExtra,
7
8
  undefined,
8
- { groupByChangeType?: boolean } & FirestoreQueryParams
9
+ FirestoreListenerOptions,
10
+ undefined,
11
+ undefined,
12
+ DefaultMapperType,
13
+ FirestoreListenerQueryParams
9
14
  >;
10
15
 
11
16
  export type FirestoreAdminOnSnapshotExtra = {
12
17
  ref?: DocumentReference | Query;
13
18
  snapshot?: DocumentSnapshot | QuerySnapshot;
14
19
  unsubscribe?: () => void;
20
+ /** Grouped document changes when the listener has `groupByChangeType`, otherwise `null`. Collection listeners only. */
15
21
  groupedResult: { added: DocumentData[]; modified: DocumentData[]; removed: DocumentData[] } | null;
22
+ /** `"emptyResource"` when the document is missing or the result list is empty. */
23
+ status: FirestoreStatuses;
16
24
  };
@@ -1,12 +1,15 @@
1
1
  import type { SocketAdapter } from "@hyper-fetch/sockets";
2
- import type { RealtimeDBQueryParams, RealtimeDBStatuses } from "adapter/index";
2
+ import type { RealtimeDBListenerOptions, RealtimeDBListenerQueryParams, RealtimeDBStatuses } from "adapter/index";
3
3
  import type { Reference, DataSnapshot } from "firebase-admin/database";
4
4
 
5
5
  export type RealtimeAdminSocketAdapterType = SocketAdapter<
6
6
  any,
7
7
  RealtimeAdminOnValueMethodExtra,
8
- { onlyOnce?: boolean } & RealtimeDBQueryParams,
9
- any
8
+ RealtimeDBListenerOptions,
9
+ any,
10
+ any,
11
+ any,
12
+ RealtimeDBListenerQueryParams
10
13
  >;
11
14
 
12
15
  export type RealtimeAdminOnValueMethodExtra = {
@@ -0,0 +1,214 @@
1
+ import type { OrderByDirection, WhereFilterOp } from "firebase-admin/firestore";
2
+
3
+ import type { FirestorePermittedMethods, RealtimePermittedMethods } from "./constraints.types";
4
+ import {
5
+ $endAt,
6
+ $endBefore,
7
+ $equalTo,
8
+ $limit,
9
+ $limitToFirst,
10
+ $limitToLast,
11
+ $orderBy,
12
+ $orderByChild,
13
+ $orderByKey,
14
+ $orderByValue,
15
+ $startAfter,
16
+ $startAt,
17
+ $where,
18
+ } from "./firebase.constraints";
19
+
20
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined | Date;
21
+ type IsAny<T> = 0 extends 1 & T ? true : false;
22
+ type PreviousDepth = [never, 0, 1, 2, 3, 4];
23
+
24
+ /**
25
+ * Paths to the fields of a document, nested objects included (up to 4 levels), joined with `Separator`: `.` for
26
+ * Firestore field paths, `/` for Realtime Database child paths. The `__key` id added by the adapter is not a field.
27
+ */
28
+ export type FieldPath<Doc, Separator extends string = ".", Depth extends number = 4> =
29
+ IsAny<Doc> extends true
30
+ ? string
31
+ : [Depth] extends [never]
32
+ ? never
33
+ : Doc extends Primitive | readonly any[]
34
+ ? never
35
+ : {
36
+ [Key in Exclude<keyof Doc, "__key"> & string]: NonNullable<Doc[Key]> extends Primitive | readonly any[]
37
+ ? Key
38
+ : Key | `${Key}${Separator}${FieldPath<NonNullable<Doc[Key]>, Separator, PreviousDepth[Depth]>}`;
39
+ }[Exclude<keyof Doc, "__key"> & string];
40
+
41
+ /** Value type of the field at `Path`. */
42
+ export type FieldValue<Doc, Path extends string, Separator extends string = "."> =
43
+ IsAny<Doc> extends true
44
+ ? any
45
+ : Path extends `${infer Key}${Separator}${infer Rest}`
46
+ ? Key extends keyof Doc
47
+ ? FieldValue<NonNullable<Doc[Key]>, Rest, Separator>
48
+ : never
49
+ : Path extends keyof Doc
50
+ ? Doc[Path]
51
+ : never;
52
+
53
+ /** Value a Firestore `where` takes for an operator: arrays for `in` / `not-in`, an element for `array-contains`. */
54
+ export type WhereValue<Value, Operator extends WhereFilterOp> = Operator extends "in" | "not-in"
55
+ ? Value[]
56
+ : Operator extends "array-contains"
57
+ ? NonNullable<Value> extends readonly (infer Element)[]
58
+ ? Element
59
+ : never
60
+ : Operator extends "array-contains-any"
61
+ ? NonNullable<Value> extends readonly (infer Element)[]
62
+ ? Element[]
63
+ : never
64
+ : Value;
65
+
66
+ type CursorPrefixes<Values extends unknown[]> = Values extends [...infer Init, any]
67
+ ? Values | (Init extends [] ? never : CursorPrefixes<Init>)
68
+ : never;
69
+
70
+ /** Cursor values: one per `orderBy`, in order (a prefix is allowed), or a document id without `orderBy`. */
71
+ export type FirestoreCursorValues<Ordered extends unknown[]> = Ordered extends []
72
+ ? [documentId: string]
73
+ : CursorPrefixes<Ordered>;
74
+
75
+ /**
76
+ * Typed Firestore constraints for a document type, built as a chain. Received by the `queryParams` callback of
77
+ * Firestore requests and listeners; the adapter stores the constraints it collected.
78
+ *
79
+ * @example
80
+ * getTeas.send({ queryParams: (c) => c.where("type", "==", "Green").orderBy("year", "desc").limit(20) });
81
+ */
82
+ export interface FirestoreConstraints<Doc = any, Ordered extends unknown[] = []> {
83
+ /** Filter by a field, like Firestore's `where()`. The value type follows the field and the operator. */
84
+ where<Path extends FieldPath<Doc>, Operator extends WhereFilterOp>(
85
+ field: Path,
86
+ operator: Operator,
87
+ value: WhereValue<FieldValue<Doc, Path>, Operator>,
88
+ ): FirestoreConstraints<Doc, Ordered>;
89
+ /** Order by a field, like Firestore's `orderBy()`. Each `orderBy` adds one value the cursors take. */
90
+ orderBy<Path extends FieldPath<Doc>>(
91
+ field: Path,
92
+ direction?: OrderByDirection,
93
+ ): FirestoreConstraints<Doc, [...Ordered, FieldValue<Doc, Path>]>;
94
+ /** Limit the number of documents, like Firestore's `limit()`. */
95
+ limit(limit: number): FirestoreConstraints<Doc, Ordered>;
96
+ /** Start at these values, inclusive: one per `orderBy`, in order. */
97
+ startAt(...values: FirestoreCursorValues<Ordered>): FirestoreConstraints<Doc, Ordered>;
98
+ /** Start after these values, exclusive. Pass the values of the last document to load the next page. */
99
+ startAfter(...values: FirestoreCursorValues<Ordered>): FirestoreConstraints<Doc, Ordered>;
100
+ /** End at these values, inclusive: one per `orderBy`, in order. */
101
+ endAt(...values: FirestoreCursorValues<Ordered>): FirestoreConstraints<Doc, Ordered>;
102
+ /** End before these values, exclusive: one per `orderBy`, in order. */
103
+ endBefore(...values: FirestoreCursorValues<Ordered>): FirestoreConstraints<Doc, Ordered>;
104
+ /** The collected constraints, the data a request or listener stores. */
105
+ toJSON(): FirestorePermittedMethods[];
106
+ }
107
+
108
+ /**
109
+ * Typed Realtime Database constraints for the type of a list's children, built as a chain. A query can have one
110
+ * `orderBy*`; cursors and `equalTo` become available after it and take the ordered value.
111
+ *
112
+ * @example
113
+ * getMessages.send({ queryParams: (c) => c.orderByChild("sentAt").limitToLast(50) });
114
+ */
115
+ export interface RealtimeConstraints<Doc = any> {
116
+ /** Order by a child value, like `orderByChild()`. Nested children use `/`: `"author/name"`. */
117
+ orderByChild<Path extends FieldPath<Doc, "/">>(
118
+ path: Path,
119
+ ): OrderedRealtimeConstraints<Doc, FieldValue<Doc, Path, "/">>;
120
+ /** Order by key, like `orderByKey()`. */
121
+ orderByKey(): OrderedRealtimeConstraints<Doc, string>;
122
+ /** Order by the children's own values, like `orderByValue()`. */
123
+ orderByValue(): OrderedRealtimeConstraints<Doc, Doc>;
124
+ /** Limit to the first children, like `limitToFirst()`. */
125
+ limitToFirst(limit: number): RealtimeConstraints<Doc>;
126
+ /** Limit to the last children, like `limitToLast()`. */
127
+ limitToLast(limit: number): RealtimeConstraints<Doc>;
128
+ /** The collected constraints, the data a request or listener stores. */
129
+ toJSON(): RealtimePermittedMethods[];
130
+ }
131
+
132
+ /** Realtime Database constraints after an `orderBy*`. Cursors and `equalTo` take the ordered value and a tie key. */
133
+ export interface OrderedRealtimeConstraints<Doc = any, Value = any> {
134
+ /** Limit to the first children, like `limitToFirst()`. */
135
+ limitToFirst(limit: number): OrderedRealtimeConstraints<Doc, Value>;
136
+ /** Limit to the last children, like `limitToLast()`. */
137
+ limitToLast(limit: number): OrderedRealtimeConstraints<Doc, Value>;
138
+ /** Keep children whose ordered value equals `value`, like `equalTo()`. */
139
+ equalTo(value: Value, key?: string): OrderedRealtimeConstraints<Doc, Value>;
140
+ /** Start at `value`, inclusive. `key` breaks ties between equal values. */
141
+ startAt(value: Value, key?: string): OrderedRealtimeConstraints<Doc, Value>;
142
+ /** Start after `value`, exclusive. `key` breaks ties between equal values. */
143
+ startAfter(value: Value, key?: string): OrderedRealtimeConstraints<Doc, Value>;
144
+ /** End at `value`, inclusive. `key` breaks ties between equal values. */
145
+ endAt(value: Value, key?: string): OrderedRealtimeConstraints<Doc, Value>;
146
+ /** End before `value`, exclusive. `key` breaks ties between equal values. */
147
+ endBefore(value: Value, key?: string): OrderedRealtimeConstraints<Doc, Value>;
148
+ /** The collected constraints, the data a request or listener stores. */
149
+ toJSON(): RealtimePermittedMethods[];
150
+ }
151
+
152
+ /** Untyped shape of the chains below; the factories cast it to the typed interfaces. */
153
+ type AnyChain = Record<string, (...args: any[]) => unknown>;
154
+
155
+ const firestoreChain = (constraints: FirestorePermittedMethods[]): AnyChain => {
156
+ const add = (constraint: FirestorePermittedMethods) => firestoreChain([...constraints, constraint]);
157
+ return {
158
+ where: (field: string, operator: WhereFilterOp, value: unknown) => add($where(field, operator, value)),
159
+ orderBy: (field: string, direction?: OrderByDirection) => add($orderBy(field, direction)),
160
+ limit: (limit: number) => add($limit(limit)),
161
+ startAt: (...values: unknown[]) => add($startAt(...values)),
162
+ startAfter: (...values: unknown[]) => add($startAfter(...values)),
163
+ endAt: (...values: unknown[]) => add($endAt(...values)),
164
+ endBefore: (...values: unknown[]) => add($endBefore(...values)),
165
+ toJSON: () => constraints,
166
+ };
167
+ };
168
+
169
+ const realtimeChain = (constraints: RealtimePermittedMethods[]): AnyChain => {
170
+ const add = (constraint: RealtimePermittedMethods) => realtimeChain([...constraints, constraint]);
171
+ return {
172
+ orderByChild: (path: string) => add($orderByChild(path)),
173
+ orderByKey: () => add($orderByKey()),
174
+ orderByValue: () => add($orderByValue()),
175
+ limitToFirst: (limit: number) => add($limitToFirst(limit)),
176
+ limitToLast: (limit: number) => add($limitToLast(limit)),
177
+ equalTo: (value: unknown, key?: string) => add($equalTo(value, key)),
178
+ startAt: (value: unknown, key?: string) => add(key === undefined ? $startAt(value) : $startAt(value, key)),
179
+ startAfter: (value: unknown, key?: string) => add(key === undefined ? $startAfter(value) : $startAfter(value, key)),
180
+ endAt: (value: unknown, key?: string) => add(key === undefined ? $endAt(value) : $endAt(value, key)),
181
+ endBefore: (value: unknown, key?: string) => add(key === undefined ? $endBefore(value) : $endBefore(value, key)),
182
+ toJSON: () => constraints,
183
+ };
184
+ };
185
+
186
+ /** Start an empty Firestore constraints chain. The adapter passes one to every `queryParams` callback. */
187
+ export const createFirestoreConstraints = <Doc = any>(): FirestoreConstraints<Doc> =>
188
+ firestoreChain([]) as unknown as FirestoreConstraints<Doc>;
189
+
190
+ /** Start an empty Realtime Database constraints chain. The adapter passes one to every `queryParams` callback. */
191
+ export const createRealtimeConstraints = <Doc = any>(): RealtimeConstraints<Doc> =>
192
+ realtimeChain([]) as unknown as RealtimeConstraints<Doc>;
193
+
194
+ /** Resolve a `queryParams` callback with a fresh chain into the constraints it collected. */
195
+ export const resolveConstraints =
196
+ (createChain: () => { toJSON(): unknown[] }) => (callback: (...args: any[]) => unknown) =>
197
+ (callback(createChain()) as { toJSON(): unknown[] }).toJSON();
198
+
199
+ /**
200
+ * The constraints of `queryParams` or listener options: an array, or the deprecated `{ constraints }` object.
201
+ */
202
+ export const getConstraints = <Constraint>(queryParams: unknown): Constraint[] => {
203
+ if (Array.isArray(queryParams)) {
204
+ return queryParams as Constraint[];
205
+ }
206
+ if (
207
+ queryParams &&
208
+ typeof queryParams === "object" &&
209
+ Array.isArray((queryParams as { constraints?: unknown }).constraints)
210
+ ) {
211
+ return (queryParams as { constraints: Constraint[] }).constraints;
212
+ }
213
+ return [];
214
+ };
@@ -21,6 +21,15 @@ export enum FirestoreQueryConstraints {
21
21
  LIMIT = "limit",
22
22
  }
23
23
 
24
+ /**
25
+ * Firestore filter, the HyperFetch form of Firestore's `where()`.
26
+ *
27
+ * @param fieldPath - Field to compare, dot notation reaches nested fields (`"address.city"`)
28
+ * @param opStr - Firestore operator such as `"=="`, `">="`, `"in"` or `"array-contains"`
29
+ * @param value - Value to compare the field with
30
+ * @example
31
+ * getTeas.send({ queryParams: [$where("type", "==", "Green"), $where("year", ">=", 2020)] });
32
+ */
24
33
  export const $where = (fieldPath: string, opStr: WhereFilterOp, value: any) => {
25
34
  return {
26
35
  toString: () => `${FirestoreQueryConstraints.WHERE}_${fieldPath}${opStr}${value}`,
@@ -29,6 +38,15 @@ export const $where = (fieldPath: string, opStr: WhereFilterOp, value: any) => {
29
38
  };
30
39
  };
31
40
 
41
+ /**
42
+ * Firestore ordering, the HyperFetch form of Firestore's `orderBy()`. Cursors take one value per `$orderBy`, in the same
43
+ * order.
44
+ *
45
+ * @param fieldPath - Field to order by
46
+ * @param directionStr - `"asc"` (default) or `"desc"`
47
+ * @example
48
+ * getTeas.send({ queryParams: [$orderBy("year", "desc"), $orderBy("name")] });
49
+ */
32
50
  export const $orderBy = (fieldPath: string, directionStr?: OrderByDirection) => {
33
51
  return {
34
52
  toString: () => `${FirestoreQueryConstraints.ORDER_BY}_${fieldPath}_${directionStr || ""}`,
@@ -37,6 +55,13 @@ export const $orderBy = (fieldPath: string, directionStr?: OrderByDirection) =>
37
55
  };
38
56
  };
39
57
 
58
+ /**
59
+ * Firestore limit, the HyperFetch form of Firestore's `limit()`.
60
+ *
61
+ * @param num - Maximum number of documents to return
62
+ * @example
63
+ * getTeas.send({ queryParams: [$orderBy("year"), $limit(20)] });
64
+ */
40
65
  export const $limit = (num: number) => {
41
66
  return {
42
67
  toString: () => `${FirestoreQueryConstraints.LIMIT}_${num}`,
@@ -62,12 +87,59 @@ const startEndConstraintsImpl = (constraintType: SharedQueryConstraints) => {
62
87
  };
63
88
  };
64
89
 
90
+ /**
91
+ * Cursor that starts the ordered query at the given values, inclusive.
92
+ *
93
+ * In Firestore pass one value per `$orderBy`, in the same order. In Realtime Database pass the value of the
94
+ * `$orderBy*` field and, optionally, a key that breaks ties between equal values.
95
+ *
96
+ * @example
97
+ * // Firestore
98
+ * getTeas.send({ queryParams: [$orderBy("year"), $orderBy("name"), $startAt(2022, "Bi Luo Chun")] });
99
+ * // Realtime Database
100
+ * getTeas.send({ queryParams: [$orderByChild("year"), $startAt(2022)] });
101
+ */
65
102
  export const $startAt = startEndConstraintsImpl(SharedQueryConstraints.START_AT as const);
103
+ /**
104
+ * Cursor that starts the ordered query after the given values, exclusive. Use it to load the next page.
105
+ *
106
+ * In Firestore pass one value per `$orderBy`, in the same order. In Realtime Database pass the value of the
107
+ * `$orderBy*` field and, optionally, a key that breaks ties between equal values.
108
+ *
109
+ * @example
110
+ * const last = page.data?.at(-1);
111
+ * getTeas.send({ queryParams: [$orderBy("year"), $startAfter(last?.year), $limit(20)] });
112
+ */
66
113
  export const $startAfter = startEndConstraintsImpl(SharedQueryConstraints.START_AFTER as const);
67
114
 
115
+ /**
116
+ * Cursor that ends the ordered query at the given values, inclusive.
117
+ *
118
+ * In Firestore pass one value per `$orderBy`, in the same order. In Realtime Database pass the value of the
119
+ * `$orderBy*` field and, optionally, a key that breaks ties between equal values.
120
+ *
121
+ * @example
122
+ * getTeas.send({ queryParams: [$orderBy("year"), $endAt(2011)] });
123
+ */
68
124
  export const $endAt = startEndConstraintsImpl(SharedQueryConstraints.END_AT as const);
125
+ /**
126
+ * Cursor that ends the ordered query before the given values, exclusive.
127
+ *
128
+ * In Firestore pass one value per `$orderBy`, in the same order. In Realtime Database pass the value of the
129
+ * `$orderBy*` field and, optionally, a key that breaks ties between equal values.
130
+ *
131
+ * @example
132
+ * getTeas.send({ queryParams: [$orderBy("year"), $endBefore(2011)] });
133
+ */
69
134
  export const $endBefore = startEndConstraintsImpl(SharedQueryConstraints.END_BEFORE as const);
70
135
 
136
+ /**
137
+ * Realtime Database ordering by a child value, the HyperFetch form of `orderByChild()`. A query can have one `$orderBy*`.
138
+ *
139
+ * @param path - Child path to order by, for example `"year"` or `"author/name"`
140
+ * @example
141
+ * getTeas.send({ queryParams: [$orderByChild("year"), $limitToFirst(10)] });
142
+ */
71
143
  export const $orderByChild = (path: string) => {
72
144
  return {
73
145
  toString: () => `${RealtimeQueryConstraints.ORDER_BY_CHILD}_${path}`,
@@ -76,6 +148,12 @@ export const $orderByChild = (path: string) => {
76
148
  };
77
149
  };
78
150
 
151
+ /**
152
+ * Realtime Database ordering by key, the HyperFetch form of `orderByKey()`. A query can have one `$orderBy*`.
153
+ *
154
+ * @example
155
+ * getTeas.send({ queryParams: [$orderByKey(), $limitToLast(10)] });
156
+ */
79
157
  export const $orderByKey = () => {
80
158
  return {
81
159
  toString: () => `${RealtimeQueryConstraints.ORDER_BY_KEY}`,
@@ -84,6 +162,13 @@ export const $orderByKey = () => {
84
162
  };
85
163
  };
86
164
 
165
+ /**
166
+ * Realtime Database ordering by the child values themselves, the HyperFetch form of `orderByValue()`. A query can have
167
+ * one `$orderBy*`.
168
+ *
169
+ * @example
170
+ * getScores.send({ queryParams: [$orderByValue(), $limitToLast(3)] });
171
+ */
87
172
  export const $orderByValue = () => {
88
173
  return {
89
174
  toString: () => `${RealtimeQueryConstraints.ORDER_BY_VALUE}`,
@@ -92,6 +177,13 @@ export const $orderByValue = () => {
92
177
  };
93
178
  };
94
179
 
180
+ /**
181
+ * Realtime Database limit from the start of the ordered list, the HyperFetch form of `limitToFirst()`.
182
+ *
183
+ * @param num - Maximum number of children to return
184
+ * @example
185
+ * getTeas.send({ queryParams: [$orderByChild("year"), $limitToFirst(5)] });
186
+ */
95
187
  export const $limitToFirst = (num: number) => {
96
188
  return {
97
189
  toString: () => `${RealtimeQueryConstraints.LIMIT_TO_FIRST}_${num}`,
@@ -100,6 +192,13 @@ export const $limitToFirst = (num: number) => {
100
192
  };
101
193
  };
102
194
 
195
+ /**
196
+ * Realtime Database limit from the end of the ordered list, the HyperFetch form of `limitToLast()`.
197
+ *
198
+ * @param num - Maximum number of children to return
199
+ * @example
200
+ * getMessages.send({ queryParams: [$orderByChild("sentAt"), $limitToLast(50)] });
201
+ */
103
202
  export const $limitToLast = (num: number) => {
104
203
  return {
105
204
  toString: () => `${RealtimeQueryConstraints.LIMIT_TO_LAST}_${num}`,
@@ -108,10 +207,19 @@ export const $limitToLast = (num: number) => {
108
207
  };
109
208
  };
110
209
 
111
- export const $equalTo = (value: any) => {
210
+ /**
211
+ * Realtime Database filter for children equal to a value, the HyperFetch form of `equalTo()`. Combine it with an
212
+ * `$orderBy*` that picks the compared value.
213
+ *
214
+ * @param value - Value the ordered field must equal
215
+ * @param key - Optional key that breaks ties between children with the same value
216
+ * @example
217
+ * getTeas.send({ queryParams: [$orderByChild("type"), $equalTo("Green")] });
218
+ */
219
+ export const $equalTo = (value: any, key?: string) => {
112
220
  return {
113
- toString: () => `${RealtimeQueryConstraints.LIMIT_TO_LAST}_${value}`,
221
+ toString: () => `${RealtimeQueryConstraints.EQUAL_TO}_${value}${key === undefined ? "" : `_${key}`}`,
114
222
  type: RealtimeQueryConstraints.EQUAL_TO as const,
115
- values: [value],
223
+ values: key === undefined ? [value] : [value, key],
116
224
  };
117
225
  };
@@ -1,2 +1,3 @@
1
1
  export * from "./firebase.constraints";
2
2
  export * from "./constraints.types";
3
+ export * from "./constraints.builder";
@@ -62,21 +62,21 @@ export const getFirestoreAdminMethods = ({
62
62
 
63
63
  return { result, status, extra: { ref: path, snapshot: querySnapshot } };
64
64
  },
65
- setDoc: async ({ data, options }: { data?: any; options?: any }) => {
65
+ setDoc: async ({ payload, options }: DataType) => {
66
66
  const path = getRef(database, cleanUrl) as DocumentReference;
67
67
  const merge = options?.merge === true;
68
- const res = await path.set(data, { merge });
68
+ const res = await path.set(payload, { merge });
69
69
  return { result: res, status: "success", extra: { ref: path } };
70
70
  },
71
- addDoc: async ({ data }: { data?: any }) => {
71
+ addDoc: async ({ payload }: DataType) => {
72
72
  const ref = getRef(database, cleanUrl) as CollectionReference;
73
- const docRef = await ref.add(data);
74
- return { result: { ...data, __key: docRef.id }, status: "success", extra: { ref: docRef } };
73
+ const docRef = await ref.add(payload);
74
+ return { result: { ...payload, __key: docRef.id }, status: "success", extra: { ref: docRef } };
75
75
  },
76
- updateDoc: async ({ data }: { data?: any }) => {
76
+ updateDoc: async ({ payload }: DataType) => {
77
77
  const path = getRef(database, cleanUrl) as DocumentReference;
78
- await path.update(data);
79
- return { result: data, status: "success", extra: { ref: path } };
78
+ await path.update(payload);
79
+ return { result: payload, status: "success", extra: { ref: path } };
80
80
  },
81
81
  deleteDoc: async () => {
82
82
  const path = getRef(database, cleanUrl) as DocumentReference;
@@ -4,6 +4,8 @@ import type { DocumentReference, Firestore, Query, QuerySnapshot } from "firebas
4
4
  import { CollectionReference, DocumentSnapshot } from "firebase-admin/firestore";
5
5
  import { getStatus } from "utils";
6
6
 
7
+ import { createFirestoreConstraints, getConstraints, resolveConstraints } from "../constraints";
8
+ import type { FirestorePermittedMethods } from "../constraints";
7
9
  import { getGroupedResultFirestore, getOrderedResultFirestore, getRef, applyFireStoreAdminConstraints } from "./utils";
8
10
 
9
11
  export const firestoreAdminSockets = (database: Firestore) => {
@@ -12,67 +14,74 @@ export const firestoreAdminSockets = (database: Firestore) => {
12
14
  name: "firebase-admin-firestore",
13
15
  defaultConnected: true,
14
16
  }) as unknown as FirestoreAdminSocketAdapterType
15
- ).setConnector(({ socket, onReconnect, onListen, onEvent, onError }) => {
16
- const connect = () => {
17
- throw new Error("Connect function is not implemented for Firestore Admin socket.");
18
- };
17
+ )
18
+ .setListenerQueryParamsResolver(resolveConstraints(createFirestoreConstraints))
19
+ .setConnector(({ socket, onReconnect, onListen, onEvent, onError }) => {
20
+ const connect = () => {
21
+ throw new Error("Connect function is not implemented for Firestore Admin socket.");
22
+ };
19
23
 
20
- const disconnect = () => {
21
- throw new Error("Cannot disconnect from Firestore database socket. Use 'app.delete()' instead.");
22
- };
24
+ const disconnect = () => {
25
+ throw new Error("Cannot disconnect from Firestore database socket. Use 'app.delete()' instead.");
26
+ };
23
27
 
24
- const reconnect = () => {
25
- onReconnect({ disconnect, connect });
26
- };
28
+ const reconnect = () => {
29
+ onReconnect({ disconnect, connect });
30
+ };
27
31
 
28
- const listen: FirestoreAdminSocketAdapterType["listen"] = (listener, callback) => {
29
- const fullUrl = socket.url + listener.topic;
30
- const { options } = listener;
31
- let pathRef: DocumentReference | Query = getRef(database, fullUrl);
32
- if (pathRef instanceof CollectionReference) {
33
- pathRef = applyFireStoreAdminConstraints(pathRef, options?.constraints || []);
34
- }
35
- let unsubscribe = () => {};
36
- let unmount = () => {};
37
- let clearListeners = () => {};
32
+ const listen: FirestoreAdminSocketAdapterType["listen"] = (listener, callback) => {
33
+ const fullUrl = socket.url + listener.topic;
34
+ const { options } = listener;
35
+ let pathRef: DocumentReference | Query = getRef(database, fullUrl);
36
+ if (pathRef instanceof CollectionReference) {
37
+ // `options.constraints` is the deprecated place for constraints, kept working in v10
38
+ pathRef = applyFireStoreAdminConstraints(
39
+ pathRef,
40
+ getConstraints<FirestorePermittedMethods>(listener.queryParams ?? options?.constraints),
41
+ );
42
+ }
43
+ let unsubscribe = () => {};
44
+ let unmount = () => {};
45
+ let clearListeners = () => {};
38
46
 
39
- unsubscribe = pathRef.onSnapshot(
40
- (snapshot) => {
41
- const getSnapshotData = (s: DocumentSnapshot) => (s.data() ? { ...s.data(), __key: s.id } : null);
42
- const response =
43
- snapshot instanceof DocumentSnapshot
44
- ? getSnapshotData(snapshot)
45
- : getOrderedResultFirestore(snapshot as QuerySnapshot);
46
- const status = getStatus(response);
47
- const groupedResult =
48
- options?.groupByChangeType === true ? getGroupedResultFirestore(snapshot as QuerySnapshot) : null;
49
- const extra = { ref: pathRef, snapshot, unsubscribe, groupedResult, status };
50
- callback({ data: response, extra });
51
- onEvent({ topic: listener.topic, data: response, extra });
52
- },
53
- (error) => {
54
- onError({ error });
55
- },
56
- );
57
- unmount = onListen({ listener, callback, onUnmount: unsubscribe });
58
- clearListeners = () => {
59
- unsubscribe();
60
- unmount();
61
- };
47
+ unsubscribe = pathRef.onSnapshot(
48
+ (snapshot) => {
49
+ const getSnapshotData = (s: DocumentSnapshot) => (s.data() ? { ...s.data(), __key: s.id } : null);
50
+ const response =
51
+ snapshot instanceof DocumentSnapshot
52
+ ? getSnapshotData(snapshot)
53
+ : getOrderedResultFirestore(snapshot as QuerySnapshot);
54
+ const status = getStatus(response);
55
+ const groupedResult =
56
+ options?.groupByChangeType === true && !(snapshot instanceof DocumentSnapshot)
57
+ ? getGroupedResultFirestore(snapshot as QuerySnapshot)
58
+ : null;
59
+ const extra = { ref: pathRef, snapshot, unsubscribe, groupedResult, status };
60
+ onEvent({ topic: listener.topic, data: response, extra });
61
+ },
62
+ (error) => {
63
+ onError({ error });
64
+ },
65
+ );
66
+ unmount = onListen({ listener, callback, onUnmount: unsubscribe });
67
+ clearListeners = () => {
68
+ unsubscribe();
69
+ unmount();
70
+ };
62
71
 
63
- return clearListeners;
64
- };
72
+ return clearListeners;
73
+ };
65
74
 
66
- const emit = async () => {
67
- throw new Error("Cannot emit from Firestore database socket.");
68
- };
75
+ const emit = async () => {
76
+ throw new Error("Cannot emit from Firestore database socket.");
77
+ };
69
78
 
70
- return {
71
- connect,
72
- reconnect,
73
- disconnect,
74
- emit,
75
- listen,
76
- };
77
- });
79
+ return {
80
+ connect,
81
+ reconnect,
82
+ disconnect,
83
+ emit,
84
+ listen,
85
+ };
86
+ });
78
87
  };
@@ -20,19 +20,19 @@ export const applyFireStoreAdminConstraint = (collectionRef: Query, { type, valu
20
20
  }
21
21
  case SharedQueryConstraints.START_AT: {
22
22
  const [docOrFields] = values;
23
- return collectionRef.startAt(docOrFields);
23
+ return collectionRef.startAt(...docOrFields);
24
24
  }
25
25
  case SharedQueryConstraints.START_AFTER: {
26
26
  const [docOrFields] = values;
27
- return collectionRef.startAfter(docOrFields);
27
+ return collectionRef.startAfter(...docOrFields);
28
28
  }
29
29
  case SharedQueryConstraints.END_AT: {
30
30
  const [docOrFields] = values;
31
- return collectionRef.endAt(docOrFields);
31
+ return collectionRef.endAt(...docOrFields);
32
32
  }
33
33
  case SharedQueryConstraints.END_BEFORE: {
34
34
  const [docOrFields] = values;
35
- return collectionRef.endBefore(docOrFields);
35
+ return collectionRef.endBefore(...docOrFields);
36
36
  }
37
37
  default:
38
38
  throw new Error(`Unknown method ${type}`);