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

✨support file upload decorator #75

Closed
wants to merge 1 commit into from
Closed
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
48 changes: 38 additions & 10 deletions src/generateSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!]
Expand All @@ -213,27 +239,29 @@ 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 } =
'items' in bodySchema && bodySchema.items ? bodySchema.items : bodySchema

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 } },
}
}
}
Expand Down