From 829b6db4d8114919fcb3e23d57ec855d7f6e88b4 Mon Sep 17 00:00:00 2001 From: pondpiu Date: Wed, 5 May 2021 01:57:21 +0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8support=20file=20upload=20decorator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/generateSpec.ts | 48 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/src/generateSpec.ts b/src/generateSpec.ts index e15602c..cdbbd48 100644 --- a/src/generateSpec.ts +++ b/src/generateSpec.ts @@ -191,19 +191,45 @@ export function getQueryParams( return queries } +function getNamedParamSchema( + param: ParamMetadataArgs +): oa.SchemaObject | oa.ReferenceObject { + const { type } = param + if (type === 'file') { + return { type: 'string', format: 'binary' } + } + if (type === 'files') { + return { + type: 'array', + items: { + type: 'string', + format: 'binary', + }, + } + } + return getParamSchema(param) +} + /** * Return OpenAPI requestBody of given route, if it has one. */ export function getRequestBody(route: IRoute): oa.RequestBodyObject | void { const bodyParamMetas = route.params.filter((d) => d.type === 'body-param') - const bodyParamsSchema: oa.SchemaObject | null = - bodyParamMetas.length > 0 - ? bodyParamMetas.reduce( + + const uploadFileMetas = route.params.filter((d) => + ['file', 'files'].includes(d.type) + ) + + const namedParams = [...bodyParamMetas, ...uploadFileMetas] + + const namedParamsSchema: oa.SchemaObject | null = + namedParams.length > 0 + ? namedParams.reduce( (acc: oa.SchemaObject, d) => ({ ...acc, properties: { ...acc.properties, - [d.name!]: getParamSchema(d), + [d.name!]: getNamedParamSchema(d), }, required: isRequired(d, route) ? [...(acc.required || []), d.name!] @@ -213,8 +239,10 @@ export function getRequestBody(route: IRoute): oa.RequestBodyObject | void { ) : null - const bodyMeta = route.params.find((d) => d.type === 'body') + const contentType = + uploadFileMetas.length > 0 ? 'multipart/form-data' : 'application/json' + const bodyMeta = route.params.find((d) => d.type === 'body') if (bodyMeta) { const bodySchema = getParamSchema(bodyMeta) const { $ref } = @@ -222,18 +250,18 @@ export function getRequestBody(route: IRoute): oa.RequestBodyObject | void { return { content: { - 'application/json': { - schema: bodyParamsSchema - ? { allOf: [bodySchema, bodyParamsSchema] } + [contentType]: { + schema: namedParamsSchema + ? { allOf: [bodySchema, namedParamsSchema] } : bodySchema, }, }, description: ($ref || '').split('/').pop(), required: isRequired(bodyMeta, route), } - } else if (bodyParamsSchema) { + } else if (namedParamsSchema) { return { - content: { 'application/json': { schema: bodyParamsSchema } }, + content: { [contentType]: { schema: namedParamsSchema } }, } } }