Skip to content

Commit

Permalink
docs: default 4xx error schemas for all routes (#2159)
Browse files Browse the repository at this point in the history
  • Loading branch information
zone117x authored Nov 12, 2024
1 parent ed87f15 commit b17895b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,13 @@
"TS_NODE_SKIP_IGNORE": "true"
}
},
{
"type": "node",
"request": "launch",
"name": "docs: openapi-generator",
"runtimeArgs": ["-r", "ts-node/register/transpile-only"],
"args": ["${workspaceFolder}/src/openapi-generator.ts"]
},
{
"type": "node",
"request": "launch",
Expand Down
3 changes: 2 additions & 1 deletion src/api/schemas/responses/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ import { NakamotoBlockSchema, SignerSignatureSchema } from '../entities/block';
export const ErrorResponseSchema = Type.Object(
{
error: Type.String(),
message: Type.Optional(Type.String()),
},
{ title: 'Error Response' }
{ title: 'Error Response', additionalProperties: true }
);

export const ServerStatusResponseSchema = Type.Object(
Expand Down
13 changes: 12 additions & 1 deletion src/openapi-generator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { TSchema, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import FastifySwagger from '@fastify/swagger';
import { writeFileSync } from 'fs';
import { OpenApiSchemaOptions } from './api/schemas/openapi';
import { StacksApiRoutes } from './api/init';
import { ErrorResponseSchema } from './api/schemas/responses/responses';

/**
* Generates `openapi.yaml` based on current Swagger definitions.
Expand All @@ -14,6 +15,16 @@ async function generateOpenApiFiles() {
logger: true,
}).withTypeProvider<TypeBoxTypeProvider>();

// If a response schema is defined but lacks a '4xx' response, add it
fastify.addHook(
'onRoute',
(route: { schema?: { response: Record<string | number, TSchema> } }) => {
if (route.schema?.response && !route.schema?.response['4xx']) {
route.schema.response['4xx'] = ErrorResponseSchema;
}
}
);

await fastify.register(FastifySwagger, OpenApiSchemaOptions);
await fastify.register(StacksApiRoutes);
await fastify.ready();
Expand Down

0 comments on commit b17895b

Please sign in to comment.