Skip to content

Commit

Permalink
feat: support multiple content type schemas per request (#819)
Browse files Browse the repository at this point in the history
  • Loading branch information
vivedo authored Sep 26, 2024
1 parent f29078c commit 03783d5
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 12 deletions.
31 changes: 19 additions & 12 deletions lib/spec/openapi/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,21 +263,28 @@ function schemaToMediaRecursive (schema) {

function resolveBodyParams (body, schema, consumes, ref) {
const resolved = convertJsonSchemaToOpenapi3(ref.resolve(schema))
if ((Array.isArray(consumes) && consumes.length === 0) || consumes === undefined) {
consumes = ['application/json']
}

const media = schemaToMediaRecursive(resolved)
consumes.forEach((consume) => {
body.content[consume] = media
})
if (resolved.content && resolved.content[Object.keys(resolved.content)[0]].schema) {
for (const contentType in schema.content) {
body.content[contentType] = schemaToMediaRecursive(resolved.content[contentType].schema)
}
} else {
if ((Array.isArray(consumes) && consumes.length === 0) || consumes === undefined) {
consumes = ['application/json']
}

if (resolved && resolved.required && resolved.required.length) {
body.required = true
}
const media = schemaToMediaRecursive(resolved)
consumes.forEach((consume) => {
body.content[consume] = media
})

if (resolved && resolved.required && resolved.required.length) {
body.required = true
}

if (resolved && resolved.description) {
body.description = resolved.description
if (resolved && resolved.description) {
body.description = resolved.description
}
}
}

Expand Down
67 changes: 67 additions & 0 deletions test/spec/openapi/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1034,3 +1034,70 @@ test('avoid overwriting params when schema.params is provided', async t => {
}
})
})

test('support multiple content types as request', async t => {
const opt = {
schema: {
body: {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
jsonProperty: {
type: 'string'
}
}
}
},
'application/xml': {
schema: {
type: 'object',
properties: {
xmlProperty: {
type: 'string'
}
}
}
}
}
}
}
}

const fastify = Fastify()
await fastify.register(fastifySwagger, {
openapi: true
})
fastify.post('/', opt, () => { })
await fastify.ready()

const swaggerObject = fastify.swagger()
const api = await Swagger.validate(swaggerObject)

const definedPath = api.paths['/'].post
t.match(definedPath.requestBody, {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
jsonProperty: {
type: 'string'
}
}
}
},
'application/xml': {
schema: {
type: 'object',
properties: {
xmlProperty: {
type: 'string'
}
}
}
}
}
})
})

0 comments on commit 03783d5

Please sign in to comment.