@afora/fastify 0.0.0-stage → 0.0.11
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 +148 -2
- package/dist/index.d.ts +55 -0
- package/dist/index.js +106 -0
- package/package.json +58 -5
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @afora/fastify
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [Fastify](https://fastify.dev) sink for [`@afora/core`](../../README.md) outputs. It turns the operations of an output into a Fastify instance: the route each use case declares, validated input (from the body, the query, the path, headers and cookies), the access each use case declares, the response with its status (sensitive values masked), RFC 9457 `application/problem+json` errors, and an OpenAPI document of the same routes.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun add @afora/core @afora/fastify fastify typebox
|
|
7
|
+
# or: npm install @afora/core @afora/fastify fastify typebox
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
`@afora/core`, `fastify` (`^5.12.8`) and TypeBox (`^1`) are peer dependencies. It runs wherever Fastify does: Node >= 22 and Bun.
|
|
11
|
+
|
|
12
|
+
## Example
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import {
|
|
16
|
+
blueprintOf,
|
|
17
|
+
commandOf,
|
|
18
|
+
entityOf,
|
|
19
|
+
outputOf,
|
|
20
|
+
RepositoryEntityNotFound,
|
|
21
|
+
repositoryOf,
|
|
22
|
+
Route,
|
|
23
|
+
useCaseOf,
|
|
24
|
+
} from "@afora/core";
|
|
25
|
+
import { fastify } from "@afora/fastify";
|
|
26
|
+
|
|
27
|
+
class Post extends entityOf(
|
|
28
|
+
blueprintOf((ctx) => ({ title: ctx.text, slug: ctx.slug })),
|
|
29
|
+
) {}
|
|
30
|
+
const Posts = repositoryOf({ entity: Post, actions: ["findBySlug", "create"] });
|
|
31
|
+
|
|
32
|
+
@Route("GET", "/posts/{slug}")
|
|
33
|
+
class GetPost extends useCaseOf({
|
|
34
|
+
name: "GetPost",
|
|
35
|
+
blueprint: blueprintOf((ctx) => ({ slug: ctx.slug })),
|
|
36
|
+
response: blueprintOf(() => ({ post: Post })),
|
|
37
|
+
dependencies: { posts: Posts },
|
|
38
|
+
}) {
|
|
39
|
+
override async execute() {
|
|
40
|
+
const post = await this.dependencies.posts.findBySlug(this.input.slug);
|
|
41
|
+
if (!post) {
|
|
42
|
+
throw new RepositoryEntityNotFound({
|
|
43
|
+
source: "GetPost",
|
|
44
|
+
details: { id: this.input.slug },
|
|
45
|
+
}); // a 404
|
|
46
|
+
}
|
|
47
|
+
return { post };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const Blog = commandOf({ name: "Blog", useCases: { getPost: GetPost } });
|
|
52
|
+
|
|
53
|
+
const Api = outputOf({
|
|
54
|
+
name: "Api",
|
|
55
|
+
commands: [Blog],
|
|
56
|
+
pipe: [
|
|
57
|
+
fastify({
|
|
58
|
+
basePath: "/api",
|
|
59
|
+
docs: {
|
|
60
|
+
path: "/openapi.json",
|
|
61
|
+
info: { title: "Blog", version: "1.0.0" },
|
|
62
|
+
},
|
|
63
|
+
}),
|
|
64
|
+
],
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const app = Api.build(); // a FastifyInstance
|
|
68
|
+
await app.listen({ port: 3000 });
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
GET /api/posts/hello -> 200 { "post": { "slug": "hello", ... } }
|
|
73
|
+
GET /api/posts/Not%20A%20Slug -> 400 application/problem+json, with "issues"
|
|
74
|
+
GET /openapi.json -> the OpenAPI 3.1 document of the same routes
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Options
|
|
78
|
+
|
|
79
|
+
All options are JSON, so the stage can live in an `afora.json` (`{ "sink": "fastify", "options": { ... } }`). They are the options of every afora sink that serves HTTP, so moving an output from one server to another changes one import.
|
|
80
|
+
|
|
81
|
+
| Option | Meaning |
|
|
82
|
+
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
83
|
+
| `basePath` | Prefix of every route, e.g. `"/api"`. |
|
|
84
|
+
| `route` | `{ [operationId]: { method?, path?, status? } }`: overrides the route a use case declares, or the default `POST /{command}/{operation}`. |
|
|
85
|
+
| `responses` | `{ [operationId]: { headers: { name: value } } }`: static headers of the success responses, such as `cache-control`. |
|
|
86
|
+
| `requestId` | `true` (`x-request-id`) or a header name: every response of the sink carries the request's id, or a new one. |
|
|
87
|
+
| `security` | `{ schemes, operations?, default? }`: the security schemes of the OpenAPI document. |
|
|
88
|
+
| `docs` | `{ path, info: { title, version, description? }, servers? }`: serves the OpenAPI document of the same operations at `path` (not under `basePath`). |
|
|
89
|
+
| `debug` | `true` adds the `trace` to problems and the real `detail` to 5xx ones. Off by default. |
|
|
90
|
+
| `context` | `{ headers?: { [contextKey]: headerName }, variables?: { [contextKey]: name } }`: the context of an operation from request headers and from properties a hook set on the request (`request.tenant`, declared with `decorateRequest`). |
|
|
91
|
+
| `auth` | `{ jwt: { secret: { env }, issuer?, audience?, algorithm?, header?, cookie? } }`: authenticates callers from a JSON Web Token. Experimental: see [Tokens and sessions](../../docs/auth.md#tokens-and-sessions). |
|
|
92
|
+
|
|
93
|
+
What JSON cannot hold goes in a second argument, the hooks: `fastify(options, { authenticator, middlewares, app })`. The type `FastifyHooks` is exported.
|
|
94
|
+
|
|
95
|
+
| Hook | Meaning |
|
|
96
|
+
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
97
|
+
| `authenticator` | `(request) => Principal \| null`: who calls, from the credentials of the request. `request` has `header(name)`, `cookie(name)`, the `operation` and `native`, the `FastifyRequest`. |
|
|
98
|
+
| `middlewares` | `onRequest` hooks: `(request, reply) => ...`, run in order before the routes of the sink. |
|
|
99
|
+
| `app` | The Fastify instance to add the routes to, instead of a new one. |
|
|
100
|
+
|
|
101
|
+
Invalid options throw `InvalidOutputStage` when the stage is made, and unknown operation ids in `route` or two operations on one method and path when the output is built.
|
|
102
|
+
|
|
103
|
+
## Behavior
|
|
104
|
+
|
|
105
|
+
The requests are handled by the route table of the core (`compileRoutes` of `@afora/core/adapters`), shared by every afora sink that serves HTTP, so they all answer the same way. This package only routes and sends. The behavior is described once, in [Outputs](../../docs/outputs.md); in short:
|
|
106
|
+
|
|
107
|
+
- **Input.** `post`, `put` and `patch` read a JSON body, `get` and `delete` the query string. Over it come the keys the [route of the use case](../../docs/use-cases.md#routes) places: `{name}` segments of the path, and the query keys, headers and cookies it declares. Text is converted to the numbers and booleans the input takes, and the blueprint of the use case validates it: a 400 problem with `issues`.
|
|
108
|
+
- **Access.** An operation whose use case declares an [`access`](../../docs/auth.md) asks the `authenticator` hook (or `auth`) who calls, and answers a 401 or a 403 problem before the input is validated. With neither, such an operation always answers 401.
|
|
109
|
+
- **Success.** The status of the route (`200` by default) with the response as JSON; records go through `toJSON`, so sensitive values are masked. A `204` has no body. The keys a route sends with `setCookie` leave the body and become `set-cookie` headers.
|
|
110
|
+
- **Errors.** `application/problem+json`, with the status of `statusOf`: the `statuses` of the output first, then 400, 401, 403, 404, 409, 422 for a declared error, else 500, whose detail is `"Internal error."` unless `debug` is on.
|
|
111
|
+
- **Unknown routes** are a 404 problem and anything thrown outside an operation is a problem too, unless you gave the `app`.
|
|
112
|
+
- **The body.** The routes are registered in an encapsulated plugin whose content type parser keeps the body as text, so an invalid JSON body is a problem like the others, not Fastify's own error.
|
|
113
|
+
|
|
114
|
+
## Middlewares and your own app
|
|
115
|
+
|
|
116
|
+
<!-- docs:code skip: fragment: the second argument of the stage; tenantOf stands for your code -->
|
|
117
|
+
```ts
|
|
118
|
+
fastify(
|
|
119
|
+
{ context: { variables: { tenant: "tenant" } } },
|
|
120
|
+
{
|
|
121
|
+
middlewares: [
|
|
122
|
+
async (request) => {
|
|
123
|
+
request.tenant = tenantOf(request.headers.host);
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
},
|
|
127
|
+
);
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
A value a middleware sets reaches the use case through `context.variables`, for the operations whose `context` blueprint declares the key.
|
|
131
|
+
|
|
132
|
+
`app` takes a Fastify instance you made: register `@fastify/cors`, `@fastify/helmet` or a rate limiter on it as usual. The routes of the sink live in a plugin of their own, where the body is read as text (the route table parses it), so the content type parsers of your instance are not touched; your not found and error handlers are kept.
|
|
133
|
+
|
|
134
|
+
## Catalog
|
|
135
|
+
|
|
136
|
+
`FastifyStages` is `stageCatalogOf(fastify)` (from `@afora/core/adapters`), and `stages` are the entries codegen reads to resolve `{ "sink": "fastify" }` in an `afora.json`:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// stages.ts
|
|
140
|
+
export { stages } from "@afora/fastify";
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
bunx afora-codegen generate --stages ./stages.ts
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Testing a sink
|
|
148
|
+
|
|
149
|
+
This package passes `httpProviderContract` of `@afora/core/testing`, the cases every afora sink that serves HTTP must pass. A sink for another server is tested the same way; see [Outputs](../../docs/outputs.md).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type Authenticator, type HttpOptions } from "@afora/core/adapters";
|
|
2
|
+
import { type FastifyInstance, type onRequestHookHandler } from "fastify";
|
|
3
|
+
/**
|
|
4
|
+
* The options of the `fastify` sink: those of every sink that serves HTTP
|
|
5
|
+
* (`basePath`, `route`, `responses`, `requestId`, `security`, `docs`,
|
|
6
|
+
* `debug`, `context`, `auth`). JSON, so the stage can live in an
|
|
7
|
+
* `afora.json`. The `variables` of `context` are properties a hook set on
|
|
8
|
+
* the request (`request.tenant`, after `decorateRequest`).
|
|
9
|
+
*/
|
|
10
|
+
export type FastifyOptions = HttpOptions;
|
|
11
|
+
/**
|
|
12
|
+
* What the `fastify` sink takes that JSON cannot hold, as the second
|
|
13
|
+
* argument of `fastify(options, hooks)`.
|
|
14
|
+
*/
|
|
15
|
+
export interface FastifyHooks {
|
|
16
|
+
/**
|
|
17
|
+
* Who calls, from the credentials of a request (`request.native` is the
|
|
18
|
+
* `FastifyRequest`). Asked for each operation with an `access` other than
|
|
19
|
+
* `public`; without it (and without `auth`) those operations answer 401.
|
|
20
|
+
*/
|
|
21
|
+
readonly authenticator?: Authenticator;
|
|
22
|
+
/** `onRequest` hooks, run in order before every route of the sink. */
|
|
23
|
+
readonly middlewares?: readonly onRequestHookHandler[];
|
|
24
|
+
/**
|
|
25
|
+
* The Fastify instance to add the routes to, instead of a new one: its own
|
|
26
|
+
* plugins, hooks, not found and error handlers are kept.
|
|
27
|
+
*/
|
|
28
|
+
readonly app?: FastifyInstance;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A Fastify instance that serves the operations of an output: the route each
|
|
32
|
+
* use case declares (`route` or `@Route`), else
|
|
33
|
+
* `POST {basePath}/{command}/{operation}`. The requests are handled by the
|
|
34
|
+
* route table of the core (`compileRoutes`), as in every sink that serves
|
|
35
|
+
* HTTP: the input from the body, the query, the path, headers and cookies,
|
|
36
|
+
* the context, the access of each use case (401 and 403), statuses,
|
|
37
|
+
* `application/problem+json` errors, the request id and the OpenAPI document
|
|
38
|
+
* at `docs.path`.
|
|
39
|
+
*
|
|
40
|
+
* The routes live in a plugin of their own, where the body is read as text
|
|
41
|
+
* (the table parses it, so an invalid one is a problem like the others), so
|
|
42
|
+
* the content type parsers of the instance are not touched. `hooks` (the
|
|
43
|
+
* second argument) holds what is not JSON: `authenticator`, `middlewares`
|
|
44
|
+
* (`onRequest` hooks) and an `app` to add the routes to.
|
|
45
|
+
*/
|
|
46
|
+
export declare const fastify: import("@afora/core/adapters").SinkFactory<FastifyInstance<import("fastify").RawServerDefault, import("node:http").IncomingMessage, import("node:http").ServerResponse<import("node:http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>, HttpOptions, FastifyHooks>;
|
|
47
|
+
/** The runtime catalog of this package: the stage name `fastify` resolves to the sink. */
|
|
48
|
+
export declare const FastifyStages: import("../../../dist/index.js").IStageCatalog<Readonly<Record<string, import("../../../dist/index.js").StageFactory>>>;
|
|
49
|
+
/** The catalog entries codegen reads (`--stages`): `{ name, module, export, kind }`. */
|
|
50
|
+
export declare const stages: readonly [{
|
|
51
|
+
readonly name: "fastify";
|
|
52
|
+
readonly module: "@afora/fastify";
|
|
53
|
+
readonly export: "fastify";
|
|
54
|
+
readonly kind: "sink";
|
|
55
|
+
}];
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
compileRoutes,
|
|
4
|
+
HTTP_OPTION_KEYS,
|
|
5
|
+
httpOptionsIssue,
|
|
6
|
+
sinkOf,
|
|
7
|
+
stageCatalogOf
|
|
8
|
+
} from "@afora/core/adapters";
|
|
9
|
+
import Fastify from "fastify";
|
|
10
|
+
function validate(options) {
|
|
11
|
+
for (const key of Object.keys(options)) {
|
|
12
|
+
if (!HTTP_OPTION_KEYS.includes(key)) {
|
|
13
|
+
return `fastify has no option "${key}".`;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return httpOptionsIssue(options, "fastify");
|
|
17
|
+
}
|
|
18
|
+
function first(value) {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return first(value[0]);
|
|
21
|
+
return typeof value === "string" ? value : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class FastifyHttpRequest {
|
|
25
|
+
native;
|
|
26
|
+
constructor(native) {
|
|
27
|
+
this.native = native;
|
|
28
|
+
}
|
|
29
|
+
param(name) {
|
|
30
|
+
return this.native.params[name];
|
|
31
|
+
}
|
|
32
|
+
query() {
|
|
33
|
+
const query = {};
|
|
34
|
+
for (const [name, value] of Object.entries(this.native.query)) {
|
|
35
|
+
query[name] = first(value);
|
|
36
|
+
}
|
|
37
|
+
return query;
|
|
38
|
+
}
|
|
39
|
+
header(name) {
|
|
40
|
+
return first(this.native.headers[name]);
|
|
41
|
+
}
|
|
42
|
+
text() {
|
|
43
|
+
return typeof this.native.body === "string" ? this.native.body : "";
|
|
44
|
+
}
|
|
45
|
+
variable(name) {
|
|
46
|
+
return this.native[name];
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
var requestOf = (request) => new FastifyHttpRequest(request);
|
|
50
|
+
function send(reply, result) {
|
|
51
|
+
reply.code(result.status).headers(result.headers);
|
|
52
|
+
if (result.cookies.length > 0)
|
|
53
|
+
reply.header("set-cookie", result.cookies);
|
|
54
|
+
return result.body === null ? reply.send() : reply.send(result.body);
|
|
55
|
+
}
|
|
56
|
+
function fastifyPath(path) {
|
|
57
|
+
return path.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, ":$1");
|
|
58
|
+
}
|
|
59
|
+
var fastify = sinkOf({
|
|
60
|
+
name: "fastify",
|
|
61
|
+
validate,
|
|
62
|
+
build: (operations, options, context, hooks) => {
|
|
63
|
+
const table = compileRoutes(operations, options, context, {
|
|
64
|
+
source: "fastify",
|
|
65
|
+
...hooks?.authenticator ? { authenticator: hooks.authenticator } : {}
|
|
66
|
+
});
|
|
67
|
+
const app = hooks?.app ?? Fastify();
|
|
68
|
+
if (!hooks?.app) {
|
|
69
|
+
app.setNotFoundHandler((request, reply) => send(reply, table.notFound(requestOf(request))));
|
|
70
|
+
app.setErrorHandler((error, request, reply) => send(reply, table.failure(error, { request: requestOf(request) })));
|
|
71
|
+
}
|
|
72
|
+
app.register(async (scope) => {
|
|
73
|
+
scope.removeAllContentTypeParsers();
|
|
74
|
+
scope.addContentTypeParser("*", { parseAs: "string" }, (_request, body, done) => done(null, body));
|
|
75
|
+
for (const middleware of hooks?.middlewares ?? []) {
|
|
76
|
+
scope.addHook("onRequest", middleware);
|
|
77
|
+
}
|
|
78
|
+
for (const route of table.routes) {
|
|
79
|
+
scope.route({
|
|
80
|
+
method: route.method.toUpperCase(),
|
|
81
|
+
url: fastifyPath(route.path),
|
|
82
|
+
handler: async (request, reply) => send(reply, await route.handle(requestOf(request)))
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
const docs = table.docs;
|
|
86
|
+
if (docs) {
|
|
87
|
+
scope.get(docs.path, (request, reply) => send(reply, docs.handle(requestOf(request))));
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
return app;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
var FastifyStages = stageCatalogOf(fastify);
|
|
94
|
+
var stages = [
|
|
95
|
+
{
|
|
96
|
+
name: "fastify",
|
|
97
|
+
module: "@afora/fastify",
|
|
98
|
+
export: "fastify",
|
|
99
|
+
kind: "sink"
|
|
100
|
+
}
|
|
101
|
+
];
|
|
102
|
+
export {
|
|
103
|
+
FastifyStages,
|
|
104
|
+
fastify,
|
|
105
|
+
stages
|
|
106
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@afora/fastify",
|
|
3
|
+
"version": "0.0.11",
|
|
4
|
+
"description": "A Fastify sink for afora outputs: one route per operation, problem+json errors, sensitive data masked, declared access enforced and an optional OpenAPI document.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"afora",
|
|
7
|
+
"fastify",
|
|
8
|
+
"openapi",
|
|
9
|
+
"problem-json",
|
|
10
|
+
"http",
|
|
11
|
+
"api"
|
|
12
|
+
],
|
|
13
|
+
"author": "Alan Reis <alanreisanjo@gmail.com> (https://github.com/Hoyasumii)",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"homepage": "https://github.com/afora-framework/core/tree/main/packages/fastify#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/afora-framework/core.git",
|
|
19
|
+
"directory": "packages/fastify"
|
|
20
|
+
},
|
|
21
|
+
"type": "module",
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"module": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"bun": ">=1.4.4",
|
|
38
|
+
"node": ">=22"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public",
|
|
42
|
+
"provenance": true
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"typecheck": "bun check",
|
|
46
|
+
"build": "rm -rf dist && bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --tsconfig-override tsconfig.build.json && tsc -p tsconfig.build.json && bun ../../scripts/add-dts-extensions.ts dist",
|
|
47
|
+
"test": "bun test"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/bun": "^1.4.4",
|
|
51
|
+
"fastify": "^5.12.8",
|
|
52
|
+
"typebox": "^1.4.3"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"@afora/core": ">=0.0.9",
|
|
56
|
+
"fastify": "^5.12.8",
|
|
57
|
+
"typebox": "^1"
|
|
58
|
+
}
|
|
59
|
+
}
|