@alxia/create 0.2.0 → 0.3.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/package.json +6 -5
- package/templates/graphql/README.md +16 -2
- package/templates/graphql/package.json +1 -0
- package/templates/graphql/src/app.spec.ts +28 -1
- package/templates/graphql/src/app.ts +6 -2
- package/templates/graphql/src/context.ts +5 -3
- package/templates/graphql/src/loaders.ts +13 -0
- package/templates/graphql/src/resolvers.ts +2 -5
- package/templates/graphql/src/store.ts +13 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/create",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Start an alxia app: `bun create @alxia` writes a minimal API, a spec-first one, a GraphQL one, or React Router's official template served by alxia",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -41,16 +41,17 @@
|
|
|
41
41
|
]
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
44
|
+
"@alxia/core": "^0.6.0",
|
|
45
45
|
"@alxia/env": "^0.2.0",
|
|
46
|
-
"@alxia/graphql": "^0.3.
|
|
47
|
-
"@alxia/openapi": "^0.5.
|
|
48
|
-
"@alxia/react-router": "^0.6.
|
|
46
|
+
"@alxia/graphql": "^0.3.1",
|
|
47
|
+
"@alxia/openapi": "^0.5.1",
|
|
48
|
+
"@alxia/react-router": "^0.6.1",
|
|
49
49
|
"@graphql-codegen/cli": "7.4.3",
|
|
50
50
|
"@graphql-codegen/typescript": "6.1.0",
|
|
51
51
|
"@graphql-codegen/typescript-resolvers": "6.1.0",
|
|
52
52
|
"@nxgt/openapi-codegen": "0.7.0",
|
|
53
53
|
"@types/bun": "^1.4.2",
|
|
54
|
+
"dataloader": "^2.2.3",
|
|
54
55
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
55
56
|
"graphql-yoga": "^5.16.0",
|
|
56
57
|
"openapi-fetch": "^0.17.0",
|
|
@@ -29,8 +29,10 @@ curl localhost:3000/graphql -H 'content-type: application/json' \
|
|
|
29
29
|
resolver reads `viewer`, `db` and `env` from its context, typed.
|
|
30
30
|
- `src/context.ts`: the base app and its middleware. `viewerOf` reads
|
|
31
31
|
`Authorization: Bearer <token>` and gives every resolver `viewer`: the
|
|
32
|
-
user, or `null`. `Context` is `GraphQLContext<typeof base>`, which
|
|
32
|
+
user, or `null`. `Context` is `GraphQLContext<typeof base, { loaders }>`, which
|
|
33
33
|
`codegen.ts` hands to `Resolvers`.
|
|
34
|
+
- `src/loaders.ts`: the DataLoaders, built per request by the `context` option
|
|
35
|
+
of `src/app.ts` (`Note.author` loads its users in one batch: [Batching](#batching-n1)).
|
|
34
36
|
- `src/schema.ts`, `src/app.ts`: `createSchema` from `schema.graphql` and the
|
|
35
37
|
resolvers, then `health()`'s probes (`GET /health`, `GET /ready`) and
|
|
36
38
|
`graphql(app, { schema })` mounted on the base.
|
|
@@ -43,7 +45,8 @@ curl localhost:3000/graphql -H 'content-type: application/json' \
|
|
|
43
45
|
- `src/server.ts`: listens on `env.PORT`, 3000 by default, and shuts down
|
|
44
46
|
gracefully on `SIGINT` and `SIGTERM`, which `listen` handles.
|
|
45
47
|
- `src/app.spec.ts`: POST `/graphql` through `app.request()`, no port:
|
|
46
|
-
queries, the mutation with and without a token,
|
|
48
|
+
queries, the mutation with and without a token, one batch for N authors,
|
|
49
|
+
and the subscription.
|
|
47
50
|
- `biome.json`: Biome's lint and format settings ([Lint and format](#lint-and-format)).
|
|
48
51
|
|
|
49
52
|
## The schema first
|
|
@@ -72,6 +75,17 @@ tokens in `src/store.ts` are for development (`ada-token`): verify a JWT with
|
|
|
72
75
|
[`@alxia/jwt`](https://www.npmjs.com/package/@alxia/jwt)'s `bearer`, or look
|
|
73
76
|
a session up, in the same place.
|
|
74
77
|
|
|
78
|
+
## Batching (N+1)
|
|
79
|
+
|
|
80
|
+
`Note.author` runs once per note: with a database that is a query per note.
|
|
81
|
+
It reads `loaders.user.load(note.authorId)`, a
|
|
82
|
+
[DataLoader](https://github.com/graphql/dataloader) that collects the ids of
|
|
83
|
+
one request and calls `findUsers` in `src/store.ts` once for all of them
|
|
84
|
+
(`src/app.spec.ts` asserts one call for five notes). `createLoaders()` runs
|
|
85
|
+
for **each request**, in the `context` option: a loader caches what it loads,
|
|
86
|
+
so one shared between requests would keep stale data and hand one user's to
|
|
87
|
+
another. Add a loader for each field that loads a record by id.
|
|
88
|
+
|
|
75
89
|
## Subscriptions
|
|
76
90
|
|
|
77
91
|
`noteAdded` is served over server-sent events, Yoga's default: a request
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
2
|
import { app } from "./app";
|
|
3
|
-
import { db, pubsub } from "./store";
|
|
3
|
+
import { db, pubsub, queries } from "./store";
|
|
4
4
|
|
|
5
5
|
interface Result {
|
|
6
6
|
data?: Record<string, unknown>;
|
|
@@ -80,6 +80,33 @@ describe("mutations", () => {
|
|
|
80
80
|
});
|
|
81
81
|
});
|
|
82
82
|
|
|
83
|
+
describe("batching", () => {
|
|
84
|
+
test("the authors of N notes are loaded in one batch", async () => {
|
|
85
|
+
db.users.set("2", { id: "2", name: "Grace" });
|
|
86
|
+
db.notes.splice(0, db.notes.length);
|
|
87
|
+
for (let i = 1; i <= 5; i++) {
|
|
88
|
+
db.notes.push({
|
|
89
|
+
id: String(i),
|
|
90
|
+
text: `Note ${i}`,
|
|
91
|
+
authorId: String((i % 2) + 1),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
queries.users = 0;
|
|
95
|
+
const { data, errors } = await query("{ notes { text author { name } } }");
|
|
96
|
+
expect(errors).toBeUndefined();
|
|
97
|
+
expect(data?.["notes"]).toHaveLength(5);
|
|
98
|
+
expect(queries.users).toBe(1);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("each request gets its own loaders", async () => {
|
|
102
|
+
queries.users = 0;
|
|
103
|
+
await query("{ notes { author { name } } }");
|
|
104
|
+
await query("{ notes { author { name } } }");
|
|
105
|
+
// A cache shared between requests would answer the second without a call.
|
|
106
|
+
expect(queries.users).toBe(2);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
83
110
|
describe("subscriptions", () => {
|
|
84
111
|
test("noteAdded streams each note over server-sent events", async () => {
|
|
85
112
|
const response = await app.request("/graphql", {
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { health } from "@alxia/core";
|
|
2
2
|
import { graphql } from "@alxia/graphql";
|
|
3
3
|
import { base } from "./context";
|
|
4
|
+
import { createLoaders } from "./loaders";
|
|
4
5
|
import { schema } from "./schema";
|
|
5
6
|
|
|
6
7
|
// The probes (GET /health, GET /ready), then POST and GET /graphql, behind
|
|
7
8
|
// the base's middlewares. Subscriptions are served over server-sent events.
|
|
8
9
|
// The IDE (GraphiQL, on a browser's GET) follows alxia's dev switch: on
|
|
9
|
-
// under `bun dev` (NODE_ENV=development), off otherwise.
|
|
10
|
+
// under `bun dev` (NODE_ENV=development), off otherwise. `context` builds the
|
|
11
|
+
// loaders anew for each request, so a loader's cache is never shared.
|
|
10
12
|
export const app = base
|
|
11
13
|
.plugin(health())
|
|
12
|
-
.plugin((app) =>
|
|
14
|
+
.plugin((app) =>
|
|
15
|
+
graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }),
|
|
16
|
+
);
|
|
13
17
|
|
|
14
18
|
export type App = typeof app;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { alxia, defineMiddleware } from "@alxia/core";
|
|
2
2
|
import type { GraphQLContext } from "@alxia/graphql";
|
|
3
3
|
import { env } from "./env";
|
|
4
|
+
import type { Loaders } from "./loaders";
|
|
4
5
|
import { db } from "./store";
|
|
5
6
|
|
|
6
7
|
// Reads the bearer token: `viewer` is the user it names, or null. A query
|
|
@@ -19,6 +20,7 @@ const viewerOf = defineMiddleware(({ request }, next) => {
|
|
|
19
20
|
// The base: what every resolver reads, decorated or derived here.
|
|
20
21
|
export const base = alxia().decorate({ env, db }).use(viewerOf);
|
|
21
22
|
|
|
22
|
-
// A resolver's context: Yoga's,
|
|
23
|
-
//
|
|
24
|
-
|
|
23
|
+
// A resolver's context: Yoga's, the base's (`env`, `db`, `viewer`) and the
|
|
24
|
+
// per-request `loaders` that src/app.ts's `context` option builds. The
|
|
25
|
+
// generated `Resolvers` takes it (codegen.ts: `contextType`).
|
|
26
|
+
export type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import DataLoader from "dataloader";
|
|
2
|
+
import { findUsers } from "./store";
|
|
3
|
+
|
|
4
|
+
// The loaders of ONE request: `context` in src/app.ts calls this per request.
|
|
5
|
+
// A loader batches the `load` calls made in the same tick into one call of
|
|
6
|
+
// its function, and caches each key it has seen, so it must never outlive the
|
|
7
|
+
// request: a loader shared between requests would serve one user's data to
|
|
8
|
+
// another, and never see a change.
|
|
9
|
+
export function createLoaders() {
|
|
10
|
+
return { user: new DataLoader(findUsers) };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type Loaders = ReturnType<typeof createLoaders>;
|
|
@@ -33,10 +33,7 @@ export const resolvers: Resolvers = {
|
|
|
33
33
|
},
|
|
34
34
|
},
|
|
35
35
|
Note: {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (author === undefined) throw new Error(`No user ${note.authorId}`);
|
|
39
|
-
return author;
|
|
40
|
-
},
|
|
36
|
+
// The notes of one query load their authors in one batch (N+1 otherwise).
|
|
37
|
+
author: (note, _, { loaders }) => loaders.user.load(note.authorId),
|
|
41
38
|
},
|
|
42
39
|
};
|
|
@@ -23,3 +23,16 @@ export const db = {
|
|
|
23
23
|
// What a subscription streams: `addNote` publishes, `noteAdded` subscribes.
|
|
24
24
|
// One process only: across several, back it with a broker.
|
|
25
25
|
export const pubsub = createPubSub<{ noteAdded: [NoteRecord] }>();
|
|
26
|
+
|
|
27
|
+
// How many times the store was asked for users: a stand-in for a database's
|
|
28
|
+
// query log. `findUsers` is one query however many ids it is given.
|
|
29
|
+
export const queries = { users: 0 };
|
|
30
|
+
|
|
31
|
+
// The batch behind `loaders.user` (src/loaders.ts): one `WHERE id IN (...)` in
|
|
32
|
+
// a database. It answers each id in order, an Error for one that is missing.
|
|
33
|
+
export async function findUsers(
|
|
34
|
+
ids: readonly string[],
|
|
35
|
+
): Promise<(UserRecord | Error)[]> {
|
|
36
|
+
queries.users += 1;
|
|
37
|
+
return ids.map((id) => db.users.get(id) ?? new Error(`No user ${id}`));
|
|
38
|
+
}
|