@tcds-io/fastify-server 0.0.0-stage → 0.1.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 CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @tcds-io/fastify-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ ## Peers
27
+
28
+ `fastify`, `@tcds-io/errors` and `@tcds-io/runtime` are peer dependencies (ADR-0070).
@@ -0,0 +1,2 @@
1
+ export { createHttpServer, pinoLogger, REQUEST_ID_HEADER } from './server.js';
2
+ export type { HttpServerOptions } from './server.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createHttpServer, pinoLogger, REQUEST_ID_HEADER } from './server.js';
@@ -0,0 +1,23 @@
1
+ import { type ErrorHandlerOptions } from '@tcds-io/fastify-errors';
2
+ import type { IdGenerator, Logger } from '@tcds-io/runtime';
3
+ import { type FastifyInstance } from 'fastify';
4
+ export declare const REQUEST_ID_HEADER = "x-request-id";
5
+ export type HttpServerOptions = {
6
+ readonly logLevel: string;
7
+ /** Mints the id of a request that arrives without `x-request-id`. */
8
+ readonly ids: IdGenerator;
9
+ /** Browser origins allowed to call the API. Empty or omitted: none (same-origin only). */
10
+ readonly corsOrigins?: readonly string[];
11
+ /** Passed to `installErrorHandler`: status table, wire codes, internal message, `onError`. */
12
+ readonly errorOptions?: ErrorHandlerOptions;
13
+ /** Where log lines go. Default: stdout. */
14
+ readonly logStream?: NodeJS.WritableStream;
15
+ };
16
+ /**
17
+ * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one,
18
+ * minted by `ids` otherwise), echoed back on the response and bound to every log line as `requestId`, optional
19
+ * CORS, and the one error handler (`@tcds-io/fastify-errors`).
20
+ */
21
+ export declare const createHttpServer: (options: HttpServerOptions) => FastifyInstance;
22
+ /** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
23
+ export declare const pinoLogger: (fastify: Pick<FastifyInstance, "log">) => Logger;
package/dist/server.js ADDED
@@ -0,0 +1,41 @@
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
+ /**
6
+ * Fastify with pino logging, one request id per request (taken from `x-request-id` when the caller sends one,
7
+ * minted by `ids` otherwise), echoed back on the response and bound to every log line as `requestId`, optional
8
+ * CORS, and the one error handler (`@tcds-io/fastify-errors`).
9
+ */
10
+ export const createHttpServer = (options) => {
11
+ const frameworkHandler = createErrorHandler(options.errorOptions);
12
+ const fastify = Fastify({
13
+ logger: { level: options.logLevel, ...(options.logStream !== undefined ? { stream: options.logStream } : {}) },
14
+ logController: new LogController({ requestIdLogLabel: 'requestId' }),
15
+ requestIdHeader: REQUEST_ID_HEADER,
16
+ genReqId: () => options.ids.next(),
17
+ // Errors Fastify raises before the request hooks ran (a malformed URL, say): same body, and the request id the
18
+ // `onRequest` hook would have echoed.
19
+ frameworkErrors: (error, request, reply) => {
20
+ void reply.header(REQUEST_ID_HEADER, request.id);
21
+ void frameworkHandler(error, request, reply);
22
+ },
23
+ });
24
+ fastify.addHook('onRequest', (request, reply, done) => {
25
+ reply.header(REQUEST_ID_HEADER, request.id);
26
+ done();
27
+ });
28
+ if (options.corsOrigins !== undefined && options.corsOrigins.length > 0) {
29
+ void fastify.register(cors, { origin: [...options.corsOrigins], exposedHeaders: [REQUEST_ID_HEADER] });
30
+ }
31
+ installErrorHandler(fastify, options.errorOptions);
32
+ return fastify;
33
+ };
34
+ /** The `Logger` port (`@tcds-io/runtime`) over Fastify's pino logger. */
35
+ export const pinoLogger = (fastify) => ({
36
+ debug: (message, fields) => fastify.log.debug(fields ?? {}, message),
37
+ info: (message, fields) => fastify.log.info(fields ?? {}, message),
38
+ warn: (message, fields) => fastify.log.warn(fields ?? {}, message),
39
+ error: (message, fields) => fastify.log.error(fields ?? {}, message),
40
+ fatal: (message, fields) => fastify.log.fatal(fields ?? {}, message),
41
+ });
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@tcds-io/fastify-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
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.0"
29
+ },
30
+ "peerDependencies": {
31
+ "@tcds-io/errors": "~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/runtime": "^0.1.0",
41
+ "@tcds-io/errors": "^0.1.0"
42
+ },
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.build.json",
48
+ "check:types": "tsc --noEmit -p .",
49
+ "test": "vitest run"
50
+ }
6
51
  }