@hyper-fetch/firebase-admin 10.0.0 → 10.1.1

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 +8 -7
  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
package/README.md CHANGED
@@ -1,116 +1,164 @@
1
- # 🔥 Hyper Fetch Firebase Admin
1
+ <p align="center">
2
+ <a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/firebase-admin.png" alt="Hyper Fetch Firebase Admin. Firebase on the server. Same typed requests. The Admin SDK behind HyperFetch requests for route handlers, workers and scripts." /></a>
3
+ </p>
2
4
 
3
5
  <p align="center">
4
- <b>Type-safe Firebase Admin SDK adapter for HyperFetch. Server-side Firestore and Realtime Database — fully typed.</b>
6
+ <a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/overview"><b>Quick Start</b></a> ·
7
+ <a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/overview">Documentation</a> ·
8
+ <a href="https://hyperfetch.bettertyped.com/docs/api/adapter-firebase-admin/Functions/FirebaseAdminAdapter">API Reference</a> ·
9
+ <a href="https://github.com/BetterTyped/hyper-fetch">GitHub</a> ·
10
+ <a href="https://discord.gg/7upC2kVmyM">Discord</a>
5
11
  </p>
6
12
 
7
13
  <p align="center">
8
- <a href="https://bettertyped.com/">
9
- <img src="https://custom-icon-badges.demolab.com/static/v1?label=&message=BetterTyped&color=333&logo=BT" />
10
- </a>
11
- <a href="https://github.com/BetterTyped/hyper-fetch">
12
- <img src="https://custom-icon-badges.demolab.com/github/stars/BetterTyped/hyper-fetch?logo=star&color=118ab2" />
13
- </a>
14
- <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
15
- <img src="https://custom-icon-badges.demolab.com/github/license/BetterTyped/hyper-fetch?logo=law&color=yellow" />
16
- </a>
17
- <a href="https://www.npmjs.com/package/@hyper-fetch/firebase-admin">
18
- <img src="https://custom-icon-badges.demolab.com/npm/v/@hyper-fetch/firebase-admin.svg?logo=npm&color=e76f51" />
19
- </a>
20
- <a href="https://www.npmjs.com/package/@hyper-fetch/firebase-admin">
21
- <img src="https://custom-icon-badges.demolab.com/npm/dm/@hyper-fetch/firebase-admin?logoColor=fff&logo=trending-up" />
22
- </a>
23
- <a href="https://github.com/BetterTyped/hyper-fetch">
24
- <img src="https://custom-icon-badges.demolab.com/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" />
25
- </a>
26
- <a href="https://bundlephobia.com/package/@hyper-fetch/firebase-admin">
27
- <img src="https://custom-icon-badges.demolab.com/bundlephobia/minzip/@hyper-fetch/firebase-admin?color=64BC4B&logo=package" />
28
- </a>
29
- <a href="https://github.com/BetterTyped/hyper-fetch">
30
- <img src="https://img.shields.io/badge/firebase-ffca28?logo=firebase&logoColor=black" alt="Firebase" />
31
- </a>
14
+ <a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?style=flat&logo=github&color=333" alt="GitHub stars" /></a>
15
+ <a href="https://www.npmjs.com/package/@hyper-fetch/firebase-admin"><img src="https://img.shields.io/npm/v/@hyper-fetch/firebase-admin?logo=npm&color=e76f51" alt="npm version" /></a>
16
+ <a href="https://www.npmjs.com/package/@hyper-fetch/firebase-admin"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/firebase-admin&color=fbc646" alt="Monthly downloads" /></a>
17
+ <a href="https://bundlejs.com/?q=@hyper-fetch/firebase-admin"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/firebase-admin&external=@hyper-fetch/core,@hyper-fetch/sockets,firebase,firebase-admin" alt="Bundle size" /></a>
18
+ <a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" /></a>
19
+ <a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/overview"><img src="https://img.shields.io/badge/Firebase-admin-FFCA28?logo=firebase&logoColor=black" alt="Firebase" /></a>
20
+ <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md"><img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=blue" alt="License" /></a>
32
21
  </p>
33
22
 
34
23
  ## 📖 About
35
24
 
36
- This adapter brings HyperFetch to server-side Firebase. Share request patterns between browser and Node.js, use the same
37
- typed API for Firestore and Realtime Database, and leverage HyperFetch's queuing and retry capabilities on top of the
38
- Firebase Admin SDK.
25
+ `@hyper-fetch/firebase-admin` runs Firestore and Realtime Database operations from server code as Hyper Fetch requests,
26
+ on top of the Firebase Admin SDK. Route handlers, workers and scripts get typed responses, retries and queues with the
27
+ same request API as `@hyper-fetch/firebase` in the browser.
39
28
 
40
29
  ## 🎯 Key Capabilities
41
30
 
42
- - 🔮 **Same code, server-side** — Identical HyperFetch patterns for server and client Firebase operations
43
- - 🔥 **Firestore & Realtime Database** — Both engines through one typed adapter
44
- - 🔁 **Server-side retry and queuing** — Automatic retries with backoff for flaky Firebase calls in backend services
45
- - ✨ **Full TypeScript types** — Parameters, payloads, and responses typed for every database operation
31
+ - 🔮 **The same requests on server and client** - Methods, constraints and responses match `@hyper-fetch/firebase`
32
+ - 🔁 **Retries and queues for backend work** - Retry, deduplication and queueing on top of Admin SDK calls
33
+ - 🧭 **Typed queries** - `c.where("status", "==", "open").limit(50)` is checked against your document type
34
+ - 📡 **Server-side listeners** - React to Firestore and Realtime Database changes in workers through sockets
35
+ - 🗂️ **Change groups** - `groupByChangeType` splits a snapshot into `added`, `modified` and `removed`
36
+ - 🛡️ **Errors in the response** - Firebase errors arrive in `response.error`, and `send()` never throws
46
37
 
47
38
  ## 🚀 Quick Start
48
39
 
49
40
  ```bash
50
- npm install @hyper-fetch/core @hyper-fetch/firebase-admin firebase-admin
41
+ npm install @hyper-fetch/core @hyper-fetch/sockets @hyper-fetch/firebase-admin firebase-admin
51
42
  ```
52
43
 
53
44
  ```ts
54
- import { createClient } from "@hyper-fetch/core";
45
+ import { Client } from "@hyper-fetch/core";
55
46
  import { FirebaseAdminAdapter } from "@hyper-fetch/firebase-admin";
47
+ import { initializeApp } from "firebase-admin/app";
56
48
  import { getFirestore } from "firebase-admin/firestore";
57
49
 
58
- const db = getFirestore();
59
- const client = createClient({ url: "" }).setAdapter(FirebaseAdminAdapter(db));
50
+ initializeApp();
51
+
52
+ const client = new Client({ url: "" }).setAdapter(FirebaseAdminAdapter(getFirestore()));
53
+
54
+ const getJobs = client.createRequest<{ response: Job[] }>()({ endpoint: "jobs", method: "getDocs" });
55
+
56
+ const { data, error } = await getJobs.send();
60
57
  ```
61
58
 
62
59
  ## 📚 Documentation
63
60
 
64
- - [Firebase Admin Adapter Docs](https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin)
65
- - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
66
- - [API Reference](https://hyperfetch.bettertyped.com/api/)
61
+ - **[Firebase Admin Adapter](https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/overview)** - Setup on the server
62
+ - **[Firestore](https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/firestore)** - Methods, constraints and typed queries
63
+ - **[Realtime Database](https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/realtime)** - Methods, ordering and filters
64
+ - **[Realtime listening](https://hyperfetch.bettertyped.com/docs/integrations/adapter-firebase-admin/realtime-queries)** - Listeners in workers
65
+ - **[API Reference](https://hyperfetch.bettertyped.com/docs/api/adapter-firebase-admin/Functions/FirebaseAdminAdapter)** - Every adapter, method and type
67
66
 
68
67
  ## 💡 Examples
69
68
 
70
69
  ### Server-side CRUD
71
70
 
72
71
  ```ts
73
- interface Message {
74
- text: string;
75
- author: string;
76
- createdAt: number;
77
- }
72
+ type Message = { text: string; author: string; createdAt: number };
78
73
 
79
- const addMessage = client.createRequest<{ payload: Message; response: Message & { __key: string } }>()({
80
- endpoint: "/messages",
74
+ const addMessage = client.createRequest<{ response: Message & { __key: string }; payload: Message }>()({
75
+ endpoint: "messages",
81
76
  method: "addDoc",
82
77
  });
83
78
 
84
- const getMessages = client.createRequest<{ response: Message[] }>()({
85
- endpoint: "/messages",
86
- method: "getDocs",
79
+ const updateMessage = client.createRequest<{ response: Partial<Message>; payload: Partial<Message> }>()({
80
+ endpoint: "messages/:messageId",
81
+ method: "updateDoc",
82
+ });
83
+
84
+ const deleteMessage = client.createRequest<{ response: null }>()({
85
+ endpoint: "messages/:messageId",
86
+ method: "deleteDoc",
87
87
  });
88
88
 
89
- await addMessage.send({
90
- payload: { text: "Hello from server!", author: "system", createdAt: Date.now() },
89
+ const { data: created } = await addMessage.send({
90
+ payload: { text: "Hello from the server", author: "system", createdAt: Date.now() },
91
91
  });
92
92
 
93
- const { data: messages } = await getMessages.send();
94
- messages?.forEach((msg) => console.log(`${msg.author}: ${msg.text}`));
93
+ if (created) {
94
+ await updateMessage.setParams({ messageId: created.__key }).send({ payload: { text: "Updated" } });
95
+ await deleteMessage.setParams({ messageId: created.__key }).send();
96
+ }
95
97
  ```
96
98
 
97
- ### Update and delete
99
+ ### Query with constraints
98
100
 
99
101
  ```ts
100
- const updateMessage = client.createRequest<{ payload: Partial<Message>; response: Partial<Message> }>()({
101
- endpoint: "/messages/:messageId",
102
- method: "updateDoc",
102
+ import type { FirestoreQueryParams } from "@hyper-fetch/firebase-admin";
103
+
104
+ const getMessages = client.createRequest<{ response: Message[]; queryParams?: FirestoreQueryParams<Message> }>()({
105
+ endpoint: "messages",
106
+ method: "getDocs",
103
107
  });
104
108
 
105
- const deleteMessage = client.createRequest<{ response: null }>()({
106
- endpoint: "/messages/:messageId",
107
- method: "deleteDoc",
109
+ const { data: recent } = await getMessages.send({
110
+ queryParams: (c) => c.where("author", "==", "system").orderBy("createdAt", "desc").limit(50),
108
111
  });
112
+ ```
109
113
 
110
- await updateMessage.setParams({ messageId: "abc" }).send({ payload: { text: "Updated!" } });
111
- await deleteMessage.setParams({ messageId: "abc" }).send();
114
+ ### Process new jobs in a worker
115
+
116
+ ```ts
117
+ import { Socket } from "@hyper-fetch/sockets";
118
+ import { FirebaseSocketsAdminAdapter } from "@hyper-fetch/firebase-admin";
119
+
120
+ const socket = new Socket({ url: "", adapter: FirebaseSocketsAdminAdapter(getFirestore()) });
121
+
122
+ const onQueued = socket
123
+ .createListener<Job[]>()({ topic: "jobs", options: { groupByChangeType: true } })
124
+ .setQueryParams((c) => c.where("state", "==", "queued"));
125
+
126
+ const stop = onQueued.listen(({ extra }) => {
127
+ extra.groupedResult?.added.forEach((job) => enqueue(job));
128
+ });
112
129
  ```
113
130
 
131
+ ## 🧩 Hyper Fetch Ecosystem
132
+
133
+ One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
134
+
135
+ <table align="center">
136
+ <tr>
137
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/core"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hyper-fetch.svg" width="36" height="36" alt="" /><br /><sub><b>Core</b></sub></a></td>
138
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/react"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-react.svg" width="36" height="36" alt="" /><br /><sub><b>React</b></sub></a></td>
139
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/sockets"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-sockets.svg" width="36" height="36" alt="" /><br /><sub><b>Sockets</b></sub></a></td>
140
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/cli"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-openapi.svg" width="36" height="36" alt="" /><br /><sub><b>OpenAPI CLI</b></sub></a></td>
141
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-graphql"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-graphql.svg" width="36" height="36" alt="" /><br /><sub><b>GraphQL</b></sub></a></td>
142
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-trpc"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-trpc.svg" width="36" height="36" alt="" /><br /><sub><b>tRPC</b></sub></a></td>
143
+ </tr>
144
+ <tr>
145
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-orpc"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc-dark.svg" /><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc.svg" width="36" height="36" alt="" /></picture><br /><sub><b>oRPC</b></sub></a></td>
146
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hono"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hono.svg" width="36" height="36" alt="" /><br /><sub><b>Hono</b></sub></a></td>
147
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/elysia"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-elysia.svg" width="36" height="36" alt="" /><br /><sub><b>Elysia</b></sub></a></td>
148
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-firebase"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-firebase.svg" width="36" height="36" alt="" /><br /><sub><b>Firebase</b></sub></a></td>
149
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-axios"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-axios.svg" width="36" height="36" alt="" /><br /><sub><b>Axios</b></sub></a></td>
150
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hyper-flow"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/hyper-flow.svg" width="36" height="36" alt="" /><br /><sub><b>HyperFlow</b></sub></a></td>
151
+ </tr>
152
+ </table>
153
+
154
+ ## 💖 Sponsors
155
+
156
+ <p align="center">
157
+ <a href="https://github.com/sponsors/prc5">
158
+ <img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
159
+ </a>
160
+ </p>
161
+
114
162
  ## License
115
163
 
116
164
  [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -0,0 +1,44 @@
1
+ import {
2
+ $endAt,
3
+ $endBefore,
4
+ $equalTo,
5
+ $limit,
6
+ $limitToFirst,
7
+ $limitToLast,
8
+ $orderBy,
9
+ $orderByChild,
10
+ $orderByKey,
11
+ $orderByValue,
12
+ $startAfter,
13
+ $startAt,
14
+ $where,
15
+ } from "constraints";
16
+
17
+ describe("Constraints [ Base ]", () => {
18
+ it("should prefix every constraint description with its own type", () => {
19
+ const constraints = [
20
+ $where("year", "==", 2023),
21
+ $orderBy("year", "desc"),
22
+ $limit(2),
23
+ $startAt(2),
24
+ $startAfter(2),
25
+ $endAt(2),
26
+ $endBefore(2),
27
+ $orderByChild("year"),
28
+ $orderByKey(),
29
+ $orderByValue(),
30
+ $limitToFirst(2),
31
+ $limitToLast(2),
32
+ $equalTo(2),
33
+ ];
34
+
35
+ constraints.forEach((constraint) => {
36
+ expect(String(constraint).split("_")[0]).toBe(constraint.type);
37
+ });
38
+ });
39
+
40
+ it("should describe equalTo and limitToLast with the same value differently", () => {
41
+ expect(String($equalTo(2))).toBe("equalTo_2");
42
+ expect(String($equalTo(2))).not.toBe(String($limitToLast(2)));
43
+ });
44
+ });
@@ -0,0 +1,14 @@
1
+ import type {
2
+ FirestoreAdminOnSnapshotExtra,
3
+ FirestoreStatuses,
4
+ RealtimeAdminOnValueMethodExtra,
5
+ RealtimeDBStatuses,
6
+ } from "adapter";
7
+ import { expectTypeOf } from "vitest";
8
+
9
+ describe("Listener extra [ Types ]", () => {
10
+ it("should type the status every snapshot carries", () => {
11
+ expectTypeOf<FirestoreAdminOnSnapshotExtra["status"]>().toEqualTypeOf<FirestoreStatuses>();
12
+ expectTypeOf<RealtimeAdminOnValueMethodExtra["status"]>().toEqualTypeOf<RealtimeDBStatuses>();
13
+ });
14
+ });
@@ -0,0 +1,83 @@
1
+ import type { FirestoreQueryParams, RealtimeDBQueryParams } from "adapter";
2
+ import { $limit, $orderByChild, $startAfter, $where, createFirestoreConstraints, createRealtimeConstraints } from "constraints";
3
+ import { expectTypeOf } from "vitest";
4
+
5
+ type Tea = {
6
+ __key: string;
7
+ name: string;
8
+ type: "Green" | "Black";
9
+ year: number;
10
+ tags: string[];
11
+ origin: { country: string };
12
+ };
13
+
14
+ type Message = { text: string; sentAt: number; author: { name: string } };
15
+
16
+ describe("Query params [ Types ]", () => {
17
+ it("should accept a callback, the constraints array and the deprecated object", () => {
18
+ const callback: FirestoreQueryParams<Tea> = (c) => c.where("type", "==", "Green").orderBy("year", "desc").limit(20);
19
+ const array: FirestoreQueryParams<Tea> = [$where("type", "==", "Green"), $limit(1)];
20
+ const deprecated: FirestoreQueryParams<Tea> = { constraints: [$limit(1)] };
21
+ const realtime: RealtimeDBQueryParams<Message> = (c) => c.orderByChild("sentAt").limitToLast(50);
22
+
23
+ expectTypeOf([callback, array, deprecated, realtime]).toBeArray();
24
+ // @ts-expect-error - $where is a Firestore constraint
25
+ expectTypeOf([$where("type", "==", "Green")]).toMatchTypeOf<RealtimeDBQueryParams>();
26
+ expectTypeOf([$orderByChild("year"), $startAfter(2022, "0")]).toMatchTypeOf<RealtimeDBQueryParams>();
27
+ });
28
+
29
+ it("should check Firestore fields and values against the document", () => {
30
+ const c = createFirestoreConstraints<Tea>();
31
+
32
+ c.where("origin.country", "==", "China");
33
+ c.where("type", "in", ["Green", "Black"]);
34
+ c.where("tags", "array-contains", "organic");
35
+ c.where("tags", "array-contains-any", ["organic", "loose"]);
36
+ // @ts-expect-error - unknown field
37
+ c.where("yaer", "==", 2020);
38
+ // @ts-expect-error - year is a number
39
+ c.where("year", "==", "2020");
40
+ // @ts-expect-error - "in" takes an array
41
+ c.where("type", "in", "Green");
42
+ // @ts-expect-error - "array-contains" takes one element
43
+ c.where("tags", "array-contains", ["organic"]);
44
+ // @ts-expect-error - __key is the document id, not a field
45
+ c.where("__key", "==", "1");
46
+ // @ts-expect-error - unknown field
47
+ c.orderBy("price");
48
+ });
49
+
50
+ it("should take one Firestore cursor value per orderBy, in order", () => {
51
+ const ordered = createFirestoreConstraints<Tea>().orderBy("year").orderBy("name");
52
+
53
+ ordered.startAfter(2023, "Sencha");
54
+ ordered.startAt(2023);
55
+ ordered.endBefore(2023, "Sencha");
56
+ // @ts-expect-error - name is a string
57
+ ordered.startAfter(2023, 1);
58
+ // @ts-expect-error - two orderBy, three values
59
+ ordered.startAfter(2023, "Sencha", "Gyokuro");
60
+ createFirestoreConstraints<Tea>().startAfter("document-id");
61
+ });
62
+
63
+ it("should allow one Realtime Database orderBy and type cursors by the ordered value", () => {
64
+ const c = createRealtimeConstraints<Message>();
65
+
66
+ c.orderByChild("author/name").equalTo("ann");
67
+ c.orderByChild("sentAt").startAfter(10, "key").limitToLast(5);
68
+ c.limitToFirst(5).orderByKey().startAt("a");
69
+ // @ts-expect-error - one orderBy per query
70
+ c.orderByChild("sentAt").orderByKey();
71
+ // @ts-expect-error - cursors need an orderBy first
72
+ c.startAt(1);
73
+ // @ts-expect-error - sentAt is a number
74
+ c.orderByChild("sentAt").equalTo("x");
75
+ // @ts-expect-error - Realtime Database child paths use "/"
76
+ c.orderByChild("author.name");
77
+ });
78
+
79
+ it("should keep untyped constraints open", () => {
80
+ createFirestoreConstraints().where("anything", "==", 1).orderBy("other").startAfter(1);
81
+ createRealtimeConstraints().orderByChild("any/path").equalTo(true);
82
+ });
83
+ });
@@ -12,6 +12,7 @@ describe("Firestore Admin [ Constraints ]", () => {
12
12
  const client = new Client({ url: "teas/" }).setAdapter(FirebaseAdminAdapter(firestoreDbAdmin));
13
13
 
14
14
  beforeEach(async () => {
15
+ await firestoreDbAdmin.recursiveDelete(firestoreDbAdmin.collection("teas"));
15
16
  await seedFirestoreDatabaseAdmin(firestoreDbAdmin);
16
17
  });
17
18
 
@@ -14,5 +14,8 @@ describe("Firestore Admin [ Sockets ]", () => {
14
14
  await seedFirestoreDatabaseAdmin(firestoreDbAdmin);
15
15
  });
16
16
 
17
- socketsMethodsSharedTestCases(FirebaseSocketsAdminAdapter(firestoreDbAdmin), FirebaseAdminAdapter(firestoreDbAdmin));
17
+ socketsMethodsSharedTestCases(
18
+ () => FirebaseSocketsAdminAdapter(firestoreDbAdmin),
19
+ FirebaseAdminAdapter(firestoreDbAdmin),
20
+ );
18
21
  });
@@ -1,6 +1,6 @@
1
1
  import type { Client } from "@hyper-fetch/core";
2
2
  import type { FirestoreAdapterType, FirestoreQueryParams } from "adapter";
3
- import { $limit, $orderBy, $where } from "constraints";
3
+ import { $endAt, $endBefore, $limit, $orderBy, $startAfter, $startAt, $where } from "constraints";
4
4
 
5
5
  import type { Tea } from "../../../utils";
6
6
 
@@ -11,7 +11,7 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
11
11
  endpoint: "",
12
12
  method: "getDocs",
13
13
  });
14
- const { data } = await req.send({ queryParams: { constraints: [$where("type", "==", "Green")] } });
14
+ const { data } = await req.send({ queryParams: [$where("type", "==", "Green")] });
15
15
  expect(data).toHaveLength(3);
16
16
  expect(data?.map((tea) => tea.type)).toStrictEqual(["Green", "Green", "Green"]);
17
17
  });
@@ -21,7 +21,7 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
21
21
  method: "getDocs",
22
22
  });
23
23
  const { data } = await req.send({
24
- queryParams: { constraints: [$where("type", "==", "Green"), $where("amount", ">=", 50)] },
24
+ queryParams: [$where("type", "==", "Green"), $where("amount", ">=", 50)],
25
25
  });
26
26
  expect(data).toHaveLength(2);
27
27
  expect(data?.map((tea) => tea.type)).toStrictEqual(["Green", "Green"]);
@@ -33,7 +33,7 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
33
33
  endpoint: "",
34
34
  method: "getDocs",
35
35
  });
36
- const { data } = await req.send({ queryParams: { constraints: [$orderBy("year")] } });
36
+ const { data } = await req.send({ queryParams: [$orderBy("year")] });
37
37
  expect(data?.map((tea) => tea.year)).toStrictEqual([1980, 2011, 2017, 2021, 2021, 2021, 2022, 2022, 2023, 2023]);
38
38
  });
39
39
  });
@@ -43,7 +43,7 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
43
43
  endpoint: "",
44
44
  method: "getDocs",
45
45
  });
46
- const { data } = await req.send({ queryParams: { constraints: [$limit(5)] } });
46
+ const { data } = await req.send({ queryParams: [$limit(5)] });
47
47
 
48
48
  expect(data).toHaveLength(5);
49
49
  });
@@ -55,7 +55,7 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
55
55
  method: "getDocs",
56
56
  });
57
57
  const { data } = await req.send({
58
- queryParams: { constraints: [$where("type", "==", "Green"), $orderBy("year"), $limit(1)] },
58
+ queryParams: [$where("type", "==", "Green"), $orderBy("year"), $limit(1)],
59
59
  });
60
60
  expect(data).toHaveLength(1);
61
61
  // eslint-disable-next-line @typescript-eslint/naming-convention
@@ -69,4 +69,85 @@ export const constraintsSharedTestCases = (client: Client<Error, FirestoreAdapte
69
69
  });
70
70
  });
71
71
  });
72
+ describe("cursors", () => {
73
+ it("should start and end the ordered query at field values", async () => {
74
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams }>()({
75
+ endpoint: "",
76
+ method: "getDocs",
77
+ });
78
+ const { data: fromStart } = await req.send({
79
+ queryParams: [$orderBy("year"), $startAt(2022)],
80
+ });
81
+ const { data: afterStart } = await req.send({
82
+ queryParams: [$orderBy("year"), $startAfter(2022)],
83
+ });
84
+ const { data: toEnd } = await req.send({
85
+ queryParams: [$orderBy("year"), $endAt(2011)],
86
+ });
87
+ const { data: beforeEnd } = await req.send({
88
+ queryParams: [$orderBy("year"), $endBefore(2011)],
89
+ });
90
+
91
+ expect(fromStart?.map((tea) => tea.year)).toStrictEqual([2022, 2022, 2023, 2023]);
92
+ expect(afterStart?.map((tea) => tea.year)).toStrictEqual([2023, 2023]);
93
+ expect(toEnd?.map((tea) => tea.year)).toStrictEqual([1980, 2011]);
94
+ expect(beforeEnd?.map((tea) => tea.year)).toStrictEqual([1980]);
95
+ });
96
+ it("should pass every cursor value when ordering by multiple fields", async () => {
97
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams }>()({
98
+ endpoint: "",
99
+ method: "getDocs",
100
+ });
101
+ const { data } = await req.send({
102
+ queryParams: [$orderBy("year"), $orderBy("name"), $startAfter(2023, "Hong Yu")],
103
+ });
104
+
105
+ expect(data?.map((tea) => tea.name)).toStrictEqual(["Taiping Hou Kui"]);
106
+ });
107
+ });
108
+ describe("constraints callback", () => {
109
+ it("should filter, order and limit with a callback", async () => {
110
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams<Tea> }>()({
111
+ endpoint: "",
112
+ method: "getDocs",
113
+ });
114
+ const { data } = await req.send({
115
+ queryParams: (c) => c.where("type", "==", "Green").orderBy("year", "desc").limit(2),
116
+ });
117
+
118
+ expect(data?.map((tea) => tea.name)).toStrictEqual(["Taiping Hou Kui", "Bi Luo Chun"]);
119
+ });
120
+ it("should page with cursors from a callback", async () => {
121
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams<Tea> }>()({
122
+ endpoint: "",
123
+ method: "getDocs",
124
+ });
125
+ const { data } = await req.send({
126
+ queryParams: (c) => c.orderBy("year").orderBy("name").startAfter(2023, "Hong Yu"),
127
+ });
128
+
129
+ expect(data?.map((tea) => tea.name)).toStrictEqual(["Taiping Hou Kui"]);
130
+ });
131
+ it("should store the resolved constraints, sharing the cache key with the array form", () => {
132
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams<Tea> }>()({
133
+ endpoint: "",
134
+ method: "getDocs",
135
+ });
136
+ const fromCallback = req.setQueryParams((c) => c.where("type", "==", "Green").limit(2));
137
+ const fromArray = req.setQueryParams([$where("type", "==", "Green"), $limit(2)]);
138
+
139
+ expect(Array.isArray(fromCallback.queryParams)).toBe(true);
140
+ expect(fromCallback.cacheKey).toBe(fromArray.cacheKey);
141
+ expect(fromCallback.cacheKey).not.toBe(req.setQueryParams((c) => c.limit(3)).cacheKey);
142
+ });
143
+ it("should keep the deprecated constraints object working", async () => {
144
+ const req = client.createRequest<{ response: Tea[]; queryParams: FirestoreQueryParams<Tea> }>()({
145
+ endpoint: "",
146
+ method: "getDocs",
147
+ });
148
+ const { data } = await req.send({ queryParams: { constraints: [$where("type", "==", "Green")] } });
149
+
150
+ expect(data).toHaveLength(3);
151
+ });
152
+ });
72
153
  };
@@ -45,6 +45,21 @@ export const getDocTestSuite = (adapterFunction: () => ReturnType<typeof Firebas
45
45
  expect(success).toBe(true);
46
46
  expect(error).toBe(null);
47
47
  });
48
+ it("should resolve with an error for a method Firestore does not have", async () => {
49
+ const client = new Client({ url: "teas/" }).setAdapter(adapterFunction());
50
+ const request = client
51
+ .createRequest<{ response: Tea }>()({
52
+ endpoint: ":teaId",
53
+ method: "push",
54
+ })
55
+ .setParams({ teaId: 1 });
56
+
57
+ const { data, error, status, success } = await request.send();
58
+ expect(data).toBeNull();
59
+ expect(error).toBeInstanceOf(Error);
60
+ expect(status).toBe("error");
61
+ expect(success).toBe(false);
62
+ });
48
63
  it("should emit lifecycle events", async () => {
49
64
  const client = new Client({ url: "teas/" }).setAdapter(adapterFunction());
50
65
  const request = client
@@ -27,7 +27,7 @@ export const getDocsTestSuite = (adapterFunction: () => ReturnType<typeof Fireba
27
27
  method: "getDocs",
28
28
  });
29
29
  const { data, status, success, error } = await req.send();
30
- expect(data).toStrictEqual(null);
30
+ expect(data).toStrictEqual([]);
31
31
  expect(status).toBe("emptyResource");
32
32
  expect(success).toBe(true);
33
33
  expect(error).toBe(null);