@tcds-io/fastify-server 0.0.0-stage → 0.1.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 +53 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/server.d.ts +47 -0
- package/dist/server.js +91 -0
- package/package.json +48 -3
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tcds-io/fastify-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Fastify with the plumbing every API repeats already wired: a request id per request, pino logging bound to it, CORS, and the one error handler from [`@tcds-io/fastify-errors`](../fastify-errors). `fastify` (>= 5.12) is a peer dependency.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createHttpServer, pinoLogger } from '@tcds-io/fastify-server';
|
|
7
|
+
import { UuidV7Generator } from '@tcds-io/runtime';
|
|
8
|
+
|
|
9
|
+
const http = createHttpServer({
|
|
10
|
+
logLevel: 'info',
|
|
11
|
+
ids: new UuidV7Generator(),
|
|
12
|
+
corsOrigins: ['https://app.example.com'],
|
|
13
|
+
errorOptions: { unknownCode: 'INTERNAL_ERROR', clientErrorCode: 'VALIDATION_FAILED' }, // see fastify-errors
|
|
14
|
+
});
|
|
15
|
+
const logger = pinoLogger(http); // the `Logger` port from @tcds-io/runtime
|
|
16
|
+
|
|
17
|
+
await http.listen({ host: '0.0.0.0', port: 3000 });
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- **Request id:** taken from `x-request-id` when the caller sends one, minted by `ids` otherwise, echoed on the response, bound to every log line as `requestId`, including on errors Fastify raises before the request hooks run (`frameworkErrors`).
|
|
21
|
+
- **CORS:** off when `corsOrigins` is empty or omitted (same-origin only); otherwise only those origins, with `x-request-id` exposed.
|
|
22
|
+
- **Errors:** `installErrorHandler(fastify, errorOptions)`: one wire shape for every failure, the real message of a 5xx never leaves.
|
|
23
|
+
- **`pinoLogger(fastify)`** implements `debug`, `info`, `warn`, `error` and `fatal`, fields first as pino expects.
|
|
24
|
+
- **`logStream`** sends log lines elsewhere than stdout (a test collects them).
|
|
25
|
+
|
|
26
|
+
## Taking over a piece
|
|
27
|
+
|
|
28
|
+
Each option below is optional; a server that sets none of them behaves as above. Conflicting options throw at construction.
|
|
29
|
+
|
|
30
|
+
| Option | Instead of | Use when |
|
|
31
|
+
| --- | --- | --- |
|
|
32
|
+
| `logger` | `logLevel` + `logStream` (throws if either is also set) | You bring your own pino options (serializers, redaction, transport), or `false` for no logging. |
|
|
33
|
+
| `requestLogging: false` | Fastify's `incoming request` / `request completed` lines | You write your own access log line. `requestId` stays bound to every line. |
|
|
34
|
+
| `requestId: (raw) => string` | `ids` + trusting the caller's `x-request-id` | The id comes from elsewhere (a `traceparent`, a gateway header). The caller's `x-request-id` is then ignored; the id is still echoed on the response. |
|
|
35
|
+
| `cors: (request) => CorsAnswer` | `corsOrigins` (throws if both are set) | The policy differs per route family. The answer is the `@fastify/cors` options for that request (readonly arrays accepted); `x-request-id` is always added to its `exposedHeaders`. |
|
|
36
|
+
| `installErrorHandler: false` | the error and not-found handlers | You install your own `setErrorHandler` (no `FSTWRN004`) and want Fastify's default 404, or your own `setNotFoundHandler`. |
|
|
37
|
+
| `frameworkErrors` | the router-phase answer (malformed URL, bad content type, ...) | Your error body differs from `fastify-errors`, e.g. with `installErrorHandler: false`. `x-request-id` is written before it runs. |
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const http = createHttpServer({
|
|
41
|
+
logger: { level: 'info', redact: ['req.headers.authorization'] },
|
|
42
|
+
requestLogging: false,
|
|
43
|
+
requestId: (raw) => traceIdFrom(raw.headers.traceparent) ?? randomUUID(),
|
|
44
|
+
cors: (request) => (request.url.startsWith('/public/') ? { origin: true } : { origin: ['https://app.example.com'], credentials: true }),
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Known gap
|
|
49
|
+
|
|
50
|
+
Errors Fastify raises before the request hooks run (`frameworkErrors`) skip the CORS hook, so with `corsOrigins` (or `cors`) and the default `frameworkErrors` those replies carry no CORS headers: a browser sees a CORS failure instead of the 400. Set `frameworkErrors` and add the headers there if your clients need to read those errors.
|
|
51
|
+
|
|
52
|
+
## Peers
|
|
53
|
+
|
|
54
|
+
`fastify`, `@tcds-io/domain` and `@tcds-io/runtime` are peer dependencies (ADR-0070).
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createHttpServer, pinoLogger, REQUEST_ID_HEADER } from './server.js';
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type FastifyCorsOptions } from '@fastify/cors';
|
|
2
|
+
import { type ErrorHandlerOptions } from '@tcds-io/fastify-errors';
|
|
3
|
+
import type { IdGenerator, Logger } from '@tcds-io/runtime';
|
|
4
|
+
import { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest, type FastifyServerOptions, type RawRequestDefaultExpression } from 'fastify';
|
|
5
|
+
export declare const REQUEST_ID_HEADER = "x-request-id";
|
|
6
|
+
type CorsOrigin = boolean | string | RegExp;
|
|
7
|
+
/** The CORS options for one request (the `@fastify/cors` delegator answer), with readonly arrays accepted. */
|
|
8
|
+
export type CorsAnswer = Omit<FastifyCorsOptions, 'origin' | 'methods' | 'allowedHeaders' | 'exposedHeaders' | 'delegator' | 'hook' | 'hideOptionsRoute' | 'logLevel'> & {
|
|
9
|
+
readonly origin?: CorsOrigin | readonly CorsOrigin[];
|
|
10
|
+
readonly methods?: string | readonly string[];
|
|
11
|
+
readonly allowedHeaders?: string | readonly string[];
|
|
12
|
+
/** `x-request-id` is always added. */
|
|
13
|
+
readonly exposedHeaders?: string | readonly string[];
|
|
14
|
+
};
|
|
15
|
+
export type HttpServerOptions = {
|
|
16
|
+
/** Required unless `logger` is set. */
|
|
17
|
+
readonly logLevel?: string;
|
|
18
|
+
/** Mints the id of a request that arrives without `x-request-id`. Required unless `requestId` is set. */
|
|
19
|
+
readonly ids?: IdGenerator;
|
|
20
|
+
/** Browser origins allowed to call the API. Empty or omitted: none (same-origin only). Not with `cors`. */
|
|
21
|
+
readonly corsOrigins?: readonly string[];
|
|
22
|
+
/** Passed to `installErrorHandler`: status table, wire codes, internal message, `onError`. */
|
|
23
|
+
readonly errorOptions?: ErrorHandlerOptions;
|
|
24
|
+
/** Where log lines go. Default: stdout. Not with `logger`. */
|
|
25
|
+
readonly logStream?: NodeJS.WritableStream;
|
|
26
|
+
/** Fastify's `logger` option, used as given (options object or `false`). Not with `logLevel` or `logStream`. */
|
|
27
|
+
readonly logger?: FastifyServerOptions['logger'];
|
|
28
|
+
/** Fastify's "incoming request" / "request completed" log lines. Default true. */
|
|
29
|
+
readonly requestLogging?: boolean;
|
|
30
|
+
/** Derives the request id from the raw request; `x-request-id` from the caller is then not trusted and `ids` is unused. */
|
|
31
|
+
readonly requestId?: (request: RawRequestDefaultExpression) => string;
|
|
32
|
+
/** CORS decided per request; `x-request-id` is always added to the exposed headers. Not with `corsOrigins`. */
|
|
33
|
+
readonly cors?: (request: FastifyRequest) => CorsAnswer;
|
|
34
|
+
/** Default true. false: neither the error handler nor the not-found handler is installed; the caller installs its own. */
|
|
35
|
+
readonly installErrorHandler?: boolean;
|
|
36
|
+
/** Answers errors Fastify raises before the request hooks run. `x-request-id` is written before it is called. */
|
|
37
|
+
readonly frameworkErrors?: (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => void;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one and
|
|
41
|
+
* minted by `ids` otherwise, or derived by `requestId`), echoed back on the response and bound to every log line as
|
|
42
|
+
* `requestId`, optional CORS, and the one error handler (`@tcds-io/fastify-errors`).
|
|
43
|
+
*/
|
|
44
|
+
export declare const createHttpServer: (options: HttpServerOptions) => FastifyInstance;
|
|
45
|
+
/** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
|
|
46
|
+
export declare const pinoLogger: (fastify: Pick<FastifyInstance, "log">) => Logger;
|
|
47
|
+
export {};
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import cors, {} from '@fastify/cors';
|
|
2
|
+
import { createErrorHandler, installErrorHandler } from '@tcds-io/fastify-errors';
|
|
3
|
+
import Fastify, { LogController, } from 'fastify';
|
|
4
|
+
export const REQUEST_ID_HEADER = 'x-request-id';
|
|
5
|
+
const validate = (options) => {
|
|
6
|
+
if (options.logger !== undefined && (options.logLevel !== undefined || options.logStream !== undefined)) {
|
|
7
|
+
throw new Error('createHttpServer: `logger` replaces `logLevel` and `logStream`; set one or the other');
|
|
8
|
+
}
|
|
9
|
+
if (options.logger === undefined && options.logLevel === undefined) {
|
|
10
|
+
throw new Error('createHttpServer: set `logLevel` or `logger`');
|
|
11
|
+
}
|
|
12
|
+
if (options.ids === undefined && options.requestId === undefined) {
|
|
13
|
+
throw new Error('createHttpServer: set `ids` or `requestId`');
|
|
14
|
+
}
|
|
15
|
+
if (options.cors !== undefined && options.corsOrigins !== undefined) {
|
|
16
|
+
throw new Error('createHttpServer: set `cors` or `corsOrigins`, not both');
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const list = (value) => value === undefined ? [] : typeof value === 'string' ? value.split(',').map((item) => item.trim()).filter(Boolean) : [...value];
|
|
20
|
+
const withRequestIdExposed = (answer) => {
|
|
21
|
+
const exposed = list(answer.exposedHeaders);
|
|
22
|
+
if (!exposed.some((header) => header.toLowerCase() === REQUEST_ID_HEADER))
|
|
23
|
+
exposed.push(REQUEST_ID_HEADER);
|
|
24
|
+
return {
|
|
25
|
+
...answer,
|
|
26
|
+
origin: Array.isArray(answer.origin) ? [...answer.origin] : answer.origin,
|
|
27
|
+
methods: answer.methods === undefined ? undefined : list(answer.methods),
|
|
28
|
+
allowedHeaders: answer.allowedHeaders === undefined ? undefined : list(answer.allowedHeaders),
|
|
29
|
+
exposedHeaders: exposed,
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one and
|
|
34
|
+
* minted by `ids` otherwise, or derived by `requestId`), echoed back on the response and bound to every log line as
|
|
35
|
+
* `requestId`, optional CORS, and the one error handler (`@tcds-io/fastify-errors`).
|
|
36
|
+
*/
|
|
37
|
+
export const createHttpServer = (options) => {
|
|
38
|
+
validate(options);
|
|
39
|
+
const answerFrameworkError = options.frameworkErrors ?? createErrorHandler(options.errorOptions);
|
|
40
|
+
const requestId = options.requestId;
|
|
41
|
+
const ids = options.ids;
|
|
42
|
+
const fastify = Fastify({
|
|
43
|
+
logger: options.logger !== undefined
|
|
44
|
+
? options.logger
|
|
45
|
+
: { level: options.logLevel, ...(options.logStream !== undefined ? { stream: options.logStream } : {}) },
|
|
46
|
+
logController: new LogController({
|
|
47
|
+
requestIdLogLabel: 'requestId',
|
|
48
|
+
...(options.requestLogging === false ? { disableRequestLogging: true } : {}),
|
|
49
|
+
}),
|
|
50
|
+
...(requestId !== undefined
|
|
51
|
+
? { requestIdHeader: false, genReqId: requestId }
|
|
52
|
+
: { requestIdHeader: REQUEST_ID_HEADER, genReqId: () => ids.next() }),
|
|
53
|
+
// Errors Fastify raises before the request hooks ran (a malformed URL, say): the request id the `onRequest` hook
|
|
54
|
+
// would have echoed, then the same body as every other error (or the caller's own answer).
|
|
55
|
+
frameworkErrors: (error, request, reply) => {
|
|
56
|
+
void reply.header(REQUEST_ID_HEADER, request.id);
|
|
57
|
+
void answerFrameworkError(error, request, reply);
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
fastify.addHook('onRequest', (request, reply, done) => {
|
|
61
|
+
reply.header(REQUEST_ID_HEADER, request.id);
|
|
62
|
+
done();
|
|
63
|
+
});
|
|
64
|
+
const corsAnswer = options.cors;
|
|
65
|
+
if (corsAnswer !== undefined) {
|
|
66
|
+
void fastify.register(cors, {
|
|
67
|
+
delegator: (request, callback) => {
|
|
68
|
+
try {
|
|
69
|
+
callback(null, withRequestIdExposed(corsAnswer(request)));
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
callback(error);
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
else if (options.corsOrigins !== undefined && options.corsOrigins.length > 0) {
|
|
78
|
+
void fastify.register(cors, { origin: [...options.corsOrigins], exposedHeaders: [REQUEST_ID_HEADER] });
|
|
79
|
+
}
|
|
80
|
+
if (options.installErrorHandler !== false)
|
|
81
|
+
installErrorHandler(fastify, options.errorOptions);
|
|
82
|
+
return fastify;
|
|
83
|
+
};
|
|
84
|
+
/** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
|
|
85
|
+
export const pinoLogger = (fastify) => ({
|
|
86
|
+
debug: (message, fields) => fastify.log.debug(fields ?? {}, message),
|
|
87
|
+
info: (message, fields) => fastify.log.info(fields ?? {}, message),
|
|
88
|
+
warn: (message, fields) => fastify.log.warn(fields ?? {}, message),
|
|
89
|
+
error: (message, fields) => fastify.log.error(fields ?? {}, message),
|
|
90
|
+
fatal: (message, fields) => fastify.log.fatal(fields ?? {}, message),
|
|
91
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tcds-io/fastify-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Fastify with request ids, pino logging, CORS and the one error handler already wired.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/tcds-io/ts-platform.git",
|
|
11
|
+
"directory": "packages/fastify-server"
|
|
12
|
+
},
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public",
|
|
15
|
+
"registry": "https://registry.npmjs.org"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@fastify/cors": "^11.1.0",
|
|
28
|
+
"@tcds-io/fastify-errors": "^0.1.2"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@tcds-io/domain": "~0.1.0",
|
|
32
|
+
"@tcds-io/runtime": "~0.1.0",
|
|
33
|
+
"fastify": ">=5.12"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^22.10.2",
|
|
37
|
+
"fastify": "^5.12.8",
|
|
38
|
+
"typescript": "^5.7.2",
|
|
39
|
+
"vitest": "^2.1.8",
|
|
40
|
+
"@tcds-io/domain": "^0.1.0",
|
|
41
|
+
"@tcds-io/runtime": "^0.1.0"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
48
|
+
"check:types": "tsc --noEmit -p .",
|
|
49
|
+
"test": "vitest run"
|
|
50
|
+
}
|
|
6
51
|
}
|