From 3ca9baf72a21544833e19b3639f352dcb1b15232 Mon Sep 17 00:00:00 2001 From: Shawn Zhu Date: Wed, 12 Jul 2023 11:03:19 -0400 Subject: [PATCH] fix(PML-222): unexpected type in generated openapi spec --- src/openapi.test.ts | 24 ++++++++++++++++++++++++ src/openapi.ts | 21 ++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/openapi.test.ts b/src/openapi.test.ts index ca7f9bb..7ed9c38 100644 --- a/src/openapi.test.ts +++ b/src/openapi.test.ts @@ -29,6 +29,16 @@ const TEST_SPEC: OneSchemaDefinition = withAssumptions({ type: 'string', optional: true, }, + limit: { + description: 'page size', + type: 'integer', + optional: true, + }, + updatedAt: { + description: 'epoch time', + type: 'number', + optional: true, + }, }, }, Response: { @@ -132,6 +142,20 @@ describe('toOpenAPISpec', () => { required: false, schema: { type: 'string' }, }, + { + in: 'query', + description: 'page size', + name: 'limit', + required: false, + schema: { type: 'integer' }, + }, + { + in: 'query', + description: 'epoch time', + name: 'updatedAt', + required: false, + schema: { type: 'number' }, + }, ], responses: { '200': { diff --git a/src/openapi.ts b/src/openapi.ts index 73c2d4f..0361806 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -2,6 +2,7 @@ import type { OpenAPIV3 } from 'openapi-types'; import type { OneSchemaDefinition } from './types'; import { deepCopy } from './generate-endpoints'; import { validateSchema } from './meta-schema'; +import { JSONSchema4 } from 'json-schema'; /** * Converts e.g. `/users/:id/profile` to `/users/{id}/profile`. @@ -18,6 +19,24 @@ const getPathParameters = (koaPath: string) => .filter((part) => part.startsWith(':')) .map((part) => part.slice(1)); +/** + * @param schema json schema object + * @return supported openapi schema object type + */ +const getSchemaObjectType = ( + schema: JSONSchema4, +): OpenAPIV3.NonArraySchemaObjectType => { + // TODO supports more types from JSON schema + switch (schema.type) { + case 'integer': + return 'integer'; + case 'number': + return 'number'; + default: + return 'string'; + } +}; + export const toOpenAPISpec = ( schema: OneSchemaDefinition, config: { @@ -87,7 +106,7 @@ export const toOpenAPISpec = ( in: 'query', name, description: schema.description, - schema: { type: 'string' }, + schema: { type: getSchemaObjectType(schema) }, required: Array.isArray(Request.required) && Request.required.includes(name),