@alxia/create 0.2.0 → 0.3.2

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 CHANGED
@@ -36,8 +36,8 @@ bun create @alxia my-site --template react-router
36
36
  | template | what it writes |
37
37
  | --- | --- |
38
38
  | `minimal` | the smallest alxia app: `src/index.ts` exports `app = alxia().get("/", …)` and listens on `PORT` only when it is the entry file, `src/index.spec.ts` calls it with `app.request()`; `bun dev` (`NODE_ENV=development bun --hot`), `build`, `start`, `typecheck`, a strict `tsconfig.json`, Biome and `verify` (`check:ci`, `typecheck`, then `test`), a `Dockerfile` running on `oven/bun:1-alpine`, `.dockerignore`, `.gitignore`, `.vscode/` and a README. One dependency, `@alxia/core`: no OpenAPI, no code generation, no validator, no env file |
39
- | `api` | an `@alxia/core` app with Zod, OpenAPI spec first: `openapi.yaml` declares `GET /todos`, `POST /todos` and `GET /todos/{id}`; `bun run generate` writes `src/generated/` from it with [`@nxgt/openapi-codegen`](https://www.npmjs.com/package/@nxgt/openapi-codegen) (`openapi-codegen.config.ts`), committed, so nothing is generated at install or build; `src/env.ts` reads `PORT`, `API_KEY` and `API_DOCS` with `defineEnv` from [`@alxia/env`](https://www.npmjs.com/package/@alxia/env), `API_KEY` a secret defaulting to `dev-key` under `NODE_ENV` `development` and `test` alone, required anywhere else; `src/context.ts` holds the base the routes read, `alxia({ errors: "problem" })` so alxia's own errors are RFC 9457 problems as `openapi.yaml` declares them, and registers it with `@alxia/core`'s `Register`; `src/routes/todos.ts`, made with `defineRoutes()`, reads that context with no import of the app and binds each operation with `route(operation, …middlewares, handler)`, as `route(operations.createTodo, requireKey, handler)`, where `requireKey`, made with `defineMiddleware`, answers 401 without an API key, and the operation's schemas validate the request and check the handler's reply; `src/app.ts` mounts `health()` (`GET /health`, `GET /ready`), `apiDocs` from `@alxia/openapi` (the API reference at `/docs`, from `openapi.yaml` imported into the bundle; on in development, else with `API_DOCS=true`) and the routes on the base; a `bun test` spec calling the app through the typed [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) client over the generated `paths.ts`, its `fetch` being `app.fetch` (in process, no server), keeping one `app.request()` test, and asserting `matchesSpec` from [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi): every operation has its route, and no route is outside the spec; `bun dev` (`NODE_ENV=development`) restarting on change, `typecheck`, `build`, a strict `tsconfig.json`, Biome (`biome.json`, `lint`, `format`, `check`, `check:ci`), `verify`, starting with `generate --check`, a `Dockerfile` running on `oven/bun:1-alpine`, `.dockerignore`, `.gitignore`, `.env.example`, `.vscode/` and a README. `@alxia/openapi` is a dependency; `openapi-fetch` and `@nxgt/openapi-codegen` are devDependencies |
40
- | `graphql` | a GraphQL API with [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server) through [`@alxia/graphql`](https://www.npmjs.com/package/@alxia/graphql), schema first: `schema.graphql` is the contract (`Query`, `Mutation`, `Subscription`); `bun run generate` writes `src/generated/resolvers.ts` from it with [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) (`codegen.ts`), committed, typing `Resolvers` with the app's context; `src/context.ts` holds the base and `viewerOf`, a middleware reading `Authorization: Bearer <token>` so every resolver reads a typed `viewer`; `src/resolvers.ts`; `src/schema.ts` and `src/app.ts` mounting `health()` and `graphql(app, { schema })`, GraphiQL on in dev alone; `src/env.ts` (`PORT`) with `defineEnv`; `src/store.ts`, in memory, with the pub/sub of the `noteAdded` subscription (server-sent events); a `bun test` spec posting to `/graphql` through `app.request()`; the same scripts, `Dockerfile`, Biome and `.vscode/` as `api`, `verify` starting with `generate --check`, and a `.env.example`. `@alxia/graphql`, `@alxia/env`, `graphql` and `graphql-yoga` are dependencies; the code generator is a devDependency |
39
+ | `api` | an `@alxia/core` app with Zod, OpenAPI spec first: `openapi.yaml` declares `GET /todos`, `POST /todos` and `GET /todos/{id}`; `bun run generate` writes `src/generated/` from it with [`@nxgt/openapi-codegen`](https://www.npmjs.com/package/@nxgt/openapi-codegen) (`openapi-codegen.config.ts`), committed, so nothing is generated at install or build; `src/env.ts` reads `PORT`, `API_KEY` and `API_DOCS` with `defineEnv` from [`@alxia/env`](https://www.npmjs.com/package/@alxia/env), `API_KEY` a secret defaulting to `dev-key` under `NODE_ENV` `development` and `test` alone, required anywhere else; `src/context.ts` holds the base the routes read, `alxia({ errors: "problem" })` so alxia's own errors are RFC 9457 problems as `openapi.yaml` declares them, and registers it with `@alxia/core`'s `Register`; `src/routes/todos.ts`, made with `defineRoutes()`, reads that context with no import of the app and binds each operation with `route(operation, …middlewares, handler)`, as `route(operations.createTodo, requireKey, handler)`, where `requireKey`, made with `defineMiddleware`, answers 401 without an API key, and the operation's schemas validate the request and check the handler's reply; `src/app.ts` mounts `health()` (`GET /health`, `GET /ready`), `apiDocs` from `@alxia/openapi` (the API reference at `/docs`, from `openapi.yaml` imported into the bundle; on in development, else with `API_DOCS=true`) and the routes on the base; a `bun test` spec calling the app through the typed [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) client over the generated `paths.ts`, its `fetch` being `app.fetch` (in process, no server), keeping one `app.request()` test, and asserting `matchesSpec` from [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi): every operation has its route, and `strict: true` also fails on a route outside the spec; `bun dev` (`NODE_ENV=development`) restarting on change, `typecheck`, `build`, a strict `tsconfig.json`, Biome (`biome.json`, `lint`, `format`, `check`, `check:ci`), `verify`, starting with `generate --check`, a `Dockerfile` running on `oven/bun:1-alpine`, `.dockerignore`, `.gitignore`, `.env.example`, `.vscode/` and a README. `@alxia/openapi` is a dependency; `openapi-fetch` and `@nxgt/openapi-codegen` are devDependencies |
40
+ | `graphql` | a GraphQL API with [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server) through [`@alxia/graphql`](https://www.npmjs.com/package/@alxia/graphql), schema first: `schema.graphql` is the contract (`Query`, `Mutation`, `Subscription`); `bun run generate` writes `src/generated/resolvers.ts` from it with [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) (`codegen.ts`), committed, typing `Resolvers` with the app's context; `src/context.ts` holds the base and `viewerOf`, a middleware reading `Authorization: Bearer <token>` so every resolver reads a typed `viewer`; `src/loaders.ts`, `createLoaders()`, the [DataLoader](https://github.com/graphql/dataloader)s of one request, built per request by the `context` option of `graphql()` in `src/app.ts` so `Note.author` loads the authors of a list of notes in one batch (`findUsers`) instead of one call per note; `src/resolvers.ts`; `src/schema.ts` and `src/app.ts` mounting `health()` and `graphql(app, { schema, context })`, GraphiQL on in dev alone; `src/env.ts` (`PORT`) with `defineEnv`; `src/store.ts`, in memory, with the pub/sub of the `noteAdded` subscription (server-sent events); a `bun test` spec posting to `/graphql` through `app.request()`; the same scripts, `Dockerfile`, Biome and `.vscode/` as `api`, `verify` starting with `generate --check`, and a `.env.example`. `@alxia/graphql`, `@alxia/env`, `dataloader`, `graphql` and `graphql-yoga` are dependencies; the code generator is a devDependency |
41
41
  | `react-router` | React Router's official template, as `create-react-router` writes it, shipped in this package and copied, with [`@alxia/react-router`](https://www.npmjs.com/package/@alxia/react-router) added as its README says: `alxia()` in `vite.config.ts`'s plugins, `dev` under `NODE_ENV=development`, `start` running `NODE_ENV=production bun build/server/index.js`, a `bunfig.toml` starting React Router's CLI on Bun, a `Dockerfile` running on `oven/bun:1-alpine` in place of React Router's Node one, and Biome as the `api` project has it, the scaffold formatted by it once. No server file: the default one serves the pages; `bunx alxia-react-router reveal` writes it out to customise |
42
42
 
43
43
  The heart of the `api` project, its middleware and a route bound to an
@@ -93,7 +93,7 @@ const viewerOf = defineMiddleware(({ request }, next) => {
93
93
  return next({ viewer: (id === undefined ? undefined : db.users.get(id)) ?? null });
94
94
  });
95
95
  export const base = alxia().decorate({ env, db }).use(viewerOf);
96
- export type Context = GraphQLContext<typeof base>;
96
+ export type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
97
97
 
98
98
  // src/resolvers.ts, in part: `Resolvers` is generated from the schema
99
99
  export const resolvers: Resolvers = {
@@ -107,6 +107,10 @@ export const resolvers: Resolvers = {
107
107
  // …
108
108
  },
109
109
  },
110
+ Note: {
111
+ // The notes of one query load their authors in one batch (N+1 otherwise).
112
+ author: (note, _, { loaders }) => loaders.user.load(note.authorId),
113
+ },
110
114
  };
111
115
  ```
112
116
 
package/docs/guide.md CHANGED
@@ -453,7 +453,7 @@ export type App = typeof app;
453
453
  `health()` answers `GET /health` (liveness) and `GET /ready` (readiness),
454
454
  and `apiDocs` serves a Scalar page at `/docs` with the document at
455
455
  `/docs/openapi.yaml` and `/docs/openapi.json`. `matchesSpec` leaves both
456
- out: no operation of `openapi.yaml` describes them. The document is public
456
+ out under `strict`: no operation of `openapi.yaml` describes them. The document is public
457
457
  wherever `/docs` is on.
458
458
 
459
459
  ```ts
@@ -503,7 +503,7 @@ const api = createClient<paths>({
503
503
  headers: { "x-api-key": env.API_KEY },
504
504
  });
505
505
 
506
- test("routes every operation of openapi.yaml, and nothing else", () => {
506
+ test("routes every operation of openapi.yaml", () => {
507
507
  matchesSpec(app, operations);
508
508
  });
509
509
 
@@ -518,7 +518,8 @@ test("creates a todo from JSON", async () => {
518
518
 
519
519
  `matchesSpec(app, operations)`, from
520
520
  [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi), throws
521
- when an operation has no route, or a route has no operation, naming each.
521
+ when an operation has no route, naming each; `strict: true` also throws on
522
+ a route with no operation.
522
523
  The spec also checks the 400, the 401 before the body and the 404 through
523
524
  the client, and keeps one test on `app.request()`: the client sends only
524
525
  what the spec allows, so a request it forbids (`/todos/first`) goes
@@ -651,10 +652,11 @@ my-graphql-api/
651
652
  │ ├── generated/resolvers.ts what `bun run generate` writes: committed, never edited
652
653
  │ ├── env.ts defineEnv: PORT
653
654
  │ ├── store.ts in-memory users, tokens and notes, and the pub/sub
655
+ │ ├── loaders.ts createLoaders(): the DataLoaders of one request
654
656
  │ ├── context.ts the base, the viewerOf middleware, and Context
655
657
  │ ├── resolvers.ts const resolvers: Resolvers
656
658
  │ ├── schema.ts createSchema from schema.graphql and the resolvers
657
- │ ├── app.ts health() and graphql(app, { schema }) mounted on the base
659
+ │ ├── app.ts health() and graphql(app, { schema, context }) mounted on the base
658
660
  │ ├── graphql.d.ts declares the *.graphql module
659
661
  │ ├── app.spec.ts bun test: POST /graphql through app.request()
660
662
  │ └── server.ts app.listen on env.PORT, which stops on SIGINT and SIGTERM
@@ -721,6 +723,7 @@ not resolvers, and Pothos is code first.
721
723
  import { alxia, defineMiddleware } from "@alxia/core";
722
724
  import type { GraphQLContext } from "@alxia/graphql";
723
725
  import { env } from "./env";
726
+ import type { Loaders } from "./loaders";
724
727
  import { db } from "./store";
725
728
 
726
729
  const viewerOf = defineMiddleware(({ request }, next) => {
@@ -734,13 +737,14 @@ const viewerOf = defineMiddleware(({ request }, next) => {
734
737
  });
735
738
 
736
739
  export const base = alxia().decorate({ env, db }).use(viewerOf);
737
- export type Context = GraphQLContext<typeof base>;
740
+ export type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
738
741
  ```
739
742
 
740
743
  `viewerOf` is a middleware given to `use`: it reads
741
744
  `Authorization: Bearer <token>` and passes `next({ viewer })`, the user or
742
745
  `null`. It never refuses, so a query may be anonymous (`me` is `null`), and
743
- `viewer` is typed in every resolver through `GraphQLContext<typeof base>`.
746
+ `viewer` is typed in every resolver through `GraphQLContext`, whose second
747
+ argument types the `loaders` the `context` option of `src/app.ts` adds.
744
748
  The tokens in `src/store.ts` are for development (`ada-token`): look a
745
749
  session up, or verify a JWT, in the same place.
746
750
 
@@ -761,6 +765,10 @@ export const resolvers: Resolvers = {
761
765
  // …
762
766
  },
763
767
  },
768
+ Note: {
769
+ // The notes of one query load their authors in one batch (N+1 otherwise).
770
+ author: (note, _, { loaders }) => loaders.user.load(note.authorId),
771
+ },
764
772
  };
765
773
  ```
766
774
 
@@ -768,12 +776,37 @@ A field the schema lacks, or a value its type refuses, is a compile error.
768
776
  `addNote` throws a `GraphQLError` with the code `UNAUTHENTICATED` when
769
777
  `viewer` is `null` ([troubleshooting](troubleshooting.md#sign-in-to-add-a-note)).
770
778
 
779
+ ### `src/loaders.ts`: one batch per request
780
+
781
+ ```ts
782
+ // src/loaders.ts
783
+ import DataLoader from "dataloader";
784
+ import { findUsers } from "./store";
785
+
786
+ export function createLoaders() {
787
+ return { user: new DataLoader(findUsers) };
788
+ }
789
+
790
+ export type Loaders = ReturnType<typeof createLoaders>;
791
+ ```
792
+
793
+ `Note.author` calls `loaders.user.load(note.authorId)`. A DataLoader
794
+ collects the `load` calls of one tick into one call of `findUsers` (in a
795
+ database, one `WHERE id IN (...)`), so a list of N notes loads its authors
796
+ in one batch, not N calls. It also caches each key it has seen, so loaders
797
+ are built per request, never shared: `src/app.ts` passes `context` to
798
+ `graphql()`, and a shared loader would serve one user's data to another and
799
+ never see a change. `dataloader` is a dependency of the project; the spec
800
+ asserts one batch for N notes and a fresh set of loaders per request.
801
+
771
802
  ### `src/app.ts` and the subscription
772
803
 
773
804
  ```ts
774
805
  export const app = base
775
806
  .plugin(health())
776
- .plugin((app) => graphql(app, { schema }));
807
+ .plugin((app) =>
808
+ graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }),
809
+ );
777
810
  ```
778
811
 
779
812
  `health()` answers `GET /health` and `GET /ready`. GraphiQL follows the
@@ -462,17 +462,17 @@ where you were, pin the previous version again, `0.7.0` after a move to `0.8.0`:
462
462
 
463
463
  ### `TypeError: matchesSpec(): 1 operation has no route: DELETE /todos/:id (deleteTodo)`
464
464
 
465
- With several, `2 operations have no route: …`; a route outside the spec
466
- reads `1 route has no operation: …`, after a `;` when both happen.
465
+ With several, `2 operations have no route: …`; under `matchesSpec(app, operations, { strict: true })`, a route outside
466
+ the spec reads `1 route has no operation: …`, after a `;` when both happen.
467
467
 
468
468
  **When:** `bun test`, in `src/app.spec.ts`, after an operation was added
469
469
  to `openapi.yaml` and `bun run generate` run, before `src/routes/todos.ts` routes
470
470
  it. The path is in alxia's form, `/todos/:id`, and the `operationId` is
471
471
  in parentheses.
472
472
 
473
- **Why:** `matchesSpec(app, operations)` checks both ways: every operation
474
- of `src/generated/alxia.ts` has a route of its method and path, and every
475
- route has an operation.
473
+ **Why:** `matchesSpec(app, operations)` checks that every operation
474
+ of `src/generated/alxia.ts` has a route of its method and path (and, under
475
+ `strict`, that every route has an operation).
476
476
 
477
477
  **Fix:** bind the operation in `src/routes/todos.ts`
478
478
  ([Adding an operation](guide.md#adding-an-operation)):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alxia/create",
3
- "version": "0.2.0",
3
+ "version": "0.3.2",
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.5.0",
44
+ "@alxia/core": "^0.6.0",
45
45
  "@alxia/env": "^0.2.0",
46
- "@alxia/graphql": "^0.3.0",
47
- "@alxia/openapi": "^0.5.0",
48
- "@alxia/react-router": "^0.6.0",
46
+ "@alxia/graphql": "^0.4.0",
47
+ "@alxia/openapi": "^0.6.0",
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",
@@ -42,7 +42,8 @@ operations generated from it, and a client is generated from the same file.
42
42
  its `fetch` being `app.fetch`: no server, no port), one `app.request()`
43
43
  test, and `matchesSpec` from
44
44
  [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi): every
45
- operation of `openapi.yaml` has its route, and no route is outside it.
45
+ operation of `openapi.yaml` has its route (`strict: true` also fails on a
46
+ route outside it).
46
47
  - `biome.json`: Biome's lint and format settings ([Lint and format](#lint-and-format)).
47
48
 
48
49
  ## The contract first
@@ -14,7 +14,7 @@ const api = createClient<paths>({
14
14
  headers: { "x-api-key": env.API_KEY },
15
15
  });
16
16
 
17
- test("routes every operation of openapi.yaml, and nothing else", () => {
17
+ test("routes every operation of openapi.yaml", () => {
18
18
  matchesSpec(app, operations);
19
19
  });
20
20
 
@@ -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, and the subscription.
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
@@ -19,6 +19,7 @@
19
19
  "@alxia/core": "workspace:^",
20
20
  "@alxia/env": "workspace:^",
21
21
  "@alxia/graphql": "workspace:^",
22
+ "dataloader": "^2.2.3",
22
23
  "graphql": "^16.11.0",
23
24
  "graphql-yoga": "^5.16.0",
24
25
  "zod": "^4.5.4"
@@ -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) => graphql(app, { schema }));
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, and the base's (`env`, `db`, `viewer`).
23
- // The generated `Resolvers` takes it (codegen.ts: `contextType`).
24
- export type Context = GraphQLContext<typeof base>;
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
- author: (note, _, { db }) => {
37
- const author = db.users.get(note.authorId);
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
+ }