Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: default 4xx error schemas for all routes #2159

Merged
merged 1 commit into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading