|
| 1 | +/** |
| 2 | + * buildApp() — wires the Fastify application. |
| 3 | + * |
| 4 | + * Plugin ordering per plans/api-skeleton.md#plugin-order: |
| 5 | + * 1. @fastify/env → validates env; populates fastify.config |
| 6 | + * 2. @fastify/cors → CORS for dev SPA proxy + future cross-origin consumers |
| 7 | + * 3. @fastify/cookie → cookie parsing for session JWTs (auth-jwt-substrate plan) |
| 8 | + * 4. trace-id plugin → UUIDv7 traceId on every request |
| 9 | + * 5. setErrorHandler → single error mapper for all throws |
| 10 | + * 6. store plugin → decorates fastify.store from bootStores() |
| 11 | + * 7. rate-limit plugin → in-memory counters keyed per-IP + per-account |
| 12 | + * 8. idempotency plugin → in-memory map keyed by personId+key |
| 13 | + * 9. @fastify/swagger → OpenAPI 3.1 doc generation |
| 14 | + * 10. @fastify/swagger-ui → Swagger UI at /api/_docs |
| 15 | + * 11. routes → registered last after all plumbing |
| 16 | + * |
| 17 | + * Tests can call buildApp() with overrideEnv to inject a test environment |
| 18 | + * without requiring real filesystem paths. |
| 19 | + */ |
| 20 | +import Fastify, { type FastifyInstance, type FastifyServerOptions } from 'fastify'; |
| 21 | +import fastifyEnv from '@fastify/env'; |
| 22 | +import fastifyCors from '@fastify/cors'; |
| 23 | +import fastifyCookie from '@fastify/cookie'; |
| 24 | +import fastifySwagger from '@fastify/swagger'; |
| 25 | +import fastifySwaggerUi from '@fastify/swagger-ui'; |
| 26 | + |
| 27 | +import { envJsonSchema, type Env } from './env.js'; |
| 28 | +import { mapError } from './lib/errors.js'; |
| 29 | +import traceIdPlugin from './plugins/trace-id.js'; |
| 30 | +import storePlugin from './plugins/store.js'; |
| 31 | +import rateLimitPlugin from './plugins/rate-limit.js'; |
| 32 | +import idempotencyPlugin from './plugins/idempotency.js'; |
| 33 | +import { healthRoutes } from './routes/health.js'; |
| 34 | + |
| 35 | +declare module 'fastify' { |
| 36 | + interface FastifyInstance { |
| 37 | + config: Env; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +export interface BuildAppOptions { |
| 42 | + /** |
| 43 | + * Override environment variables for testing. |
| 44 | + * When provided, @fastify/env still validates the schema but reads from this |
| 45 | + * object instead of process.env. |
| 46 | + */ |
| 47 | + overrideEnv?: Partial<Record<string, string>>; |
| 48 | + /** Extra Fastify server options (e.g. logger: false for tests). */ |
| 49 | + serverOptions?: FastifyServerOptions; |
| 50 | +} |
| 51 | + |
| 52 | +export async function buildApp(opts: BuildAppOptions = {}): Promise<FastifyInstance> { |
| 53 | + const { overrideEnv, serverOptions = {} } = opts; |
| 54 | + |
| 55 | + // Default logger: pretty in dev, JSON in prod. |
| 56 | + // Callers can override via serverOptions.logger. |
| 57 | + const defaultLogger: FastifyServerOptions['logger'] = |
| 58 | + process.env['NODE_ENV'] === 'production' |
| 59 | + ? true |
| 60 | + : { transport: { target: 'pino-pretty' } }; |
| 61 | + |
| 62 | + const fastify = Fastify({ |
| 63 | + logger: defaultLogger, |
| 64 | + pluginTimeout: 30_000, // gitsheets boot runs git operations which can be slow |
| 65 | + ...serverOptions, |
| 66 | + genReqId: () => '', // traceId plugin handles IDs |
| 67 | + }); |
| 68 | + |
| 69 | + // ----- 1. Env validation ----- |
| 70 | + await fastify.register(fastifyEnv, { |
| 71 | + schema: envJsonSchema, |
| 72 | + data: overrideEnv ?? process.env, |
| 73 | + dotenv: false, |
| 74 | + }); |
| 75 | + |
| 76 | + // ----- 2. CORS ----- |
| 77 | + await fastify.register(fastifyCors, { |
| 78 | + origin: fastify.config.NODE_ENV === 'production' ? false : true, |
| 79 | + credentials: true, |
| 80 | + }); |
| 81 | + |
| 82 | + // ----- 3. Cookie parsing ----- |
| 83 | + await fastify.register(fastifyCookie); |
| 84 | + |
| 85 | + // ----- 4. Trace ID (UUIDv7 on every request) ----- |
| 86 | + await fastify.register(traceIdPlugin); |
| 87 | + |
| 88 | + // ----- 5. Error mapper ----- |
| 89 | + fastify.setErrorHandler(mapError); |
| 90 | + |
| 91 | + // ----- 6. Store (boots gitsheets + private-store) ----- |
| 92 | + await fastify.register(storePlugin); |
| 93 | + |
| 94 | + // ----- 7. Rate limiting ----- |
| 95 | + await fastify.register(rateLimitPlugin); |
| 96 | + |
| 97 | + // ----- 8. Idempotency ----- |
| 98 | + await fastify.register(idempotencyPlugin); |
| 99 | + |
| 100 | + // ----- 9-10. OpenAPI / Swagger UI ----- |
| 101 | + await fastify.register(fastifySwagger, { |
| 102 | + openapi: { |
| 103 | + openapi: '3.1.0', |
| 104 | + info: { |
| 105 | + title: 'CodeForPhilly API', |
| 106 | + description: 'The codeforphilly.org API. See specs/api/ for the authoritative spec.', |
| 107 | + version: '1.0.0', |
| 108 | + }, |
| 109 | + servers: [{ url: '/api', description: 'API base' }], |
| 110 | + tags: [{ name: 'health', description: 'Health check' }], |
| 111 | + }, |
| 112 | + prefix: '/api', |
| 113 | + }); |
| 114 | + |
| 115 | + await fastify.register(fastifySwaggerUi, { |
| 116 | + routePrefix: '/api/_docs', |
| 117 | + uiConfig: { |
| 118 | + docExpansion: 'list', |
| 119 | + deepLinking: false, |
| 120 | + }, |
| 121 | + }); |
| 122 | + |
| 123 | + // ----- 11. Routes ----- |
| 124 | + await fastify.register(healthRoutes); |
| 125 | + |
| 126 | + // Serve the OpenAPI JSON at the spec-mandated path /api/_openapi.json |
| 127 | + // (swagger-ui also exposes it at /api/_docs/json, but the spec names this path) |
| 128 | + fastify.get('/api/_openapi.json', { schema: { hide: true } }, (_req, reply) => { |
| 129 | + return reply.send(fastify.swagger()); |
| 130 | + }); |
| 131 | + |
| 132 | + return fastify; |
| 133 | +} |
0 commit comments