@hyper-fetch/graphql 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.
- package/README.md +152 -84
- package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
- package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
- package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
- package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
- package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
- package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
- package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
- package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
- package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
- package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
- package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
- package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
- package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
- package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
- package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
- package/__tests__/features/socket/socket.connection.spec.ts +892 -0
- package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
- package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
- package/__tests__/features/socket/socket.types.spec.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +238 -0
- package/dist/adapter/adapter.constants.d.ts +5 -0
- package/dist/adapter/adapter.constants.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +55 -2
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +51 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +958 -128
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +5 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.constants.d.ts +44 -0
- package/dist/socket/socket.constants.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +74 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +102 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +80 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/socket/socket.websocket.d.ts +30 -0
- package/dist/socket/socket.websocket.d.ts.map +1 -0
- package/package.json +14 -9
- package/src/adapter/adapter.constants.ts +6 -0
- package/src/adapter/adapter.types.ts +69 -3
- package/src/adapter/adapter.utils.ts +196 -25
- package/src/adapter/http-adapter.fetch.ts +93 -43
- package/src/index.ts +1 -0
- package/src/socket/index.ts +4 -0
- package/src/socket/socket.constants.ts +59 -0
- package/src/socket/socket.subscriptions.ts +160 -0
- package/src/socket/socket.types.ts +118 -0
- package/src/socket/socket.utils.ts +150 -0
- package/src/socket/socket.websocket.ts +555 -0
- package/vite.config.ts +4 -0
package/README.md
CHANGED
|
@@ -1,147 +1,215 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/graphql.png" alt="Hyper Fetch GraphQL. GraphQL operations. Cached by variables. Queries and mutations as typed requests with their own cache entry per set of variables." /></a>
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
5
|
<p align="center">
|
|
4
|
-
<b>
|
|
6
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/overview"><b>Quick Start</b></a> ·
|
|
7
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/overview">Documentation</a> ·
|
|
8
|
+
<a href="https://hyperfetch.bettertyped.com/docs/api/adapter-graphql/Functions/GraphqlAdapter">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://
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
<a href="https://
|
|
12
|
-
|
|
13
|
-
|
|
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/graphql">
|
|
18
|
-
<img src="https://custom-icon-badges.demolab.com/npm/v/@hyper-fetch/graphql.svg?logo=npm&color=e76f51" />
|
|
19
|
-
</a>
|
|
20
|
-
<a href="https://www.npmjs.com/package/@hyper-fetch/graphql">
|
|
21
|
-
<img src="https://custom-icon-badges.demolab.com/npm/dm/@hyper-fetch/graphql?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/graphql">
|
|
27
|
-
<img src="https://custom-icon-badges.demolab.com/bundlephobia/minzip/@hyper-fetch/graphql?color=64BC4B&logo=package" />
|
|
28
|
-
</a>
|
|
29
|
-
<a href="https://github.com/BetterTyped/hyper-fetch">
|
|
30
|
-
<img src="https://img.shields.io/badge/graphql-e10098?logo=graphql&logoColor=white" alt="GraphQL" />
|
|
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/graphql"><img src="https://img.shields.io/npm/v/@hyper-fetch/graphql?logo=npm&color=e76f51" alt="npm version" /></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/graphql"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/graphql&color=fbc646" alt="Monthly downloads" /></a>
|
|
17
|
+
<a href="https://bundlejs.com/?q=@hyper-fetch/graphql"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/graphql&external=@hyper-fetch/core,graphql" 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-graphql/overview"><img src="https://img.shields.io/badge/GraphQL-15%20%7C%2016-E10098?logo=graphql&logoColor=white" alt="GraphQL" /></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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
25
|
+
`@hyper-fetch/graphql` sends GraphQL queries and mutations over HTTP as regular Hyper Fetch requests. The document is
|
|
26
|
+
the endpoint, the variables are the payload, and every set of variables gets its own cache entry. You keep the core
|
|
27
|
+
request API, cache, retries, offline replay and React hooks, with no GraphQL-specific client to learn. Subscriptions run
|
|
28
|
+
over WebSocket with `GraphqlWsAdapter`, which speaks `graphql-transport-ws`, the protocol of `graphql-ws`.
|
|
39
29
|
|
|
40
30
|
## 🎯 Key Capabilities
|
|
41
31
|
|
|
42
|
-
- 🎡 **
|
|
43
|
-
- 🔮 **
|
|
44
|
-
-
|
|
45
|
-
-
|
|
46
|
-
-
|
|
32
|
+
- 🎡 **Operations are requests** - Write a `gql` document as the `endpoint` and call `send()`, `useFetch` or `useSubmit`
|
|
33
|
+
- 🔮 **Typed variables and data** - A typed document from GraphQL Code Generator or gql.tada types both, no generics
|
|
34
|
+
- 💾 **Cache per variables** - `{ id: "1" }` and `{ id: "2" }` are cached separately and served instantly next time
|
|
35
|
+
- 🌐 **GET when you want it** - `GraphqlMethod.GET` makes queries cacheable by browsers and CDNs
|
|
36
|
+
- 🛣️ **A URL per operation** - The `document` option keeps a path per operation for gateways, logs and APM
|
|
37
|
+
- 🛡️ **Errors you can handle** - The GraphQL `errors` array lands in `response.error`, and `send()` never throws
|
|
38
|
+
- 📊 **Extensions included** - Cost and tracing data from `extensions` arrive in `response.extra`
|
|
39
|
+
- 🔴 **Subscriptions** - `graphql-transport-ws` over WebSocket, with reconnecting, shared subscriptions and lazy connections
|
|
40
|
+
- 📡 **Any spec-compliant server** - Apollo, Yoga, Hasura or your own, over plain HTTP
|
|
47
41
|
|
|
48
42
|
## 🚀 Quick Start
|
|
49
43
|
|
|
50
44
|
```bash
|
|
51
|
-
npm install @hyper-fetch/core @hyper-fetch/graphql graphql-tag
|
|
45
|
+
npm install @hyper-fetch/core @hyper-fetch/sockets @hyper-fetch/graphql graphql graphql-tag
|
|
52
46
|
```
|
|
53
47
|
|
|
54
48
|
```ts
|
|
55
49
|
import { createClient } from "@hyper-fetch/core";
|
|
56
50
|
import { GraphqlAdapter } from "@hyper-fetch/graphql";
|
|
51
|
+
import gql from "graphql-tag";
|
|
57
52
|
|
|
58
53
|
const client = createClient({ url: "https://api.example.com/graphql" }).setAdapter(GraphqlAdapter());
|
|
54
|
+
|
|
55
|
+
const getUser = client.createRequest<{ response: { user: User | null }; payload: { id: string } }>()({
|
|
56
|
+
endpoint: gql`
|
|
57
|
+
query GetUser($id: ID!) {
|
|
58
|
+
user(id: $id) {
|
|
59
|
+
id
|
|
60
|
+
name
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
`,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// The payload is sent as the GraphQL variables
|
|
67
|
+
const { data, error } = await getUser.send({ payload: { id: "1" } });
|
|
59
68
|
```
|
|
60
69
|
|
|
61
70
|
## 📚 Documentation
|
|
62
71
|
|
|
63
|
-
- [
|
|
64
|
-
- [
|
|
65
|
-
- [
|
|
72
|
+
- **[Overview](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/overview)** - Setup, methods, errors and caching
|
|
73
|
+
- **[Queries](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/queries)** - Variables, GET queries and cache keys
|
|
74
|
+
- **[Mutations](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/mutations)** - Writes, forms and optimistic updates
|
|
75
|
+
- **[Subscriptions](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/subscriptions)** - `GraphqlWsAdapter`, connection params and reconnecting
|
|
76
|
+
- **[graphql-tag](https://hyperfetch.bettertyped.com/docs/integrations/adapter-graphql/graphql-tag)** - Documents, fragments and typing
|
|
77
|
+
- **[API Reference](https://hyperfetch.bettertyped.com/docs/api/adapter-graphql/Functions/GraphqlAdapter)** - `GraphqlAdapter`, `GraphqlMethod` and types
|
|
66
78
|
|
|
67
79
|
## 💡 Examples
|
|
68
80
|
|
|
69
|
-
###
|
|
70
|
-
|
|
71
|
-
The query goes in `endpoint` as a `gql` document.
|
|
81
|
+
### Mutation
|
|
72
82
|
|
|
73
83
|
```ts
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const getUsers = client.createRequest<{ response: UsersResponse; payload: { limit: number } }>()({
|
|
84
|
+
const createUser = client.createRequest<{
|
|
85
|
+
response: { createUser: User };
|
|
86
|
+
payload: { name: string; email: string };
|
|
87
|
+
}>()({
|
|
81
88
|
endpoint: gql`
|
|
82
|
-
|
|
83
|
-
|
|
89
|
+
mutation CreateUser($name: String!, $email: String!) {
|
|
90
|
+
createUser(name: $name, email: $email) {
|
|
84
91
|
id
|
|
85
92
|
name
|
|
86
|
-
email
|
|
87
93
|
}
|
|
88
94
|
}
|
|
89
95
|
`,
|
|
90
96
|
});
|
|
91
97
|
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
const { data, error } = await createUser.send({ payload: { name: "Jane", email: "jane@example.com" } });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### React hooks
|
|
94
102
|
|
|
95
|
-
|
|
103
|
+
```tsx
|
|
104
|
+
import { useFetch, useSubmit } from "@hyper-fetch/react";
|
|
105
|
+
|
|
106
|
+
const UserProfile = ({ id }: { id: string }) => {
|
|
107
|
+
// A new id is a new cache key: known users render instantly
|
|
108
|
+
const { data, loading } = useFetch(getUser.setPayload({ id }));
|
|
109
|
+
const { submit, submitting } = useSubmit(createUser);
|
|
110
|
+
|
|
111
|
+
if (loading) return <Spinner />;
|
|
112
|
+
return <Profile user={data?.user} onInvite={(payload) => submit({ payload })} saving={submitting} />;
|
|
113
|
+
};
|
|
96
114
|
```
|
|
97
115
|
|
|
98
|
-
###
|
|
116
|
+
### Handle GraphQL errors
|
|
99
117
|
|
|
100
118
|
```ts
|
|
101
|
-
|
|
102
|
-
createUser: { id: string; name: string };
|
|
103
|
-
}
|
|
119
|
+
import type { GraphqlErrorType } from "@hyper-fetch/graphql";
|
|
104
120
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
121
|
+
// Declare the error shape once. GraphQL errors, network failures, aborts and timeouts all arrive as a list
|
|
122
|
+
export const client = createClient<{ error: GraphqlErrorType }>({
|
|
123
|
+
url: "https://api.example.com/graphql",
|
|
124
|
+
}).setAdapter(GraphqlAdapter());
|
|
125
|
+
|
|
126
|
+
const { error, extra } = await getUser.send({ payload: { id: "1" } });
|
|
127
|
+
|
|
128
|
+
console.log(error?.map((item) => item.message), extra.extensions);
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Cacheable GET queries
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { GraphqlMethod } from "@hyper-fetch/graphql";
|
|
135
|
+
|
|
136
|
+
const listUsers = client.createRequest<{ response: { users: User[] } }>()({
|
|
109
137
|
endpoint: gql`
|
|
110
|
-
|
|
111
|
-
|
|
138
|
+
query ListUsers {
|
|
139
|
+
users {
|
|
112
140
|
id
|
|
113
141
|
name
|
|
114
142
|
}
|
|
115
143
|
}
|
|
116
144
|
`,
|
|
145
|
+
method: GraphqlMethod.GET,
|
|
117
146
|
});
|
|
118
147
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
148
|
+
// GET {client.url}?query=...&variables=...
|
|
149
|
+
await listUsers.send();
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Typed documents
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { GetUserDocument } from "./gql/graphql";
|
|
122
156
|
|
|
123
|
-
|
|
157
|
+
// data and variables are typed from the generated document - no generics
|
|
158
|
+
const getUserOperation = client.createRequest()({ endpoint: GetUserDocument });
|
|
159
|
+
await getUserOperation.send({ payload: { id: "1" } });
|
|
124
160
|
```
|
|
125
161
|
|
|
126
|
-
###
|
|
162
|
+
### Subscriptions
|
|
127
163
|
|
|
128
|
-
```
|
|
129
|
-
import {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
164
|
+
```ts
|
|
165
|
+
import { Socket } from "@hyper-fetch/sockets";
|
|
166
|
+
import { GraphqlWsAdapter } from "@hyper-fetch/graphql";
|
|
167
|
+
|
|
168
|
+
const socket = new Socket({
|
|
169
|
+
url: "wss://api.example.com/graphql",
|
|
170
|
+
adapter: GraphqlWsAdapter(),
|
|
171
|
+
// Runs on every connection attempt, so a reconnect sends a fresh token
|
|
172
|
+
adapterOptions: { connectionParams: async () => ({ token: await getToken() }) },
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const onMessage = socket.createListener()({ topic: "OnMessage", options: { document: OnMessageDocument } });
|
|
176
|
+
|
|
177
|
+
onMessage.setPayload({ room: "general" }).listen(({ data, extra }) => {
|
|
178
|
+
console.log(data.onMessage.text, extra.errors);
|
|
179
|
+
});
|
|
143
180
|
```
|
|
144
181
|
|
|
182
|
+
## 🧩 Hyper Fetch Ecosystem
|
|
183
|
+
|
|
184
|
+
One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
|
|
185
|
+
|
|
186
|
+
<table align="center">
|
|
187
|
+
<tr>
|
|
188
|
+
<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>
|
|
189
|
+
<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>
|
|
190
|
+
<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>
|
|
191
|
+
<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>
|
|
192
|
+
<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>
|
|
193
|
+
<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>
|
|
194
|
+
</tr>
|
|
195
|
+
<tr>
|
|
196
|
+
<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>
|
|
197
|
+
<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>
|
|
198
|
+
<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>
|
|
199
|
+
<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>
|
|
200
|
+
<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>
|
|
201
|
+
<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>
|
|
202
|
+
</tr>
|
|
203
|
+
</table>
|
|
204
|
+
|
|
205
|
+
## 💖 Sponsors
|
|
206
|
+
|
|
207
|
+
<p align="center">
|
|
208
|
+
<a href="https://github.com/sponsors/prc5">
|
|
209
|
+
<img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
|
|
210
|
+
</a>
|
|
211
|
+
</p>
|
|
212
|
+
|
|
145
213
|
## License
|
|
146
214
|
|
|
147
215
|
[Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment node
|
|
3
|
+
*/
|
|
4
|
+
import { Socket } from "@hyper-fetch/sockets";
|
|
5
|
+
import type { GraphQLFormattedError } from "graphql";
|
|
6
|
+
import { createClient } from "graphql-ws";
|
|
7
|
+
|
|
8
|
+
import { GraphqlSubscriptionError, GraphqlWsAdapter } from "../../src";
|
|
9
|
+
import type { ServerState } from "./e2e.graphql-ws-server";
|
|
10
|
+
import { createE2EGraphqlWsServer, createServerState } from "./e2e.graphql-ws-server";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What a client observed of one subscription: every result in order and how it ended. Both clients are reduced to it,
|
|
14
|
+
* so the adapter can be compared with the reference client of the protocol.
|
|
15
|
+
*/
|
|
16
|
+
type ResultType = { data: unknown; errors?: readonly GraphQLFormattedError[] };
|
|
17
|
+
|
|
18
|
+
type ObservedType = {
|
|
19
|
+
results: ResultType[];
|
|
20
|
+
end: "complete" | "stopped" | { errors: readonly GraphQLFormattedError[] };
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type ScenarioType = {
|
|
24
|
+
name: string;
|
|
25
|
+
query: string;
|
|
26
|
+
variables?: Record<string, unknown>;
|
|
27
|
+
connectionParams?: Record<string, unknown>;
|
|
28
|
+
/** Runs once the subscription is active on the server, e.g. publishes events */
|
|
29
|
+
act?: (state: ServerState) => void;
|
|
30
|
+
/** Stop after this many results - for subscriptions that never end on their own */
|
|
31
|
+
take?: number;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const scenarios: ScenarioType[] = [
|
|
35
|
+
{
|
|
36
|
+
name: "events of the variables",
|
|
37
|
+
query: "subscription OnMessage($room: String!) { onMessage(room: $room) { id text } }",
|
|
38
|
+
variables: { room: "a" },
|
|
39
|
+
act: (state) => {
|
|
40
|
+
state.publish({ id: "1", room: "b", text: "other room" });
|
|
41
|
+
state.publish({ id: "2", room: "a", text: "first" });
|
|
42
|
+
state.publish({ id: "3", room: "a", text: "second" });
|
|
43
|
+
},
|
|
44
|
+
take: 2,
|
|
45
|
+
},
|
|
46
|
+
{ name: "a completed subscription", query: "subscription { countdown(from: 3) }" },
|
|
47
|
+
{ name: "a subscription without events", query: "subscription { countdown(from: 0) }" },
|
|
48
|
+
{ name: "a validation error", query: "subscription { unknownField }" },
|
|
49
|
+
{ name: "missing variables", query: "subscription OnMessage($room: String!) { onMessage(room: $room) { id } }" },
|
|
50
|
+
{ name: "an execution error of an event", query: "subscription { failing }", take: 1 },
|
|
51
|
+
{ name: "connection params in the context", query: "subscription { whoAmI }", connectionParams: { token: "ann" } },
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
describe("Graphql Ws Adapter [ Conformance with graphql-ws ]", () => {
|
|
55
|
+
let state: ServerState = createServerState();
|
|
56
|
+
let server = createE2EGraphqlWsServer(state);
|
|
57
|
+
let url = "";
|
|
58
|
+
|
|
59
|
+
beforeEach(async () => {
|
|
60
|
+
state = createServerState();
|
|
61
|
+
server = createE2EGraphqlWsServer(state);
|
|
62
|
+
url = await server.startServer();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
afterEach(async () => {
|
|
66
|
+
await server.stopServer();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/** Waits until the subscription runs on the server, then lets the scenario act */
|
|
70
|
+
const actWhenActive = async (scenario: ScenarioType) => {
|
|
71
|
+
if (!scenario.act) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await vi.waitFor(() => expect(state.active("onMessage")).toHaveLength(1));
|
|
75
|
+
scenario.act(state);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const observeWithGraphqlWs = async (scenario: ScenarioType): Promise<ObservedType> => {
|
|
79
|
+
const client = createClient({ url, connectionParams: scenario.connectionParams, retryAttempts: 0 });
|
|
80
|
+
const results: ResultType[] = [];
|
|
81
|
+
try {
|
|
82
|
+
return await new Promise<ObservedType>((resolve) => {
|
|
83
|
+
const dispose = client.subscribe(
|
|
84
|
+
{ query: scenario.query, variables: scenario.variables },
|
|
85
|
+
{
|
|
86
|
+
next: (result) => {
|
|
87
|
+
// Listeners always get `data` - `null` where the result of the reference client has none
|
|
88
|
+
results.push(
|
|
89
|
+
result.errors ? { data: result.data ?? null, errors: result.errors } : { data: result.data ?? null },
|
|
90
|
+
);
|
|
91
|
+
if (results.length === scenario.take) {
|
|
92
|
+
dispose();
|
|
93
|
+
resolve({ results, end: "stopped" });
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
error: (errors) => resolve({ results, end: { errors: errors as GraphQLFormattedError[] } }),
|
|
97
|
+
complete: () => resolve({ results, end: "complete" }),
|
|
98
|
+
},
|
|
99
|
+
);
|
|
100
|
+
actWhenActive(scenario);
|
|
101
|
+
});
|
|
102
|
+
} finally {
|
|
103
|
+
await client.dispose();
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const observeWithAdapter = async (scenario: ScenarioType): Promise<ObservedType> => {
|
|
108
|
+
const socket = new Socket({
|
|
109
|
+
url,
|
|
110
|
+
adapter: GraphqlWsAdapter(),
|
|
111
|
+
adapterOptions: { connectionParams: scenario.connectionParams },
|
|
112
|
+
});
|
|
113
|
+
const listener = socket.createListener<unknown, Record<string, unknown> | undefined>()({
|
|
114
|
+
topic: scenario.query,
|
|
115
|
+
});
|
|
116
|
+
const results: ResultType[] = [];
|
|
117
|
+
try {
|
|
118
|
+
return await new Promise<ObservedType>((resolve) => {
|
|
119
|
+
const stop = listener.setPayload(scenario.variables).listen(
|
|
120
|
+
({ data, extra }) => {
|
|
121
|
+
// The reference client hands over the raw result - errors are left out when the server sent none
|
|
122
|
+
results.push(extra.errors ? { data, errors: extra.errors } : { data });
|
|
123
|
+
if (results.length === scenario.take) {
|
|
124
|
+
stop();
|
|
125
|
+
resolve({ results, end: "stopped" });
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
onEnd: ({ error }) => {
|
|
130
|
+
if (error instanceof GraphqlSubscriptionError) {
|
|
131
|
+
resolve({ results, end: { errors: error.errors } });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
resolve({ results, end: "complete" });
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
);
|
|
138
|
+
actWhenActive(scenario);
|
|
139
|
+
});
|
|
140
|
+
} finally {
|
|
141
|
+
await socket.disconnect();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
it.each(scenarios)("should observe the same as graphql-ws for $name", async (scenario) => {
|
|
146
|
+
const reference = await observeWithGraphqlWs(scenario);
|
|
147
|
+
state = createServerState();
|
|
148
|
+
await server.stopServer();
|
|
149
|
+
server = createE2EGraphqlWsServer(state);
|
|
150
|
+
url = await server.startServer();
|
|
151
|
+
|
|
152
|
+
const observed = await observeWithAdapter(scenario);
|
|
153
|
+
|
|
154
|
+
expect(observed).toStrictEqual(reference);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("should send the same handshake and subscription messages as graphql-ws", async () => {
|
|
158
|
+
const received: { client: string; messages: unknown[] }[] = [];
|
|
159
|
+
const record = (client: string) => {
|
|
160
|
+
const entry = { client, messages: [] as unknown[] };
|
|
161
|
+
received.push(entry);
|
|
162
|
+
return entry.messages;
|
|
163
|
+
};
|
|
164
|
+
await server.stopServer();
|
|
165
|
+
let current: unknown[] = [];
|
|
166
|
+
server = createE2EGraphqlWsServer(state, {
|
|
167
|
+
onConnect: (ctx) => {
|
|
168
|
+
current.push({ type: "connection_init", payload: ctx.connectionParams });
|
|
169
|
+
return true;
|
|
170
|
+
},
|
|
171
|
+
onSubscribe: (_, id, payload) => {
|
|
172
|
+
current.push({ type: "subscribe", payload });
|
|
173
|
+
},
|
|
174
|
+
onComplete: () => {
|
|
175
|
+
current.push({ type: "complete" });
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
url = await server.startServer();
|
|
179
|
+
const scenario: ScenarioType = {
|
|
180
|
+
name: "handshake",
|
|
181
|
+
query: "subscription OnMessage($room: String!) { onMessage(room: $room) { id text } }",
|
|
182
|
+
variables: { room: "a" },
|
|
183
|
+
connectionParams: { token: "ann" },
|
|
184
|
+
act: (serverState) => serverState.publish({ id: "1", room: "a", text: "hi" }),
|
|
185
|
+
take: 1,
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
current = record("graphql-ws");
|
|
189
|
+
await observeWithGraphqlWs(scenario);
|
|
190
|
+
await vi.waitFor(() => expect(current).toContainEqual({ type: "complete" }));
|
|
191
|
+
current = record("adapter");
|
|
192
|
+
await observeWithAdapter(scenario);
|
|
193
|
+
await vi.waitFor(() => expect(current).toContainEqual({ type: "complete" }));
|
|
194
|
+
|
|
195
|
+
const [reference, adapter] = received;
|
|
196
|
+
// The adapter sends the operation name too, which the reference client leaves to the caller
|
|
197
|
+
expect(adapter.messages).toStrictEqual([
|
|
198
|
+
reference.messages[0],
|
|
199
|
+
{
|
|
200
|
+
type: "subscribe",
|
|
201
|
+
payload: { ...(reference.messages[1] as { payload: object }).payload, operationName: "OnMessage" },
|
|
202
|
+
},
|
|
203
|
+
reference.messages[2],
|
|
204
|
+
]);
|
|
205
|
+
});
|
|
206
|
+
});
|