@alxia/create 0.4.3 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/docs/README.md +1 -1
- package/docs/guide.md +25 -19
- package/docs/roadmap.md +14 -2
- package/docs/troubleshooting.md +63 -0
- package/package.json +3 -2
- package/templates/api/README.md +8 -3
- package/templates/api/package.json +2 -1
- package/templates/api/src/app.spec.ts +50 -32
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ 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`, `API_DOCS` and an optional `TRUSTED_PROXIES` (CIDR ranges, which adds `trustProxy({ trusted, untrusted: "refuse" })` to the base when set: `ctx.ip` from a trusted proxy's `X-Forwarded-For`, a forwarding header from any other connection refused, health probes untouched) 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, `src/proxy.spec.ts`, building the base behind `TRUSTED_PROXIES` and calling `app.fetch` with a peer, `src/env.spec.ts`, checking that a malformed `TRUSTED_PROXIES` stops the app, and a `bun test` spec calling the app through the typed [openapi-
|
|
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`, `API_DOCS` and an optional `TRUSTED_PROXIES` (CIDR ranges, which adds `trustProxy({ trusted, untrusted: "refuse" })` to the base when set: `ctx.ip` from a trusted proxy's `X-Forwarded-For`, a forwarding header from any other connection refused, health probes untouched) 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, `src/proxy.spec.ts`, building the base behind `TRUSTED_PROXIES` and calling `app.fetch` with a peer, `src/env.spec.ts`, checking that a malformed `TRUSTED_PROXIES` stops the app, and a `bun test` spec calling the app through the typed [`@nxgt/openapi-httpyz`](https://www.npmjs.com/package/@nxgt/openapi-httpyz) client over the generated `operations.ts`, its `fetch` being `app.fetch` (in process, no server; replies narrowed on their status), 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; `@nxgt/httpyz`, `@nxgt/openapi-httpyz` and `@nxgt/openapi-codegen` are devDependencies |
|
|
40
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` and the optional `TRUSTED_PROXIES`, as `api`) 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()`, `src/proxy.spec.ts`, the base behind `TRUSTED_PROXIES`, and `src/env.spec.ts`, a malformed one refused; 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
|
|
package/docs/README.md
CHANGED
|
@@ -10,7 +10,7 @@ errors the command and a new project print.
|
|
|
10
10
|
| Page | Read it when |
|
|
11
11
|
| --- | --- |
|
|
12
12
|
| [Guide](guide.md) | choosing a template, reading what it wrote, adding an operation to the `api` project's `openapi.yaml` or a field to the `graphql` project's `schema.graphql`, linting and formatting it with Biome, building its Docker image, pinning or moving versions, or running the command in a script or CI |
|
|
13
|
-
| [Troubleshooting](troubleshooting.md) | the command refused a directory, a template or an option, the registry did not answer or lacked a version, `bun install` failed, Biome refused to run in a project, or the `api` or `graphql` project's `generate --check`, an `api` `matchesSpec` or reply check, or a `graphql` schema import failed |
|
|
13
|
+
| [Troubleshooting](troubleshooting.md) | the command refused a directory, a template or an option, the registry did not answer or lacked a version, `bun install` failed, Biome refused to run in a project, or the `api` or `graphql` project's `generate --check`, an `api` `matchesSpec` or reply check, an `api` test's `ValidationError` or `UndeclaredStatusError`, or a `graphql` schema import failed |
|
|
14
14
|
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
15
15
|
|
|
16
16
|
## Recipes
|
package/docs/guide.md
CHANGED
|
@@ -263,7 +263,7 @@ openapi.yaml → src/generated: 5 written, 0 unchanged
|
|
|
263
263
|
| `alxia.ts` | one `as const` constant per operation, `{ method, path, schema }`, with the path in alxia's form (`/todos/:id`), the request's Zod schemas, a schema per response status and the `operationId`; and `operations`, all of them by `operationId` |
|
|
264
264
|
| `zod.ts` | a Zod schema per component schema: `zTodo`, `zNewTodo`, … |
|
|
265
265
|
| `types.ts` | a TypeScript type per component schema: `Todo`, `NewTodo`, … |
|
|
266
|
-
| `operations.ts`, `paths.ts` | the
|
|
266
|
+
| `operations.ts`, `paths.ts` | `operations.ts` is the table `@nxgt/openapi-httpyz` binds onto a client, which the template's spec uses; `paths.ts` is the same document in openapi-typescript's shape, for a client that reads it, and the template does not use it |
|
|
267
267
|
|
|
268
268
|
```ts
|
|
269
269
|
// src/generated/alxia.ts, in part
|
|
@@ -524,48 +524,54 @@ route(operation, ...middlewares, handler)
|
|
|
524
524
|
|
|
525
525
|
### `src/app.spec.ts`
|
|
526
526
|
|
|
527
|
-
The spec calls the app through
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
527
|
+
The spec calls the app through [`@nxgt/openapi-httpyz`](https://www.npmjs.com/package/@nxgt/openapi-httpyz),
|
|
528
|
+
bound to the generated `operations.ts` over an
|
|
529
|
+
[`@nxgt/httpyz`](https://www.npmjs.com/package/@nxgt/httpyz) client (both dev
|
|
530
|
+
dependencies), whose `fetch` is `app.fetch`: in process, no server, no port,
|
|
531
|
+
and every path, parameter, body and reply typed by `openapi.yaml`. A reply is
|
|
532
|
+
a union narrowed on its status. (Any OpenAPI client would work: the spec is
|
|
533
|
+
the contract. The generator still writes `paths.ts`, which nothing here uses.)
|
|
531
534
|
|
|
532
535
|
```ts
|
|
533
536
|
import { expect, test } from "bun:test";
|
|
534
537
|
import { matchesSpec } from "@alxia/openapi";
|
|
535
|
-
import
|
|
538
|
+
import { createHttpClient } from "@nxgt/httpyz";
|
|
539
|
+
import { createOpenApiClient } from "@nxgt/openapi-httpyz";
|
|
536
540
|
import { app } from "./app";
|
|
537
541
|
import { env } from "./env";
|
|
538
|
-
import { operations } from "./generated/alxia";
|
|
539
|
-
import
|
|
542
|
+
import { operations as routes } from "./generated/alxia";
|
|
543
|
+
import { operations } from "./generated/operations";
|
|
540
544
|
|
|
541
|
-
const
|
|
545
|
+
const http = createHttpClient({
|
|
542
546
|
baseUrl: "http://alxia.test",
|
|
543
547
|
fetch: (request) => app.fetch(request),
|
|
544
548
|
headers: { "x-api-key": env.API_KEY },
|
|
545
549
|
});
|
|
550
|
+
const api = createOpenApiClient(http, operations);
|
|
546
551
|
|
|
547
552
|
test("routes every operation of openapi.yaml", () => {
|
|
548
|
-
matchesSpec(app,
|
|
553
|
+
matchesSpec(app, routes);
|
|
549
554
|
});
|
|
550
555
|
|
|
551
556
|
test("creates a todo from JSON", async () => {
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
});
|
|
555
|
-
expect(response.status).toBe(201);
|
|
556
|
-
expect(data?.title).toBe("Write a route");
|
|
557
|
+
const reply = await api.op("createTodo", { json: { title: "Write a route" } });
|
|
558
|
+
expect(reply.status).toBe(201);
|
|
559
|
+
expect(reply.data).toMatchObject({ title: "Write a route" });
|
|
557
560
|
});
|
|
558
561
|
```
|
|
559
562
|
|
|
560
|
-
`matchesSpec(app,
|
|
563
|
+
`matchesSpec(app, routes)`, from
|
|
561
564
|
[`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi), throws
|
|
562
565
|
when an operation has no route, naming each; `strict: true` also throws on
|
|
563
566
|
a route with no operation.
|
|
564
567
|
The spec also checks the 400, the 401 before the body and the 404 through
|
|
565
|
-
the client, and keeps one test on `app.request()
|
|
566
|
-
|
|
567
|
-
|
|
568
|
+
the client, and keeps one test on `app.request()`. The client checks a
|
|
569
|
+
request against the spec before it sends it, so the 400 and the 401 tests
|
|
570
|
+
use a second client built with `validate: { request: false }`, and a request
|
|
571
|
+
the types forbid (`/todos/first`) goes through `app.request`. See
|
|
568
572
|
[Testing with the generated client](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/testing.md).
|
|
573
|
+
A test that throws `ValidationError` or `UndeclaredStatusError` is in
|
|
574
|
+
[troubleshooting](troubleshooting.md#validationerror-createtodo-post-todos-too-small-expected-string-to-have-1-characters) ([the other](troubleshooting.md#undeclaredstatuserror-gettodo-get-todosid-no-418-reply-is-declared)).
|
|
569
575
|
|
|
570
576
|
### Adding an operation
|
|
571
577
|
|
package/docs/roadmap.md
CHANGED
|
@@ -39,6 +39,17 @@ Nothing scheduled yet.
|
|
|
39
39
|
|
|
40
40
|
## Shipped
|
|
41
41
|
|
|
42
|
+
### 0.5.1
|
|
43
|
+
|
|
44
|
+
- **The `api` template's client errors, documented and held in step.**
|
|
45
|
+
[Troubleshooting](troubleshooting.md#validationerror-createtodo-post-todos-too-small-expected-string-to-have-1-characters)
|
|
46
|
+
names the two errors a new project's tests can meet through the typed
|
|
47
|
+
client, `ValidationError` (a request the spec refuses never leaves the
|
|
48
|
+
test: use a second client with `validate: { request: false }`) and
|
|
49
|
+
`UndeclaredStatusError` (the app answered a status the spec does not
|
|
50
|
+
declare), and a spec of `@alxia/create` fails when the template's
|
|
51
|
+
`@nxgt/httpyz` and `@nxgt/openapi-httpyz` ranges differ from its own.
|
|
52
|
+
|
|
42
53
|
### 0.4.1
|
|
43
54
|
|
|
44
55
|
- **`graphqlClient` in the `graphql` template.** Its spec calls the app through `graphqlClient` from `@alxia/graphql/testing`, in place of a helper of its own.
|
|
@@ -75,8 +86,9 @@ Nothing scheduled yet.
|
|
|
75
86
|
`openapi.yaml`; no template installs signal handlers of its own, as
|
|
76
87
|
`listen` drains and exits on `SIGINT` and `SIGTERM`.
|
|
77
88
|
- **The `api` template's tests use a typed client.** `src/app.spec.ts` calls
|
|
78
|
-
the app through
|
|
79
|
-
|
|
89
|
+
the app through a client typed by the generated spec, with `app.fetch`
|
|
90
|
+
as its `fetch`: in process, typed by `openapi.yaml` (today
|
|
91
|
+
`@nxgt/openapi-httpyz` over `operations.ts`).
|
|
80
92
|
|
|
81
93
|
### 0.1.6
|
|
82
94
|
|
package/docs/troubleshooting.md
CHANGED
|
@@ -47,6 +47,8 @@ print, or — for a trap that prints nothing — the symptom.
|
|
|
47
47
|
- [`src/generated/` changes after moving `@nxgt/openapi-codegen`](#srcgenerated-changes-after-moving-nxgtopenapi-codegen)
|
|
48
48
|
- [`TypeError: matchesSpec(): 1 operation has no route: DELETE /todos/:id (deleteTodo)`](#typeerror-matchesspec-1-operation-has-no-route-delete-todosid-deletetodo)
|
|
49
49
|
- [`ResponseValidationError: POST /todos: the 201 reply does not match its schema`](#responsevalidationerror-post-todos-the-201-reply-does-not-match-its-schema)
|
|
50
|
+
- [`ValidationError: createTodo (POST /todos): Too small: expected string to have >=1 characters`](#validationerror-createtodo-post-todos-too-small-expected-string-to-have-1-characters)
|
|
51
|
+
- [`UndeclaredStatusError: getTodo (GET /todos/{id}): no 418 reply is declared`](#undeclaredstatuserror-gettodo-get-todosid-no-418-reply-is-declared)
|
|
50
52
|
|
|
51
53
|
**The `graphql` project's schema**
|
|
52
54
|
|
|
@@ -523,6 +525,67 @@ reply.created({ id: todo.id, title: todo.title, done: todo.done }) // Todo: { id
|
|
|
523
525
|
The other forms of the error, and how to turn the check off, are in
|
|
524
526
|
[`@alxia/core`'s troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/core/docs/troubleshooting.md#responsevalidationerror--the-200-reply-does-not-match-its-schema).
|
|
525
527
|
|
|
528
|
+
### `ValidationError: createTodo (POST /todos): Too small: expected string to have >=1 characters`
|
|
529
|
+
|
|
530
|
+
A test of the app's own 400 or 401 throws in the test, before any request
|
|
531
|
+
reaches the app:
|
|
532
|
+
|
|
533
|
+
```text
|
|
534
|
+
ValidationError: createTodo (POST /todos): Too small: expected string to have >=1 characters
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
The operation, method and path are the call's, and the text after the colon is
|
|
538
|
+
the first issue's message (several are joined with `; `). The same class
|
|
539
|
+
also throws for a reply the spec does not describe (a body that is not valid
|
|
540
|
+
JSON, a value its schema refuses), whose `failure.kind` is `'response'`;
|
|
541
|
+
`'request'` is the one here.
|
|
542
|
+
|
|
543
|
+
**When:** the test sends what `openapi.yaml` refuses (an empty `title`, a
|
|
544
|
+
missing key) to see the app answer 400 or 401.
|
|
545
|
+
|
|
546
|
+
**Why:** the client checks every request against the spec before it sends
|
|
547
|
+
it, by default, and throws what the server would refuse. Nothing was sent.
|
|
548
|
+
|
|
549
|
+
**Fix:** build a second client that does not check requests, and use it for
|
|
550
|
+
the tests of a refusal. Keep the first one for the calls that must pass:
|
|
551
|
+
|
|
552
|
+
```ts
|
|
553
|
+
const api = createOpenApiClient(http, operations);
|
|
554
|
+
const raw = createOpenApiClient(http, operations, {
|
|
555
|
+
validate: { request: false },
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
const reply = await raw.op("createTodo", { json: { title: "" } });
|
|
559
|
+
expect(reply.status).toBe(400);
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
A request the types forbid (`/todos/first`) goes through `app.request()`.
|
|
563
|
+
See [Testing with the generated client](https://github.com/softistx/alxia/blob/develop/packages/openapi/docs/guide/testing.md#keep-one-apprequest-test).
|
|
564
|
+
|
|
565
|
+
### `UndeclaredStatusError: getTodo (GET /todos/{id}): no 418 reply is declared`
|
|
566
|
+
|
|
567
|
+
A test through the client throws, naming the status the app answered:
|
|
568
|
+
|
|
569
|
+
```text
|
|
570
|
+
UndeclaredStatusError: getTodo (GET /todos/{id}): no 418 reply is declared
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
The error's `status` is the status and its `response` the unread `Response`,
|
|
574
|
+
so a test can read the body to see what the app sent.
|
|
575
|
+
|
|
576
|
+
**When:** the app answers a status `openapi.yaml` does not declare for that
|
|
577
|
+
operation: a 500 from a handler that threw, a 404 or 403 the spec never
|
|
578
|
+
mentioned, a status a middleware sent.
|
|
579
|
+
|
|
580
|
+
**Why:** the client reads a reply by the statuses the operation declares, so
|
|
581
|
+
a client generated from the spec never returns a body it was not told about.
|
|
582
|
+
|
|
583
|
+
**Fix:** if the status is right, declare it under the operation's
|
|
584
|
+
`responses` in `openapi.yaml`, then `bun run generate`; if the app should not
|
|
585
|
+
send it, fix the route (a 500 is usually the handler's bug, so read
|
|
586
|
+
`error.response`). A test of a status the spec leaves out on purpose goes through
|
|
587
|
+
`app.request()`, which reads whatever comes back.
|
|
588
|
+
|
|
526
589
|
## The `graphql` project's schema
|
|
527
590
|
|
|
528
591
|
### `The following stale files were detected: src/generated/resolvers.ts`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/create",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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",
|
|
@@ -49,12 +49,13 @@
|
|
|
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
|
+
"@nxgt/httpyz": "^0.3.3",
|
|
52
53
|
"@nxgt/openapi-codegen": "0.7.0",
|
|
54
|
+
"@nxgt/openapi-httpyz": "^0.3.1",
|
|
53
55
|
"@types/bun": "^1.4.2",
|
|
54
56
|
"dataloader": "^2.2.3",
|
|
55
57
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
56
58
|
"graphql-yoga": "^5.16.0",
|
|
57
|
-
"openapi-fetch": "^0.17.0",
|
|
58
59
|
"zod": "^4.6.5"
|
|
59
60
|
}
|
|
60
61
|
}
|
package/templates/api/README.md
CHANGED
|
@@ -38,9 +38,9 @@ operations generated from it, and a client is generated from the same file.
|
|
|
38
38
|
`***`.
|
|
39
39
|
- `src/server.ts`: listens on `env.PORT`, 3000 by default, and shuts down
|
|
40
40
|
gracefully on `SIGINT` and `SIGTERM`, which `listen` handles.
|
|
41
|
-
- `src/app.spec.ts`: a typed client (openapi-
|
|
42
|
-
its `fetch` being `app.fetch`: no server, no
|
|
43
|
-
test, and `matchesSpec` from
|
|
41
|
+
- `src/app.spec.ts`: a typed client (`@nxgt/openapi-httpyz` over
|
|
42
|
+
`generated/operations.ts`, its `fetch` being `app.fetch`: no server, no
|
|
43
|
+
port; each reply narrowed on its status), one `app.request()` test, and `matchesSpec` from
|
|
44
44
|
[`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi): every
|
|
45
45
|
operation of `openapi.yaml` has its route (`strict: true` also fails on a
|
|
46
46
|
route outside it).
|
|
@@ -139,6 +139,11 @@ bun run typecheck
|
|
|
139
139
|
bun run generate # src/generated/, from openapi.yaml
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
+
A test that throws `ValidationError` (the client refused a request the spec
|
|
143
|
+
forbids before sending it) or `UndeclaredStatusError` (the app answered a
|
|
144
|
+
status `openapi.yaml` does not declare) is in
|
|
145
|
+
[troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/create/docs/troubleshooting.md#validationerror-createtodo-post-todos-too-small-expected-string-to-have-1-characters).
|
|
146
|
+
|
|
142
147
|
## Lint and format
|
|
143
148
|
|
|
144
149
|
[Biome](https://biomejs.dev) lints and formats the project, as `biome.json`
|
|
@@ -23,9 +23,10 @@
|
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
25
|
"@biomejs/biome": "2.5.15",
|
|
26
|
+
"@nxgt/httpyz": "^0.3.3",
|
|
26
27
|
"@nxgt/openapi-codegen": "0.7.0",
|
|
28
|
+
"@nxgt/openapi-httpyz": "^0.3.1",
|
|
27
29
|
"@types/bun": "^1.4.2",
|
|
28
|
-
"openapi-fetch": "^0.17.0",
|
|
29
30
|
"typescript": "^6.0.3"
|
|
30
31
|
}
|
|
31
32
|
}
|
|
@@ -1,29 +1,38 @@
|
|
|
1
1
|
import { expect, test } from "bun:test";
|
|
2
2
|
import { matchesSpec } from "@alxia/openapi";
|
|
3
|
-
import
|
|
3
|
+
import { createHttpClient } from "@nxgt/httpyz";
|
|
4
|
+
import { createOpenApiClient } from "@nxgt/openapi-httpyz";
|
|
4
5
|
import { app } from "./app";
|
|
5
6
|
import { env } from "./env";
|
|
6
|
-
import { operations } from "./generated/alxia";
|
|
7
|
-
import
|
|
7
|
+
import { operations as routes } from "./generated/alxia";
|
|
8
|
+
import { operations } from "./generated/operations";
|
|
8
9
|
|
|
9
|
-
// The client types every call from openapi.yaml (generated
|
|
10
|
-
// sends it to the app in-process: no server, no port.
|
|
11
|
-
|
|
10
|
+
// The client types every call from openapi.yaml (the generated operations
|
|
11
|
+
// table) and sends it to the app in-process: no server, no port. A reply is a
|
|
12
|
+
// union narrowed on its status; a status the spec does not declare throws.
|
|
13
|
+
const http = createHttpClient({
|
|
12
14
|
baseUrl: "http://alxia.test",
|
|
13
15
|
fetch: (request) => app.fetch(request),
|
|
14
16
|
headers: { "x-api-key": env.API_KEY },
|
|
15
17
|
});
|
|
18
|
+
const api = createOpenApiClient(http, operations);
|
|
19
|
+
|
|
20
|
+
// The client checks a request against the spec before it sends it. The tests
|
|
21
|
+
// that send what the spec refuses turn that off, to see the server refuse it.
|
|
22
|
+
const raw = createOpenApiClient(http, operations, {
|
|
23
|
+
validate: { request: false },
|
|
24
|
+
});
|
|
16
25
|
|
|
17
26
|
test("routes every operation of openapi.yaml", () => {
|
|
18
|
-
matchesSpec(app,
|
|
27
|
+
matchesSpec(app, routes);
|
|
19
28
|
});
|
|
20
29
|
|
|
21
30
|
test("creates a todo from JSON", async () => {
|
|
22
|
-
const
|
|
23
|
-
|
|
31
|
+
const reply = await api.op("createTodo", {
|
|
32
|
+
json: { title: "Write a route" },
|
|
24
33
|
});
|
|
25
|
-
expect(
|
|
26
|
-
expect(data).toEqual({
|
|
34
|
+
expect(reply.status).toBe(201);
|
|
35
|
+
expect(reply.data).toEqual({
|
|
27
36
|
id: expect.any(Number),
|
|
28
37
|
title: "Write a route",
|
|
29
38
|
done: false,
|
|
@@ -31,40 +40,49 @@ test("creates a todo from JSON", async () => {
|
|
|
31
40
|
});
|
|
32
41
|
|
|
33
42
|
test("refuses an empty title with a 400 problem naming it", async () => {
|
|
34
|
-
const
|
|
35
|
-
|
|
43
|
+
const reply = await raw.op("createTodo", { json: { title: "" } });
|
|
44
|
+
expect(reply.status).toBe(400);
|
|
45
|
+
expect(reply.response.headers.get("content-type")).toBe(
|
|
46
|
+
"application/problem+json",
|
|
47
|
+
);
|
|
48
|
+
// reply.data is the 201, 400 or 401 body until the status is checked
|
|
49
|
+
if (reply.status !== 400)
|
|
50
|
+
throw new Error(`expected a 400, got ${reply.status}`);
|
|
51
|
+
expect(reply.data).toMatchObject({
|
|
52
|
+
status: 400,
|
|
53
|
+
issues: [{ path: ["title"] }],
|
|
36
54
|
});
|
|
37
|
-
expect(response.status).toBe(400);
|
|
38
|
-
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
|
39
|
-
// error is the 400 or the 401 body: a match, not a property read
|
|
40
|
-
expect(error).toMatchObject({ status: 400, issues: [{ path: ["title"] }] });
|
|
41
55
|
});
|
|
42
56
|
|
|
43
57
|
test("asks for the key before it reads the body", async () => {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
expect(
|
|
58
|
+
const reply = await raw.op(
|
|
59
|
+
"createTodo",
|
|
60
|
+
{ json: { title: "" } },
|
|
61
|
+
{ headers: { "x-api-key": "wrong" } },
|
|
62
|
+
);
|
|
63
|
+
expect(reply.status).toBe(401); // requireKey stands before the validation
|
|
64
|
+
expect(reply.data).toEqual({ error: "unauthorized" });
|
|
50
65
|
});
|
|
51
66
|
|
|
52
67
|
test("reads the id from the path as a number, as the spec types it", async () => {
|
|
53
|
-
const created = await api.
|
|
54
|
-
|
|
55
|
-
const found = await api.
|
|
56
|
-
|
|
57
|
-
const missing = await api.GET("/todos/{id}", {
|
|
58
|
-
params: { path: { id: 9999 } },
|
|
68
|
+
const created = await api.op("createTodo", { json: { title: "Find me" } });
|
|
69
|
+
if (created.status !== 201) throw new Error("the todo was not created");
|
|
70
|
+
const found = await api.get("/todos/{id}", {
|
|
71
|
+
param: { id: created.data.id },
|
|
59
72
|
});
|
|
60
|
-
|
|
73
|
+
if (found.status !== 200) throw new Error("the todo was not found");
|
|
74
|
+
expect(found.data.title).toBe("Find me");
|
|
75
|
+
const missing = await api.get("/todos/{id}", { param: { id: 9999 } });
|
|
76
|
+
expect(missing.status).toBe(404);
|
|
77
|
+
expect(missing.data).toEqual({ error: "not_found" });
|
|
61
78
|
// `id: "first"` is a compile error here; app.request sends what it is told.
|
|
62
79
|
expect((await app.request("/todos/first")).status).toBe(400);
|
|
63
80
|
});
|
|
64
81
|
|
|
65
82
|
test("lists the todos", async () => {
|
|
66
|
-
const
|
|
67
|
-
|
|
83
|
+
const reply = await api.get("/todos");
|
|
84
|
+
if (reply.status !== 200) throw new Error(`got a ${reply.status}`);
|
|
85
|
+
expect(Array.isArray(reply.data)).toBe(true);
|
|
68
86
|
});
|
|
69
87
|
|
|
70
88
|
test("answers the liveness probe", async () => {
|