@alxia/graphql 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/dist/testing/client.d.ts +57 -0
- package/dist/testing/client.d.ts.map +1 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +47 -0
- package/dist/testing/index.js.map +10 -0
- package/docs/README.md +2 -1
- package/docs/guide/endpoint.md +13 -12
- package/docs/guide/testing.md +107 -0
- package/docs/roadmap.md +9 -1
- package/package.json +12 -6
package/README.md
CHANGED
|
@@ -206,6 +206,25 @@ app.listen({ port: 4000 });
|
|
|
206
206
|
|
|
207
207
|
See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#errors-health-and-shutdown).
|
|
208
208
|
|
|
209
|
+
## Testing
|
|
210
|
+
|
|
211
|
+
`graphqlClient` from `@alxia/graphql/testing` sends operations to the app
|
|
212
|
+
in process, through `app.fetch`: no port. It is a subpath, so the main entry
|
|
213
|
+
and a production bundle never carry it.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { graphqlClient } from '@alxia/graphql/testing';
|
|
217
|
+
|
|
218
|
+
const client = graphqlClient(app, { headers: { authorization: `Bearer ${token}` } });
|
|
219
|
+
const { status, data, errors } = await client.query(
|
|
220
|
+
'query ($name: String!) { hello(name: $name) }',
|
|
221
|
+
{ variables: { name: 'Ada' } },
|
|
222
|
+
);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
A `TypedDocumentNode` types `data` and the variables. See
|
|
226
|
+
[the testing guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/testing.md).
|
|
227
|
+
|
|
209
228
|
## API
|
|
210
229
|
|
|
211
230
|
| export | |
|
|
@@ -217,6 +236,8 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
|
|
|
217
236
|
| `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
|
|
218
237
|
| `GraphQLContext<App, UserContext?>` | what a resolver reads |
|
|
219
238
|
| `ServerContext<Ctx>`, `GraphQLOptions` | its types |
|
|
239
|
+
| `graphqlClient(app, { path?, headers? })` (`@alxia/graphql/testing`) | `query(document, { variables?, operationName?, headers? })` in process: `{ status, data?, errors?, response }` |
|
|
240
|
+
| `GraphQLClient`, `GraphQLResult`, `QueryDocument`, `QueryOptions`, `GraphQLClientOptions`, `ResponseError` (`@alxia/graphql/testing`) | its types |
|
|
220
241
|
|
|
221
242
|
## Documentation
|
|
222
243
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type DocumentNode, type TypedQueryDocumentNode } from 'graphql';
|
|
2
|
+
/**
|
|
3
|
+
* A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,
|
|
4
|
+
* or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that
|
|
5
|
+
* GraphQL Code Generator writes, read by its `__apiType` marker. Both are a
|
|
6
|
+
* `DocumentNode` with an optional function, so neither package is imported.
|
|
7
|
+
*/
|
|
8
|
+
export type QueryDocument<TData = unknown, TVars = Record<string, unknown>> = string | TypedQueryDocumentNode<TData extends object ? TData : never, TVars> | (DocumentNode & {
|
|
9
|
+
__apiType?: (variables: TVars) => TData;
|
|
10
|
+
});
|
|
11
|
+
/** One entry of a response's `errors`. */
|
|
12
|
+
export interface ResponseError {
|
|
13
|
+
readonly message: string;
|
|
14
|
+
readonly path?: readonly (string | number)[];
|
|
15
|
+
readonly extensions?: {
|
|
16
|
+
readonly code?: string;
|
|
17
|
+
readonly [key: string]: unknown;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** What `query` resolves to: the HTTP status, the parsed body, the response. */
|
|
21
|
+
export interface GraphQLResult<TData = unknown> {
|
|
22
|
+
readonly status: number;
|
|
23
|
+
readonly data?: TData | null;
|
|
24
|
+
readonly errors?: readonly ResponseError[];
|
|
25
|
+
/** The response, its body still unread: `headers`, `ok`. */
|
|
26
|
+
readonly response: Response;
|
|
27
|
+
}
|
|
28
|
+
export interface GraphQLClientOptions {
|
|
29
|
+
/** The endpoint's path. Default `/graphql`. */
|
|
30
|
+
readonly path?: string;
|
|
31
|
+
/** Sent with every query: an `authorization` header, a CSRF one. */
|
|
32
|
+
readonly headers?: HeadersInit;
|
|
33
|
+
}
|
|
34
|
+
export interface QueryOptions<TVars = Record<string, unknown>> {
|
|
35
|
+
readonly variables?: TVars;
|
|
36
|
+
readonly operationName?: string;
|
|
37
|
+
/** Added to the client's, and replacing one of the same name. */
|
|
38
|
+
readonly headers?: HeadersInit;
|
|
39
|
+
}
|
|
40
|
+
export interface GraphQLClient {
|
|
41
|
+
query<TData = unknown, TVars = Record<string, unknown>>(document: QueryDocument<TData, TVars>, options?: QueryOptions<TVars>): Promise<GraphQLResult<TData>>;
|
|
42
|
+
}
|
|
43
|
+
/** What it calls: an alxia app, or anything with a `fetch(Request)`. */
|
|
44
|
+
export interface Servable {
|
|
45
|
+
fetch(request: Request): Response | Promise<Response>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Sends operations to an app's GraphQL endpoint in process, through
|
|
49
|
+
* `app.fetch`: no port, no server, the whole chain (middlewares, body limit,
|
|
50
|
+
* Yoga's plugins) in play. Meant for specs; import it from
|
|
51
|
+
* `@alxia/graphql/testing`, never from the app.
|
|
52
|
+
*
|
|
53
|
+
* A body that is not JSON (a 413 from a body limit, a 404) leaves `data` and
|
|
54
|
+
* `errors` unset: read `status`, or `response`'s headers.
|
|
55
|
+
*/
|
|
56
|
+
export declare function graphqlClient(app: Servable, options?: GraphQLClientOptions): GraphQLClient;
|
|
57
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/testing/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEhF;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IACvE,MAAM,GACN,sBAAsB,CAAC,KAAK,SAAS,MAAM,GAAG,KAAK,GAAG,KAAK,EAAE,KAAK,CAAC,GACnE,CAAC,YAAY,GAAG;IAAE,SAAS,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,KAAK,KAAK,CAAA;CAAE,CAAC,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAC7C,QAAQ,CAAC,UAAU,CAAC,EAAE;QACrB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QACvB,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KAChC,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,WAAW,aAAa,CAAC,KAAK,GAAG,OAAO;IAC7C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;IAC3C,4DAA4D;IAC5D,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC5B;AAED,MAAM,WAAW,oBAAoB;IACpC,+CAA+C;IAC/C,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,oEAAoE;IACpE,QAAQ,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,YAAY,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC5D,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;IAC3B,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,iEAAiE;IACjE,QAAQ,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrD,QAAQ,EAAE,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,EACrC,OAAO,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,GAC3B,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;CACjC;AAED,wEAAwE;AACxE,MAAM,WAAW,QAAQ;IACxB,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtD;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,QAAQ,EACb,OAAO,GAAE,oBAAyB,GAChC,aAAa,CAyBf"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,GAClB,MAAM,UAAU,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// src/testing/client.ts
|
|
2
|
+
import { print } from "graphql";
|
|
3
|
+
function graphqlClient(app, options = {}) {
|
|
4
|
+
const { path = "/graphql" } = options;
|
|
5
|
+
return {
|
|
6
|
+
async query(document, call = {}) {
|
|
7
|
+
const headers = new Headers(options.headers);
|
|
8
|
+
headers.set("content-type", "application/json");
|
|
9
|
+
for (const [name, value] of new Headers(call.headers)) {
|
|
10
|
+
headers.set(name, value);
|
|
11
|
+
}
|
|
12
|
+
const body = JSON.stringify({
|
|
13
|
+
query: typeof document === "string" ? document : print(document),
|
|
14
|
+
variables: call.variables,
|
|
15
|
+
operationName: call.operationName
|
|
16
|
+
});
|
|
17
|
+
const response = await app.fetch(new Request(new URL(path, "http://localhost"), {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers,
|
|
20
|
+
body
|
|
21
|
+
}));
|
|
22
|
+
const text = await response.clone().text();
|
|
23
|
+
return { status: response.status, ...parse(text), response };
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function parse(text) {
|
|
28
|
+
try {
|
|
29
|
+
const body = JSON.parse(text);
|
|
30
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
const { data, errors } = body;
|
|
34
|
+
return {
|
|
35
|
+
...data === undefined ? {} : { data },
|
|
36
|
+
...errors === undefined ? {} : { errors }
|
|
37
|
+
};
|
|
38
|
+
} catch {
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
graphqlClient
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
//# debugId=BDA79F393E3D161364756E2164756E21
|
|
47
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/testing/client.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { type DocumentNode, print, type TypedQueryDocumentNode } from 'graphql';\n\n/**\n * A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,\n * or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that\n * GraphQL Code Generator writes, read by its `__apiType` marker. Both are a\n * `DocumentNode` with an optional function, so neither package is imported.\n */\nexport type QueryDocument<TData = unknown, TVars = Record<string, unknown>> =\n\t| string\n\t| TypedQueryDocumentNode<TData extends object ? TData : never, TVars>\n\t| (DocumentNode & { __apiType?: (variables: TVars) => TData });\n\n/** One entry of a response's `errors`. */\nexport interface ResponseError {\n\treadonly message: string;\n\treadonly path?: readonly (string | number)[];\n\treadonly extensions?: {\n\t\treadonly code?: string;\n\t\treadonly [key: string]: unknown;\n\t};\n}\n\n/** What `query` resolves to: the HTTP status, the parsed body, the response. */\nexport interface GraphQLResult<TData = unknown> {\n\treadonly status: number;\n\treadonly data?: TData | null;\n\treadonly errors?: readonly ResponseError[];\n\t/** The response, its body still unread: `headers`, `ok`. */\n\treadonly response: Response;\n}\n\nexport interface GraphQLClientOptions {\n\t/** The endpoint's path. Default `/graphql`. */\n\treadonly path?: string;\n\t/** Sent with every query: an `authorization` header, a CSRF one. */\n\treadonly headers?: HeadersInit;\n}\n\nexport interface QueryOptions<TVars = Record<string, unknown>> {\n\treadonly variables?: TVars;\n\treadonly operationName?: string;\n\t/** Added to the client's, and replacing one of the same name. */\n\treadonly headers?: HeadersInit;\n}\n\nexport interface GraphQLClient {\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\tdocument: QueryDocument<TData, TVars>,\n\t\toptions?: QueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n}\n\n/** What it calls: an alxia app, or anything with a `fetch(Request)`. */\nexport interface Servable {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Sends operations to an app's GraphQL endpoint in process, through\n * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,\n * Yoga's plugins) in play. Meant for specs; import it from\n * `@alxia/graphql/testing`, never from the app.\n *\n * A body that is not JSON (a 413 from a body limit, a 404) leaves `data` and\n * `errors` unset: read `status`, or `response`'s headers.\n */\nexport function graphqlClient(\n\tapp: Servable,\n\toptions: GraphQLClientOptions = {},\n): GraphQLClient {\n\tconst { path = '/graphql' } = options;\n\treturn {\n\t\tasync query(document, call = {}) {\n\t\t\tconst headers = new Headers(options.headers);\n\t\t\theaders.set('content-type', 'application/json');\n\t\t\tfor (const [name, value] of new Headers(call.headers)) {\n\t\t\t\theaders.set(name, value);\n\t\t\t}\n\t\t\tconst body = JSON.stringify({\n\t\t\t\tquery: typeof document === 'string' ? document : print(document),\n\t\t\t\tvariables: call.variables,\n\t\t\t\toperationName: call.operationName,\n\t\t\t});\n\t\t\tconst response = await app.fetch(\n\t\t\t\tnew Request(new URL(path, 'http://localhost'), {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst text = await response.clone().text();\n\t\t\treturn { status: response.status, ...parse(text), response };\n\t\t},\n\t};\n}\n\n/** `data` and `errors` of a JSON object body, each only when it has one. */\nfunction parse<TData>(text: string): {\n\tdata?: TData | null;\n\terrors?: readonly ResponseError[];\n} {\n\ttry {\n\t\tconst body: unknown = JSON.parse(text);\n\t\tif (typeof body !== 'object' || body === null || Array.isArray(body)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst { data, errors } = body as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(data === undefined ? {} : { data: data as TData | null }),\n\t\t\t...(errors === undefined\n\t\t\t\t? {}\n\t\t\t\t: { errors: errors as readonly ResponseError[] }),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AAAA;AAmEO,SAAS,aAAa,CAC5B,KACA,UAAgC,CAAC,GACjB;AAAA,EAChB,QAAQ,OAAO,eAAe;AAAA,EAC9B,OAAO;AAAA,SACA,MAAK,CAAC,UAAU,OAAO,CAAC,GAAG;AAAA,MAChC,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAAA,MAC3C,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,MAC9C,YAAY,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO,GAAG;AAAA,QACtD,QAAQ,IAAI,MAAM,KAAK;AAAA,MACxB;AAAA,MACA,MAAM,OAAO,KAAK,UAAU;AAAA,QAC3B,OAAO,OAAO,aAAa,WAAW,WAAW,MAAM,QAAQ;AAAA,QAC/D,WAAW,KAAK;AAAA,QAChB,eAAe,KAAK;AAAA,MACrB,CAAC;AAAA,MACD,MAAM,WAAW,MAAM,IAAI,MAC1B,IAAI,QAAQ,IAAI,IAAI,MAAM,kBAAkB,GAAG;AAAA,QAC9C,QAAQ;AAAA,QACR;AAAA,QACA;AAAA,MACD,CAAC,CACF;AAAA,MACA,MAAM,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;AAAA,MACzC,OAAO,EAAE,QAAQ,SAAS,WAAW,MAAM,IAAI,GAAG,SAAS;AAAA;AAAA,EAE7D;AAAA;AAID,SAAS,KAAY,CAAC,MAGpB;AAAA,EACD,IAAI;AAAA,IACH,MAAM,OAAgB,KAAK,MAAM,IAAI;AAAA,IACrC,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AAAA,MACrE,OAAO,CAAC;AAAA,IACT;AAAA,IACA,QAAQ,MAAM,WAAW;AAAA,IACzB,OAAO;AAAA,SACF,SAAS,YAAY,CAAC,IAAI,EAAE,KAA2B;AAAA,SACvD,WAAW,YACZ,CAAC,IACD,EAAE,OAA2C;AAAA,IACjD;AAAA,IACC,MAAM;AAAA,IACP,OAAO,CAAC;AAAA;AAAA;",
|
|
8
|
+
"debugId": "BDA79F393E3D161364756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
package/docs/README.md
CHANGED
|
@@ -8,12 +8,13 @@ a realistic example for each.
|
|
|
8
8
|
|
|
9
9
|
| Page | Read it when |
|
|
10
10
|
| --- | --- |
|
|
11
|
-
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or
|
|
11
|
+
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or its first spec |
|
|
12
12
|
| [The typed context](guide/context.md) | typing a schema with the app's context, reading `user` or a database handle in a resolver, setting a cookie, adding per-request loaders, or reading the `missing …` compile error |
|
|
13
13
|
| [Yoga's plugins and options](guide/yoga.md) | adding Yoga or Envelop plugins, exposing or masking errors, batching, serving subscriptions, or calling the endpoint from another origin |
|
|
14
14
|
| [GraphQL over WebSocket](guide/websockets.md) | serving Apollo Client's, urql's or `graphql-ws`'s WebSocket clients with `ws: true`, guarding the upgrade, reading `connectionParams`, the subprotocol, closing the sockets on shutdown, or testing a subscription over a socket |
|
|
15
15
|
| [Harden it for production](guide/production.md) | putting a GraphQL API on the internet: rate limiting the endpoint, depth limits, introspection off outside development, masked errors and the errors a client may read, a body limit, CSRF for a cookie session, persisted operations |
|
|
16
16
|
| [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or serving it outside dev with `ide: 'graphiql'` |
|
|
17
|
+
| [Testing the endpoint](guide/testing.md) | testing a GraphQL app without a server: `graphqlClient`, an auth header, a custom path, a typed document, the HTTP status of a 400 or a 413 |
|
|
17
18
|
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
|
|
18
19
|
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
19
20
|
|
package/docs/guide/endpoint.md
CHANGED
|
@@ -228,14 +228,16 @@ app.listen({ port: 4000 }); // SIGTERM: /ready 503, queries answered, subscripti
|
|
|
228
228
|
|
|
229
229
|
## Testing it
|
|
230
230
|
|
|
231
|
-
The endpoint runs in process through `app.
|
|
232
|
-
|
|
233
|
-
|
|
231
|
+
The endpoint runs in process through `app.fetch`, like every alxia route:
|
|
232
|
+
no server, no port. `graphqlClient` from `@alxia/graphql/testing` sends the
|
|
233
|
+
operation and reads the answer; `logging: false` keeps Yoga's logger quiet
|
|
234
|
+
in the test output.
|
|
234
235
|
|
|
235
236
|
```ts
|
|
236
237
|
import { describe, expect, test } from 'bun:test';
|
|
237
238
|
import { alxia } from '@alxia/core';
|
|
238
239
|
import { graphql } from '@alxia/graphql';
|
|
240
|
+
import { graphqlClient } from '@alxia/graphql/testing';
|
|
239
241
|
import { createSchema } from 'graphql-yoga';
|
|
240
242
|
|
|
241
243
|
const schema = createSchema({
|
|
@@ -245,21 +247,20 @@ const schema = createSchema({
|
|
|
245
247
|
|
|
246
248
|
const app = alxia().plugin((app) => graphql(app, { schema, logging: false }));
|
|
247
249
|
|
|
248
|
-
const execute = (query: string, variables?: Record<string, unknown>) =>
|
|
249
|
-
app.request('/graphql', {
|
|
250
|
-
method: 'POST',
|
|
251
|
-
headers: { 'content-type': 'application/json' },
|
|
252
|
-
body: JSON.stringify({ query, variables }),
|
|
253
|
-
});
|
|
254
|
-
|
|
255
250
|
describe('graphql', () => {
|
|
256
251
|
test('hello', async () => {
|
|
257
|
-
const
|
|
258
|
-
|
|
252
|
+
const { data } = await graphqlClient(app).query(
|
|
253
|
+
'query ($name: String!) { hello(name: $name) }',
|
|
254
|
+
{ variables: { name: 'Ada' } },
|
|
255
|
+
);
|
|
256
|
+
expect(data).toEqual({ hello: 'hello Ada' });
|
|
259
257
|
});
|
|
260
258
|
});
|
|
261
259
|
```
|
|
262
260
|
|
|
261
|
+
Headers, a custom path, typed documents and the HTTP status are in
|
|
262
|
+
[Testing the endpoint](testing.md).
|
|
263
|
+
|
|
263
264
|
## See also
|
|
264
265
|
|
|
265
266
|
- [The typed context](context.md): what a resolver reads, and the compile
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Testing the endpoint
|
|
2
|
+
|
|
3
|
+
`graphqlClient` sends an operation to an app's GraphQL endpoint in process,
|
|
4
|
+
through `app.fetch`: no port, no server, and the whole chain in play (the
|
|
5
|
+
app's middlewares, its body limit, Yoga's plugins). It is a helper for
|
|
6
|
+
specs, so it lives in its own subpath, `@alxia/graphql/testing`: the main
|
|
7
|
+
entry stays what an app ships, and a production bundle never carries it.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { expect, test } from 'bun:test';
|
|
11
|
+
import { graphqlClient } from '@alxia/graphql/testing';
|
|
12
|
+
import { app } from './app';
|
|
13
|
+
|
|
14
|
+
test('hello', async () => {
|
|
15
|
+
const { status, data, errors } = await graphqlClient(app).query(
|
|
16
|
+
'query ($name: String!) { hello(name: $name) }',
|
|
17
|
+
{ variables: { name: 'Ada' } },
|
|
18
|
+
);
|
|
19
|
+
expect(status).toBe(200);
|
|
20
|
+
expect(errors).toBeUndefined();
|
|
21
|
+
expect(data).toEqual({ hello: 'hello Ada' });
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## What `app` can be
|
|
26
|
+
|
|
27
|
+
`graphqlClient` calls `app.fetch(request)`, so `app` is an alxia app or anything
|
|
28
|
+
with a `fetch(Request)` that answers a `Response`: a Yoga instance, a
|
|
29
|
+
handler of your own, a stub.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const client = graphqlClient({ fetch: (request) => yoga.fetch(request) });
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## The result
|
|
36
|
+
|
|
37
|
+
`query` resolves to `{ status, data?, errors?, response }`:
|
|
38
|
+
|
|
39
|
+
| field | |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `status` | the HTTP status: 200 for a GraphQL answer, errors included; 400 for a request Yoga refuses, 401 or 403 from a guard, 413 over a body limit |
|
|
42
|
+
| `data`, `errors` | the JSON body's own, each unset when the body has none |
|
|
43
|
+
| `response` | the `Response`, its body unread: `headers`, `ok` |
|
|
44
|
+
|
|
45
|
+
A GraphQL error is an entry of `errors`, never a rejection. A body that is
|
|
46
|
+
not JSON (a 413, a 404) leaves `data` and `errors` unset: read `status`.
|
|
47
|
+
|
|
48
|
+
## Headers
|
|
49
|
+
|
|
50
|
+
`graphqlClient(app, { headers })` sends them with every query, which is
|
|
51
|
+
where a token goes; a call's `headers` are added to them, and replace one of
|
|
52
|
+
the same name:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const ada = graphqlClient(app, { headers: { authorization: `Bearer ${token}` } });
|
|
56
|
+
|
|
57
|
+
expect((await ada.query('{ me { name } }')).data).toEqual({ me: { name: 'Ada' } });
|
|
58
|
+
|
|
59
|
+
const anonymous = await ada.query('{ me { name } }', { headers: { authorization: '' } });
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## A custom path
|
|
63
|
+
|
|
64
|
+
`path` is the endpoint's, `/graphql` by default:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const client = graphqlClient(app, { path: '/api/graphql' });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Variables and operation names
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
await client.query(document, { variables: { id: '1' }, operationName: 'GetNote' });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`TData` and `TVars` are the result's and the variables' types, and default
|
|
77
|
+
to `unknown` and `Record<string, unknown>`; name them when the document is a
|
|
78
|
+
string: `client.query<{ me: { name: string } }>('{ me { name } }')`.
|
|
79
|
+
|
|
80
|
+
## A typed document
|
|
81
|
+
|
|
82
|
+
A `TypedDocumentNode`, as GraphQL Code Generator's `typed-document-node`
|
|
83
|
+
plugin writes it (`@graphql-typed-document-node/core`), or `graphql`'s own
|
|
84
|
+
`TypedQueryDocumentNode`, is printed to a string, and gives `data` and
|
|
85
|
+
`variables` their types, with no extra dependency:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import type { TypedQueryDocumentNode } from 'graphql';
|
|
89
|
+
import { parse } from 'graphql';
|
|
90
|
+
|
|
91
|
+
const Hello = parse('query Hello($name: String!) { hello(name: $name) }') as TypedQueryDocumentNode<
|
|
92
|
+
{ hello: string },
|
|
93
|
+
{ name: string }
|
|
94
|
+
>;
|
|
95
|
+
|
|
96
|
+
const { data } = await client.query(Hello, { variables: { name: 'Ada' } });
|
|
97
|
+
data?.hello; // string
|
|
98
|
+
// client.query(Hello, { variables: { name: 1 } }); // compile error
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Not covered
|
|
102
|
+
|
|
103
|
+
It always POSTs JSON. A subscription over server-sent events or a socket,
|
|
104
|
+
a `GET` and a persisted operation sent by hash are not sent by it; use
|
|
105
|
+
`app.request` for those (the
|
|
106
|
+
[recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#6-test-it-in-process)
|
|
107
|
+
reads a stream).
|
package/docs/roadmap.md
CHANGED
|
@@ -30,7 +30,8 @@ number on it. Every release, with each change it made, is in
|
|
|
30
30
|
|
|
31
31
|
## Next
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
- **Persisted operations in the test client.** A `GET` and a hash sent in
|
|
34
|
+
place of the document, for an app that allows nothing else.
|
|
34
35
|
|
|
35
36
|
## Later
|
|
36
37
|
|
|
@@ -38,6 +39,13 @@ Nothing scheduled yet.
|
|
|
38
39
|
|
|
39
40
|
## Shipped
|
|
40
41
|
|
|
42
|
+
### 0.7.0
|
|
43
|
+
|
|
44
|
+
- **A test client.** `graphqlClient(app)` from `@alxia/graphql/testing`
|
|
45
|
+
sends a query, its variables and headers to the endpoint in process, and
|
|
46
|
+
returns `{ status, data, errors, response }`; a `TypedDocumentNode` types
|
|
47
|
+
the answer; `app` is anything with a `fetch(Request)` ([testing guide](guide/testing.md)).
|
|
48
|
+
|
|
41
49
|
### 0.6.0
|
|
42
50
|
|
|
43
51
|
- **Each operation over a socket.** Over `ws: true`, every query, mutation and subscription on a socket is told to the observers around its upgrade, from its `subscribe` message to its end, with whether it was answered with errors: `@alxia/logger` writes a line for each, `@alxia/telemetry` a span, a child of the upgrade's, named `subscription OnNote` ([WebSocket guide](guide/websockets.md#logging-and-tracing)).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/graphql",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE or WebSocket (graphql-ws) and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -19,6 +19,11 @@
|
|
|
19
19
|
"import": "./dist/index.js",
|
|
20
20
|
"default": "./dist/index.js"
|
|
21
21
|
},
|
|
22
|
+
"./testing": {
|
|
23
|
+
"types": "./dist/testing/index.d.ts",
|
|
24
|
+
"import": "./dist/testing/index.js",
|
|
25
|
+
"default": "./dist/testing/index.js"
|
|
26
|
+
},
|
|
22
27
|
"./package.json": "./package.json"
|
|
23
28
|
},
|
|
24
29
|
"repository": {
|
|
@@ -37,13 +42,14 @@
|
|
|
37
42
|
},
|
|
38
43
|
"alxia": {
|
|
39
44
|
"entrypoints": [
|
|
40
|
-
"src/index.ts"
|
|
45
|
+
"src/index.ts",
|
|
46
|
+
"src/testing/index.ts"
|
|
41
47
|
]
|
|
42
48
|
},
|
|
43
49
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
45
|
-
"@alxia/logger": "^0.6.
|
|
46
|
-
"@alxia/telemetry": "^0.7.
|
|
50
|
+
"@alxia/core": "^0.13.0",
|
|
51
|
+
"@alxia/logger": "^0.6.5",
|
|
52
|
+
"@alxia/telemetry": "^0.7.2",
|
|
47
53
|
"@envelop/depth-limit": "^7.2.1",
|
|
48
54
|
"@graphql-yoga/plugin-csrf-prevention": "^3.24.2",
|
|
49
55
|
"@graphql-yoga/plugin-persisted-operations": "^3.24.2",
|
|
@@ -55,7 +61,7 @@
|
|
|
55
61
|
"graphql-yoga": "^5.16.0"
|
|
56
62
|
},
|
|
57
63
|
"peerDependencies": {
|
|
58
|
-
"@alxia/core": "^0.
|
|
64
|
+
"@alxia/core": "^0.13.0",
|
|
59
65
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
60
66
|
"graphql-ws": "^6.1.0",
|
|
61
67
|
"graphql-yoga": "^5.16.0",
|