Skip to content

Commit

Permalink
handle ref objects for responses
Browse files Browse the repository at this point in the history
  • Loading branch information
AGalabov committed Dec 6, 2024
1 parent 58e9213 commit 1160af8
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 6 deletions.
46 changes: 46 additions & 0 deletions spec/custom-components.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,50 @@ describe('Custom components', () => {
},
});
});

it('can generate responses', () => {
const registry = new OpenAPIRegistry();

const response = registry.registerComponent('responses', 'BadRequest', {
description: 'BadRequest',
content: {
'application/json': {
schema: {
type: 'object',
properties: { name: { type: 'string' } },
},
},
},
});

registry.registerPath({
summary: 'Get user of an organization',
method: 'get',
path: '/test',
responses: {
'400': response.ref,
},
});

const builder = new OpenApiGeneratorV3(registry.definitions);
const document = builder.generateDocument(testDocConfig);

expect(document.paths['/test']?.get?.responses['400']).toEqual({
$ref: '#/components/responses/BadRequest',
});

expect(document.components!.responses).toEqual({
BadRequest: {
description: 'BadRequest',
content: {
'application/json': {
schema: {
type: 'object',
properties: { name: { type: 'string' } },
},
},
},
},
});
});
});
20 changes: 15 additions & 5 deletions src/openapi-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,11 +597,15 @@ export class OpenAPIGenerator {
return routeDoc;
}

private getResponse({
content,
headers,
...rest
}: ResponseConfig): ResponseObject | ReferenceObject {
private getResponse(
response: ResponseConfig | ReferenceObject
): ResponseObject | ReferenceObject {
if (this.isReferenceObject(response)) {
return response;
}

const { content, headers, ...rest } = response;

const responseContent = content
? { content: this.getBodyContent(content) }
: {};
Expand All @@ -626,6 +630,12 @@ export class OpenAPIGenerator {
};
}

private isReferenceObject<T extends object>(
schema: T | ReferenceObject
): schema is ReferenceObject {
return '$ref' in schema;
}

private getResponseHeaders(headers: AnyZodObject): HeadersObject {
const schemaShape = headers._def.shape();

Expand Down
2 changes: 1 addition & 1 deletion src/openapi-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export type RouteConfig = Omit<OperationObject, 'responses'> & {
headers?: RouteParameter | ZodType<unknown>[];
};
responses: {
[statusCode: string]: ResponseConfig;
[statusCode: string]: ResponseConfig | ReferenceObject;
};
};

Expand Down

0 comments on commit 1160af8

Please sign in to comment.