@alxia/create 0.1.6 → 0.2.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 +80 -25
- package/dist/args.d.ts +3 -1
- package/dist/args.d.ts.map +1 -1
- package/dist/index.js +19 -9
- package/dist/index.js.map +7 -7
- package/dist/main.d.ts +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/registry.d.ts +2 -0
- package/dist/registry.d.ts.map +1 -1
- package/dist/versions.d.ts +5 -2
- package/dist/versions.d.ts.map +1 -1
- package/docs/README.md +16 -6
- package/docs/guide.md +438 -56
- package/docs/roadmap.md +24 -0
- package/docs/troubleshooting.md +146 -50
- package/package.json +16 -6
- package/templates/api/.env.example +9 -1
- package/templates/api/README.md +40 -12
- package/templates/api/openapi.yaml +13 -9
- package/templates/api/package.json +6 -4
- package/templates/api/src/app.spec.ts +42 -28
- package/templates/api/src/app.ts +13 -3
- package/templates/api/src/context.ts +3 -4
- package/templates/api/src/env.ts +20 -0
- package/templates/api/src/generated/alxia.ts +15 -5
- package/templates/api/src/generated/operations.ts +4 -4
- package/templates/api/src/generated/paths.ts +6 -6
- package/templates/api/src/generated/types.ts +14 -10
- package/templates/api/src/generated/zod.ts +6 -2
- package/templates/api/src/routes/todos.ts +2 -2
- package/templates/api/src/server.ts +8 -16
- package/templates/graphql/.dockerignore +6 -0
- package/templates/graphql/.env.example +3 -0
- package/templates/graphql/.vscode/extensions.json +3 -0
- package/templates/graphql/.vscode/settings.json +8 -0
- package/templates/graphql/Dockerfile +26 -0
- package/templates/graphql/README.md +171 -0
- package/templates/graphql/_biome.json +32 -0
- package/templates/graphql/codegen.ts +22 -0
- package/templates/graphql/gitignore +6 -0
- package/templates/graphql/package.json +34 -0
- package/templates/graphql/schema.graphql +26 -0
- package/templates/graphql/src/app.spec.ts +119 -0
- package/templates/graphql/src/app.ts +14 -0
- package/templates/graphql/src/context.ts +24 -0
- package/templates/graphql/src/env.ts +8 -0
- package/templates/graphql/src/generated/resolvers.ts +180 -0
- package/templates/graphql/src/graphql.d.ts +6 -0
- package/templates/graphql/src/resolvers.ts +42 -0
- package/templates/graphql/src/schema.ts +6 -0
- package/templates/graphql/src/server.ts +10 -0
- package/templates/graphql/src/store.ts +25 -0
- package/templates/graphql/tsconfig.json +25 -0
- package/templates/minimal/.dockerignore +6 -0
- package/templates/minimal/.vscode/extensions.json +3 -0
- package/templates/minimal/.vscode/settings.json +8 -0
- package/templates/minimal/Dockerfile +26 -0
- package/templates/minimal/README.md +107 -0
- package/templates/minimal/_biome.json +32 -0
- package/templates/minimal/gitignore +6 -0
- package/templates/minimal/package.json +25 -0
- package/templates/minimal/src/index.spec.ts +12 -0
- package/templates/minimal/src/index.ts +17 -0
- package/templates/minimal/tsconfig.json +25 -0
- package/templates/react-router/package.json +2 -2
|
@@ -1,65 +1,79 @@
|
|
|
1
1
|
import { expect, test } from "bun:test";
|
|
2
2
|
import { matchesSpec } from "@alxia/openapi";
|
|
3
|
+
import createClient from "openapi-fetch";
|
|
3
4
|
import { app } from "./app";
|
|
4
|
-
import {
|
|
5
|
+
import { env } from "./env";
|
|
5
6
|
import { operations } from "./generated/alxia";
|
|
7
|
+
import type { paths } from "./generated/paths";
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
// The client types every call from openapi.yaml (generated/paths.ts) and
|
|
10
|
+
// sends it to the app in-process: no server, no port.
|
|
11
|
+
const api = createClient<paths>({
|
|
12
|
+
baseUrl: "http://alxia.test",
|
|
13
|
+
fetch: (request) => app.fetch(request),
|
|
14
|
+
headers: { "x-api-key": env.API_KEY },
|
|
15
|
+
});
|
|
8
16
|
|
|
9
17
|
test("routes every operation of openapi.yaml, and nothing else", () => {
|
|
10
18
|
matchesSpec(app, operations);
|
|
11
19
|
});
|
|
12
20
|
|
|
13
21
|
test("creates a todo from JSON", async () => {
|
|
14
|
-
const response = await
|
|
15
|
-
|
|
16
|
-
headers: json,
|
|
17
|
-
body: JSON.stringify({ title: "Write a route" }),
|
|
22
|
+
const { data, response } = await api.POST("/todos", {
|
|
23
|
+
body: { title: "Write a route" },
|
|
18
24
|
});
|
|
19
25
|
expect(response.status).toBe(201);
|
|
20
|
-
expect(
|
|
26
|
+
expect(data).toEqual({
|
|
21
27
|
id: expect.any(Number),
|
|
22
28
|
title: "Write a route",
|
|
23
29
|
done: false,
|
|
24
30
|
});
|
|
25
31
|
});
|
|
26
32
|
|
|
27
|
-
test("refuses an empty title with a 400 naming it", async () => {
|
|
28
|
-
const response = await
|
|
29
|
-
|
|
30
|
-
headers: json,
|
|
31
|
-
body: JSON.stringify({ title: "" }),
|
|
33
|
+
test("refuses an empty title with a 400 problem naming it", async () => {
|
|
34
|
+
const { error, response } = await api.POST("/todos", {
|
|
35
|
+
body: { title: "" },
|
|
32
36
|
});
|
|
33
37
|
expect(response.status).toBe(400);
|
|
34
|
-
expect(
|
|
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"] }] });
|
|
35
41
|
});
|
|
36
42
|
|
|
37
43
|
test("asks for the key before it reads the body", async () => {
|
|
38
|
-
const response = await
|
|
39
|
-
|
|
40
|
-
headers: { "
|
|
41
|
-
body: JSON.stringify({ title: "" }),
|
|
44
|
+
const { error, response } = await api.POST("/todos", {
|
|
45
|
+
body: { title: "" },
|
|
46
|
+
headers: { "x-api-key": "wrong" },
|
|
42
47
|
});
|
|
43
48
|
expect(response.status).toBe(401); // requireKey stands before the validation
|
|
44
|
-
expect(
|
|
49
|
+
expect(error).toEqual({ error: "unauthorized" });
|
|
45
50
|
});
|
|
46
51
|
|
|
47
52
|
test("reads the id from the path as a number, as the spec types it", async () => {
|
|
48
|
-
const created = await
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
53
|
+
const created = await api.POST("/todos", { body: { title: "Find me" } });
|
|
54
|
+
const id = created.data?.id ?? 0;
|
|
55
|
+
const found = await api.GET("/todos/{id}", { params: { path: { id } } });
|
|
56
|
+
expect(found.data?.title).toBe("Find me");
|
|
57
|
+
const missing = await api.GET("/todos/{id}", {
|
|
58
|
+
params: { path: { id: 9999 } },
|
|
52
59
|
});
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
expect(found.status).toBe(200);
|
|
56
|
-
expect((await found.json()).title).toBe("Find me");
|
|
57
|
-
expect((await app.request("/todos/9999")).status).toBe(404);
|
|
60
|
+
expect(missing.response.status).toBe(404);
|
|
61
|
+
// `id: "first"` is a compile error here; app.request sends what it is told.
|
|
58
62
|
expect((await app.request("/todos/first")).status).toBe(400);
|
|
59
63
|
});
|
|
60
64
|
|
|
61
65
|
test("lists the todos", async () => {
|
|
66
|
+
const { data } = await api.GET("/todos");
|
|
67
|
+
expect(Array.isArray(data)).toBe(true);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("answers the liveness probe", async () => {
|
|
71
|
+
const response = await app.request("/health");
|
|
72
|
+
expect(response.status).toBe(200);
|
|
73
|
+
expect(await response.json()).toEqual({ status: "ok" });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("app.request is the same app, with a hand-written request", async () => {
|
|
62
77
|
const response = await app.request("/todos");
|
|
63
78
|
expect(response.status).toBe(200);
|
|
64
|
-
expect(Array.isArray(await response.json())).toBe(true);
|
|
65
79
|
});
|
package/templates/api/src/app.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
+
import { health } from "@alxia/core";
|
|
2
|
+
import { apiDocs } from "@alxia/openapi";
|
|
3
|
+
import spec from "../openapi.yaml";
|
|
1
4
|
import { base } from "./context";
|
|
5
|
+
import { env } from "./env";
|
|
2
6
|
import { todoRoutes } from "./routes/todos";
|
|
3
7
|
|
|
4
|
-
// The base, then the
|
|
5
|
-
//
|
|
6
|
-
|
|
8
|
+
// The base, then the probes (GET /health, GET /ready) before any guard,
|
|
9
|
+
// the API reference at /docs (on in development; API_DOCS=true elsewhere),
|
|
10
|
+
// and the route files: each requires the base's context, so mounting one
|
|
11
|
+
// before it is a compile error. openapi.yaml is imported, so `bun run build`
|
|
12
|
+
// puts it inside dist/server.js: the image needs no copy of it.
|
|
13
|
+
export const app = base
|
|
14
|
+
.plugin(health())
|
|
15
|
+
.plugin(apiDocs({ spec, enabled: env.API_DOCS }))
|
|
16
|
+
.plugin(todoRoutes);
|
|
7
17
|
|
|
8
18
|
export type App = typeof app;
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import { alxia } from "@alxia/core";
|
|
2
2
|
import type { Todo } from "./generated/types";
|
|
3
3
|
|
|
4
|
-
/** Set API_KEY in the environment: this default is for development. */
|
|
5
|
-
export const apiKey = Bun.env["API_KEY"] ?? "dev-key";
|
|
6
|
-
|
|
7
4
|
const todos: Todo[] = [];
|
|
8
5
|
|
|
9
6
|
// The base: what every route reads, decorated or derived here. It is
|
|
10
7
|
// registered below, so a route file reads it with no import of the app.
|
|
11
|
-
|
|
8
|
+
// alxia's own errors — a 400 the schemas refuse, a 404 no route matches, a
|
|
9
|
+
// 500 — are RFC 9457 problems, as openapi.yaml declares them.
|
|
10
|
+
export const base = alxia({ errors: "problem" }).decorate({ todos });
|
|
12
11
|
|
|
13
12
|
// Register the base, never the app: the app mounts the route files, whose
|
|
14
13
|
// type reads this, and would then be typed by itself.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { defineEnv } from "@alxia/env";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
// `bun dev` and `bun test` run in development and test; anything else,
|
|
5
|
+
// production included, is a deployment.
|
|
6
|
+
const local = ["development", "test"].includes(Bun.env.NODE_ENV ?? "");
|
|
7
|
+
|
|
8
|
+
// Checked once, when this module is first imported: a missing or malformed
|
|
9
|
+
// variable stops the process, with every issue, before it listens. Secrets
|
|
10
|
+
// print as `***`. API_KEY defaults to `dev-key` in development and test
|
|
11
|
+
// alone: deployed, it is required. API_DOCS serves the API reference at
|
|
12
|
+
// /docs: on in development, off unless set elsewhere.
|
|
13
|
+
export const env = defineEnv(
|
|
14
|
+
{
|
|
15
|
+
PORT: z.coerce.number().default(3000),
|
|
16
|
+
API_KEY: local ? z.string().min(1).default("dev-key") : z.string().min(1),
|
|
17
|
+
API_DOCS: z.stringbool().default(Bun.env.NODE_ENV === "development"),
|
|
18
|
+
},
|
|
19
|
+
{ secret: ["API_KEY"] },
|
|
20
|
+
);
|
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
// Generated by @nxgt/openapi-codegen from ../../openapi.yaml. Do not edit.
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Each operation as `@alxia/core`'s `app.route(operation, ...middlewares, handler)`
|
|
5
|
+
* takes it, @alxia/core 0.4 or later. The route validates the request and
|
|
6
|
+
* checks the handler's reply against `schema.response`, both just before
|
|
7
|
+
* the handler: `validate(operation)` or `responds(operation)` stands
|
|
8
|
+
* earlier among the middlewares when one is placed there.
|
|
9
|
+
* `matchesSpec(app, operations)`, from `@alxia/openapi`, fails while an
|
|
10
|
+
* operation has no route.
|
|
11
|
+
*/
|
|
12
|
+
|
|
3
13
|
import { z } from 'zod';
|
|
4
|
-
import { zNewTodo, zNotFound, zTodo, zUnauthorized,
|
|
14
|
+
import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationProblem } from './zod';
|
|
5
15
|
|
|
6
|
-
/** A number in a path, a query or a
|
|
16
|
+
/** A number in a path, a query, a header or a cookie: digits, where z.coerce.number() would read '' as 0. */
|
|
7
17
|
const numeric = z
|
|
8
18
|
.string()
|
|
9
19
|
.regex(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/)
|
|
@@ -29,7 +39,7 @@ export const createTodo = {
|
|
|
29
39
|
body: zNewTodo,
|
|
30
40
|
response: {
|
|
31
41
|
201: zTodo,
|
|
32
|
-
400:
|
|
42
|
+
400: zValidationProblem,
|
|
33
43
|
401: zUnauthorized,
|
|
34
44
|
},
|
|
35
45
|
detail: { operationId: 'createTodo', summary: 'Add a todo' },
|
|
@@ -46,14 +56,14 @@ export const getTodo = {
|
|
|
46
56
|
}),
|
|
47
57
|
response: {
|
|
48
58
|
200: zTodo,
|
|
49
|
-
400:
|
|
59
|
+
400: zValidationProblem,
|
|
50
60
|
404: zNotFound,
|
|
51
61
|
},
|
|
52
62
|
detail: { operationId: 'getTodo', summary: 'One todo' },
|
|
53
63
|
},
|
|
54
64
|
} as const;
|
|
55
65
|
|
|
56
|
-
/** Every operation alxia routes, by operationId: `app.route(operations.listTodos, handler)`. */
|
|
66
|
+
/** Every operation alxia routes, by operationId: `app.route(operations.listTodos, ...middlewares, handler)`. */
|
|
57
67
|
export const operations = {
|
|
58
68
|
listTodos,
|
|
59
69
|
createTodo,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated by @nxgt/openapi-codegen from ../../openapi.yaml. Do not edit.
|
|
2
2
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { zNewTodo, zNotFound, zTodo, zUnauthorized,
|
|
4
|
+
import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationProblem } from './zod';
|
|
5
5
|
import type { ClientOperations, Operations } from './types';
|
|
6
6
|
|
|
7
7
|
/** How a server reads a parameter, and how a client writes it. */
|
|
@@ -52,7 +52,7 @@ export interface OperationSpec<Client = unknown> {
|
|
|
52
52
|
/** A location with no parameters declared: whatever arrives there is dropped. */
|
|
53
53
|
const none = z.object({});
|
|
54
54
|
|
|
55
|
-
/** A number in a path, a query or a
|
|
55
|
+
/** A number in a path, a query, a header or a cookie: digits, where z.coerce.number() would read '' as 0. */
|
|
56
56
|
const numeric = z
|
|
57
57
|
.string()
|
|
58
58
|
.regex(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/)
|
|
@@ -100,7 +100,7 @@ export const operations: {
|
|
|
100
100
|
'application/json': { kind: 'json', schema: zTodo },
|
|
101
101
|
},
|
|
102
102
|
400: {
|
|
103
|
-
'application/json': { kind: 'json', schema:
|
|
103
|
+
'application/problem+json': { kind: 'json', schema: zValidationProblem },
|
|
104
104
|
},
|
|
105
105
|
401: {
|
|
106
106
|
'application/json': { kind: 'json', schema: zUnauthorized },
|
|
@@ -123,7 +123,7 @@ export const operations: {
|
|
|
123
123
|
'application/json': { kind: 'json', schema: zTodo },
|
|
124
124
|
},
|
|
125
125
|
400: {
|
|
126
|
-
'application/json': { kind: 'json', schema:
|
|
126
|
+
'application/problem+json': { kind: 'json', schema: zValidationProblem },
|
|
127
127
|
},
|
|
128
128
|
404: {
|
|
129
129
|
'application/json': { kind: 'json', schema: zNotFound },
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by @nxgt/openapi-codegen from ../../openapi.yaml. Do not edit.
|
|
2
2
|
|
|
3
|
-
import type { NewTodo, NotFound, Todo, Unauthorized,
|
|
3
|
+
import type { NewTodo, NotFound, Todo, Unauthorized, ValidationProblem } from './types';
|
|
4
4
|
|
|
5
5
|
export interface paths {
|
|
6
6
|
'/todos': {
|
|
@@ -50,7 +50,7 @@ export interface components {
|
|
|
50
50
|
NewTodo: NewTodo;
|
|
51
51
|
Unauthorized: Unauthorized;
|
|
52
52
|
NotFound: NotFound;
|
|
53
|
-
|
|
53
|
+
ValidationProblem: ValidationProblem;
|
|
54
54
|
};
|
|
55
55
|
responses: never;
|
|
56
56
|
parameters: never;
|
|
@@ -106,13 +106,13 @@ export interface operations {
|
|
|
106
106
|
'application/json': Todo;
|
|
107
107
|
};
|
|
108
108
|
};
|
|
109
|
-
/** alxia's own 400, for a request the schemas refuse */
|
|
109
|
+
/** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
|
|
110
110
|
400: {
|
|
111
111
|
headers: {
|
|
112
112
|
[name: string]: unknown;
|
|
113
113
|
};
|
|
114
114
|
content: {
|
|
115
|
-
'application/json':
|
|
115
|
+
'application/problem+json': ValidationProblem;
|
|
116
116
|
};
|
|
117
117
|
};
|
|
118
118
|
/** No x-api-key header, or not the key */
|
|
@@ -147,13 +147,13 @@ export interface operations {
|
|
|
147
147
|
'application/json': Todo;
|
|
148
148
|
};
|
|
149
149
|
};
|
|
150
|
-
/** alxia's own 400, for a request the schemas refuse */
|
|
150
|
+
/** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
|
|
151
151
|
400: {
|
|
152
152
|
headers: {
|
|
153
153
|
[name: string]: unknown;
|
|
154
154
|
};
|
|
155
155
|
content: {
|
|
156
|
-
'application/json':
|
|
156
|
+
'application/problem+json': ValidationProblem;
|
|
157
157
|
};
|
|
158
158
|
};
|
|
159
159
|
/** No todo has this id */
|
|
@@ -18,8 +18,12 @@ export interface NotFound {
|
|
|
18
18
|
error: 'not_found';
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export interface
|
|
22
|
-
|
|
21
|
+
export interface ValidationProblem {
|
|
22
|
+
type: string;
|
|
23
|
+
title: string;
|
|
24
|
+
status: number;
|
|
25
|
+
detail: string;
|
|
26
|
+
instance: string;
|
|
23
27
|
issues: {
|
|
24
28
|
target: 'params' | 'query' | 'headers' | 'cookies' | 'body';
|
|
25
29
|
path: (string | number)[];
|
|
@@ -62,9 +66,9 @@ export interface Operations {
|
|
|
62
66
|
201: {
|
|
63
67
|
'application/json': Todo;
|
|
64
68
|
};
|
|
65
|
-
/** alxia's own 400, for a request the schemas refuse */
|
|
69
|
+
/** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
|
|
66
70
|
400: {
|
|
67
|
-
'application/json':
|
|
71
|
+
'application/problem+json': ValidationProblem;
|
|
68
72
|
};
|
|
69
73
|
/** No x-api-key header, or not the key */
|
|
70
74
|
401: {
|
|
@@ -85,9 +89,9 @@ export interface Operations {
|
|
|
85
89
|
200: {
|
|
86
90
|
'application/json': Todo;
|
|
87
91
|
};
|
|
88
|
-
/** alxia's own 400, for a request the schemas refuse */
|
|
92
|
+
/** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
|
|
89
93
|
400: {
|
|
90
|
-
'application/json':
|
|
94
|
+
'application/problem+json': ValidationProblem;
|
|
91
95
|
};
|
|
92
96
|
/** No todo has this id */
|
|
93
97
|
404: {
|
|
@@ -116,11 +120,11 @@ export interface ClientOperations {
|
|
|
116
120
|
}];
|
|
117
121
|
reply:
|
|
118
122
|
| { status: 201; type: 'application/json'; data: Todo }
|
|
119
|
-
| { status: 400; type: 'application/json'; data:
|
|
123
|
+
| { status: 400; type: 'application/problem+json'; data: ValidationProblem }
|
|
120
124
|
| { status: 401; type: 'application/json'; data: Unauthorized };
|
|
121
125
|
wire:
|
|
122
126
|
| { status: 201; type: 'application/json'; data: Todo }
|
|
123
|
-
| { status: 400; type: 'application/json'; data:
|
|
127
|
+
| { status: 400; type: 'application/problem+json'; data: ValidationProblem }
|
|
124
128
|
| { status: 401; type: 'application/json'; data: Unauthorized };
|
|
125
129
|
};
|
|
126
130
|
/** One todo */
|
|
@@ -134,11 +138,11 @@ export interface ClientOperations {
|
|
|
134
138
|
}];
|
|
135
139
|
reply:
|
|
136
140
|
| { status: 200; type: 'application/json'; data: Todo }
|
|
137
|
-
| { status: 400; type: 'application/json'; data:
|
|
141
|
+
| { status: 400; type: 'application/problem+json'; data: ValidationProblem }
|
|
138
142
|
| { status: 404; type: 'application/json'; data: NotFound };
|
|
139
143
|
wire:
|
|
140
144
|
| { status: 200; type: 'application/json'; data: Todo }
|
|
141
|
-
| { status: 400; type: 'application/json'; data:
|
|
145
|
+
| { status: 400; type: 'application/problem+json'; data: ValidationProblem }
|
|
142
146
|
| { status: 404; type: 'application/json'; data: NotFound };
|
|
143
147
|
};
|
|
144
148
|
}
|
|
@@ -20,8 +20,12 @@ export const zNotFound = z.object({
|
|
|
20
20
|
error: z.literal('not_found'),
|
|
21
21
|
});
|
|
22
22
|
|
|
23
|
-
export const
|
|
24
|
-
|
|
23
|
+
export const zValidationProblem = z.object({
|
|
24
|
+
type: z.string(),
|
|
25
|
+
title: z.string(),
|
|
26
|
+
status: z.int(),
|
|
27
|
+
detail: z.string(),
|
|
28
|
+
instance: z.string(),
|
|
25
29
|
issues: z.array(z.object({
|
|
26
30
|
target: z.enum(['params', 'query', 'headers', 'cookies', 'body']),
|
|
27
31
|
path: z.array(z.union([z.string(), z.int()])),
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { defineMiddleware, defineRoutes } from "@alxia/core";
|
|
2
|
-
import {
|
|
2
|
+
import { env } from "../env";
|
|
3
3
|
import { operations } from "../generated/alxia";
|
|
4
4
|
|
|
5
5
|
// A middleware of the routes it is given to: it answers 401 without the key,
|
|
6
6
|
// before the body is read. openapi.yaml declares that 401.
|
|
7
7
|
const requireKey = defineMiddleware(({ request, reply }, next) =>
|
|
8
|
-
request.headers.get("x-api-key") ===
|
|
8
|
+
request.headers.get("x-api-key") === env.API_KEY
|
|
9
9
|
? next()
|
|
10
10
|
: reply(401, { error: "unauthorized" as const }),
|
|
11
11
|
);
|
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
import { app } from "./app";
|
|
2
|
+
import { env } from "./env";
|
|
2
3
|
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
console.error(error);
|
|
11
|
-
process.exit(1);
|
|
12
|
-
},
|
|
13
|
-
);
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const server = app.listen(Number(Bun.env["PORT"] ?? 3000));
|
|
18
|
-
console.log(`listening on ${server.url}`);
|
|
4
|
+
// In dev, the URL and the route table; in production, the URL alone. On
|
|
5
|
+
// SIGINT and SIGTERM, listen drains the requests in flight and exits.
|
|
6
|
+
app.listen({
|
|
7
|
+
port: env.PORT,
|
|
8
|
+
onListen: ({ dev, table, url }) =>
|
|
9
|
+
console.log(dev ? table : `listening on ${url}`),
|
|
10
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Bun bundles the app and its dependencies into dist/server.js, and the
|
|
2
|
+
# image holds dist/ alone: no node_modules, no src/. Pinned to Bun 1, the
|
|
3
|
+
# major alxia supports.
|
|
4
|
+
|
|
5
|
+
# Every dependency, then bun run build: dist/server.js and its source map.
|
|
6
|
+
FROM oven/bun:1 AS build
|
|
7
|
+
WORKDIR /app
|
|
8
|
+
COPY package.json bun.lock* bunfig.toml* ./
|
|
9
|
+
RUN bun install --frozen-lockfile
|
|
10
|
+
COPY . .
|
|
11
|
+
RUN bun run build
|
|
12
|
+
|
|
13
|
+
# The bundle, run as Bun's own non-root user with the start script's
|
|
14
|
+
# command, written out so that Bun is the container's process, and
|
|
15
|
+
# --no-install: with no node_modules, Bun would otherwise fetch a package
|
|
16
|
+
# the build left out from the registry at startup, where this fails. The
|
|
17
|
+
# server listens on PORT (3000). On Alpine, about 200 MB
|
|
18
|
+
# lighter: the bundle is JavaScript, which runs the same on musl. A native
|
|
19
|
+
# addon built for glibc alone needs oven/bun:1 here.
|
|
20
|
+
FROM oven/bun:1-alpine
|
|
21
|
+
WORKDIR /app
|
|
22
|
+
ENV NODE_ENV=production
|
|
23
|
+
COPY --from=build /app/dist ./dist
|
|
24
|
+
USER bun
|
|
25
|
+
EXPOSE 3000
|
|
26
|
+
CMD ["bun", "--no-install", "dist/server.js"]
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# An alxia GraphQL API
|
|
2
|
+
|
|
3
|
+
An [alxia](https://github.com/softistx/alxia) app serving GraphQL with
|
|
4
|
+
[GraphQL Yoga](https://the-guild.dev/graphql/yoga-server), made with
|
|
5
|
+
`bun create @alxia`. It is schema first: `schema.graphql` is the contract,
|
|
6
|
+
the resolvers are typed from it, and the endpoint is a route of the app,
|
|
7
|
+
behind its middlewares.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun dev # http://localhost:3000/graphql, GraphiQL in a browser
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
curl localhost:3000/graphql -H 'content-type: application/json' \
|
|
15
|
+
-d '{"query":"{ __typename }"}'
|
|
16
|
+
curl localhost:3000/graphql -H 'content-type: application/json' \
|
|
17
|
+
-H 'authorization: Bearer ada-token' \
|
|
18
|
+
-d '{"query":"mutation { addNote(text: \"Hello\") { id author { name } } }"}'
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- `schema.graphql`: the API's types, `Query`, `Mutation` and `Subscription`.
|
|
22
|
+
Change it first.
|
|
23
|
+
- `src/generated/resolvers.ts`: what `bun run generate` writes from it, with
|
|
24
|
+
[GraphQL Code Generator](https://the-guild.dev/graphql/codegen)
|
|
25
|
+
(`codegen.ts`): the schema's types and `Resolvers`, typed with the app's
|
|
26
|
+
context. Never edit it.
|
|
27
|
+
- `src/resolvers.ts`: the resolvers, `const resolvers: Resolvers`. A field the
|
|
28
|
+
schema lacks, or a value its type refuses, is a compile error, and each
|
|
29
|
+
resolver reads `viewer`, `db` and `env` from its context, typed.
|
|
30
|
+
- `src/context.ts`: the base app and its middleware. `viewerOf` reads
|
|
31
|
+
`Authorization: Bearer <token>` and gives every resolver `viewer`: the
|
|
32
|
+
user, or `null`. `Context` is `GraphQLContext<typeof base>`, which
|
|
33
|
+
`codegen.ts` hands to `Resolvers`.
|
|
34
|
+
- `src/schema.ts`, `src/app.ts`: `createSchema` from `schema.graphql` and the
|
|
35
|
+
resolvers, then `health()`'s probes (`GET /health`, `GET /ready`) and
|
|
36
|
+
`graphql(app, { schema })` mounted on the base.
|
|
37
|
+
- `src/env.ts`: `defineEnv` from
|
|
38
|
+
[`@alxia/env`](https://www.npmjs.com/package/@alxia/env): `PORT`, checked
|
|
39
|
+
once, when the module is first imported. A malformed one stops the
|
|
40
|
+
process with every issue, before it listens.
|
|
41
|
+
- `src/store.ts`: the in-memory users, tokens and notes, and the pub/sub the
|
|
42
|
+
subscription reads. Swap it for your database.
|
|
43
|
+
- `src/server.ts`: listens on `env.PORT`, 3000 by default, and shuts down
|
|
44
|
+
gracefully on `SIGINT` and `SIGTERM`, which `listen` handles.
|
|
45
|
+
- `src/app.spec.ts`: POST `/graphql` through `app.request()`, no port:
|
|
46
|
+
queries, the mutation with and without a token, and the subscription.
|
|
47
|
+
- `biome.json`: Biome's lint and format settings ([Lint and format](#lint-and-format)).
|
|
48
|
+
|
|
49
|
+
## The schema first
|
|
50
|
+
|
|
51
|
+
A new field starts in `schema.graphql`:
|
|
52
|
+
|
|
53
|
+
1. Add it: `notesBy(userId: ID!): [Note!]!` on `Query`, say.
|
|
54
|
+
2. `bun run generate`: `Resolvers` now has `notesBy`, with its arguments typed.
|
|
55
|
+
3. Write the resolver in `src/resolvers.ts`: `notesBy: (_, { userId }, { db }) => …`.
|
|
56
|
+
4. `bun test`: add a query to `src/app.spec.ts`.
|
|
57
|
+
|
|
58
|
+
`src/generated/` is committed, so the project builds with no generation step,
|
|
59
|
+
in Docker too. `bun run verify` runs `bun run generate --check` first: it
|
|
60
|
+
fails when `src/generated/` is not what `schema.graphql` gives. GraphQL Code
|
|
61
|
+
Generator's CLI and its two plugins are pinned exactly, since another release
|
|
62
|
+
may write the file differently: after moving them, run `bun run generate`.
|
|
63
|
+
|
|
64
|
+
## Authentication
|
|
65
|
+
|
|
66
|
+
`viewerOf` in `src/context.ts` is a middleware given to `use`: it reads the
|
|
67
|
+
bearer token and passes `next({ viewer })`, so the base's type has `viewer`,
|
|
68
|
+
and `GraphQLContext<typeof base>` gives it to every resolver. It refuses
|
|
69
|
+
nothing, so a query may be anonymous: `me` is `null`. `addNote` throws a
|
|
70
|
+
`GraphQLError` with the code `UNAUTHENTICATED` when `viewer` is `null`. The
|
|
71
|
+
tokens in `src/store.ts` are for development (`ada-token`): verify a JWT with
|
|
72
|
+
[`@alxia/jwt`](https://www.npmjs.com/package/@alxia/jwt)'s `bearer`, or look
|
|
73
|
+
a session up, in the same place.
|
|
74
|
+
|
|
75
|
+
## Subscriptions
|
|
76
|
+
|
|
77
|
+
`noteAdded` is served over server-sent events, Yoga's default: a request
|
|
78
|
+
with `Accept: text/event-stream` gets a result each time `addNote` publishes.
|
|
79
|
+
WebSockets are not served.
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
curl -N localhost:3000/graphql -H 'content-type: application/json' \
|
|
83
|
+
-H 'accept: text/event-stream' \
|
|
84
|
+
-d '{"query":"subscription { noteAdded { text author { name } } }"}'
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The pub/sub lives in one process: across several, back it with a broker, as
|
|
88
|
+
[Yoga's guide](https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions)
|
|
89
|
+
describes.
|
|
90
|
+
|
|
91
|
+
## Environment
|
|
92
|
+
|
|
93
|
+
Bun loads `.env` on every command, and `src/env.ts` checks what it finds. Copy
|
|
94
|
+
`.env.example` to `.env` to set `PORT`. GraphiQL follows alxia's dev
|
|
95
|
+
switch: on under `bun dev`, which sets `NODE_ENV=development`, off
|
|
96
|
+
otherwise — `bun start` and the image run with `NODE_ENV=production`.
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
cp .env.example .env
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Test
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
bun test # src/app.spec.ts: in process, no port
|
|
106
|
+
bun run typecheck
|
|
107
|
+
bun run generate # src/generated/, from schema.graphql
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Lint and format
|
|
111
|
+
|
|
112
|
+
[Biome](https://biomejs.dev) lints and formats the project, as `biome.json`
|
|
113
|
+
sets it: Biome's recommended rules, spaces, double quotes, imports
|
|
114
|
+
sorted. What the build writes, `dist/`, is skipped, and so is what
|
|
115
|
+
`bun run generate` writes, `src/generated/`.
|
|
116
|
+
|
|
117
|
+
```sh
|
|
118
|
+
bun run check # lint, format and sort imports, fixing what it can
|
|
119
|
+
bun run lint # lint only
|
|
120
|
+
bun run format # format only, in place
|
|
121
|
+
bun run check:ci # what CI runs: changes nothing, fails on an error
|
|
122
|
+
bun run verify # generate --check, check:ci, typecheck, then test
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`bun run check:ci`, not `bun ci`: `bun ci` is Bun's frozen-lockfile
|
|
126
|
+
install. In VS Code, `.vscode/` recommends Biome's extension and formats
|
|
127
|
+
on save with it.
|
|
128
|
+
|
|
129
|
+
`@biomejs/biome` is pinned exactly, since a release of Biome may format
|
|
130
|
+
differently. To move it:
|
|
131
|
+
|
|
132
|
+
```sh
|
|
133
|
+
bun add --dev --exact @biomejs/biome@latest
|
|
134
|
+
bunx biome migrate --write
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Build
|
|
138
|
+
|
|
139
|
+
`bun run build` bundles the server, its dependencies and `schema.graphql`
|
|
140
|
+
into one file, `dist/server.js`, minified, with its source map beside it, and
|
|
141
|
+
`bun start` runs it: what production and the image run.
|
|
142
|
+
|
|
143
|
+
```sh
|
|
144
|
+
bun run build # dist/server.js and dist/server.js.map
|
|
145
|
+
bun start # NODE_ENV=production bun dist/server.js
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`bun start` before any build fails with `Module not found
|
|
149
|
+
"dist/server.js"`: build first. `dist/` needs Bun and nothing else, no
|
|
150
|
+
`node_modules`. A dependency that cannot be bundled, a native addon, is left
|
|
151
|
+
out with `--external <name>` in the `build` script, and must then be
|
|
152
|
+
installed beside `dist/`.
|
|
153
|
+
|
|
154
|
+
## Docker
|
|
155
|
+
|
|
156
|
+
The `Dockerfile` builds in a stage of its own, on `oven/bun:1`, and runs
|
|
157
|
+
on `oven/bun:1-alpine`. The build stage installs every dependency with
|
|
158
|
+
`--frozen-lockfile`, from the `bun.lock` that `bun install` wrote (commit
|
|
159
|
+
it), and runs `bun run build`. The image holds `dist/` alone, no
|
|
160
|
+
`node_modules` and no `src/`, and runs `bun --no-install dist/server.js` as
|
|
161
|
+
its non-root `bun` user. `listen` drains the app and exits on `SIGTERM`,
|
|
162
|
+
so `docker stop` is immediate.
|
|
163
|
+
|
|
164
|
+
```sh
|
|
165
|
+
docker build -t my-graphql-api .
|
|
166
|
+
docker run --rm -p 3000:3000 my-graphql-api
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Next: [`@alxia/graphql`'s guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs):
|
|
170
|
+
Yoga's plugins, the IDE, the typed context. And
|
|
171
|
+
[`@alxia/core`'s](https://github.com/softistx/alxia/tree/develop/packages/core/docs).
|