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

feat(fromOpenApi): respect the "Accept" request header #17

Merged
merged 1 commit into from
Jan 24, 2022
Merged
Show file tree
Hide file tree
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
24 changes: 19 additions & 5 deletions src/fromOpenApi/fromOpenApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { invariant } from 'outvariant'
import { datatype, internet, random } from 'faker'
import { headersToObject } from 'headers-utils'
import { randexp } from 'randexp'
import {
RestContext,
Expand Down Expand Up @@ -147,10 +148,23 @@ function createResponseResolver(
if ('content' in response && response.content != null) {
let body: unknown

const explicitContentType = req.url.searchParams.get('type')
const contentType = explicitContentType
? explicitContentType
: Object.keys(response.content)[0]
const requestHeaders = headersToObject(req.headers)
const acceptedMimeTypes = ([] as string[]).concat(requestHeaders.accept)
const explicitContentType = acceptedMimeTypes[0]
const explicitContentTypeRegexp = new RegExp(
explicitContentType.replace(/\/+/g, '\\/').replace(/\*/g, '.+?'),
)

const allContentTypes = Object.keys(response.content)

const contentType =
allContentTypes.find((contentType) => {
// Find the first declared response content type
// that matches the "Accept" request header.
// Keep in mind that values like "*/*" and "application/*"
// are completely valid.
return explicitContentTypeRegexp.test(contentType)
}) || allContentTypes[0]

transformers.push(ctx.set('Content-Type', contentType))

Expand All @@ -167,7 +181,7 @@ function createResponseResolver(
mediaTypeObject.examples,
)[0] as OpenAPIV3.ExampleObject

// Response body must always be string.
// Response body must always be a string.
body = value
}
// JSON Schema is populated with random values.
Expand Down
50 changes: 50 additions & 0 deletions test/oas/oas-json-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,53 @@ it('responds with 501 to a request for explicit non-existing response status', a
expect(await res.text()).toEqual('')
})
})

it('respects the "Accept" request header', async () => {
const handlers = await fromOpenApi(
createOpenApiSpec({
paths: {
'/user': {
get: {
responses: {
200: {
content: {
'application/json': {
example: { id: 'user-1' },
},
'application/xml': {
example: `<id>xml-1</id>`,
},
},
},
},
},
},
},
}),
)

// The "Accept" request header with a single value.
await withHandlers(handlers, () => {
return fetch('http://localhost/user', {
headers: {
Accept: 'application/xml',
},
})
}).then(async (res) => {
expect(res.status).toEqual(200)
expect(await res.text()).toEqual(`<id>xml-1</id>`)
})

// The "Accept" request header with multiple values.
await withHandlers(handlers, () => {
return fetch('http://localhost/user', {
headers: {
Accept: 'application/json, application/xml',
},
})
}).then(async (res) => {
expect(res.status).toEqual(200)
// The first MimeType is used for the mocked data.
expect(await res.text()).toEqual(`{"id":"user-1"}`)
})
})