Skip to content

Commit

Permalink
feat(validator): check for json subtypes in validator (#2634)
Browse files Browse the repository at this point in the history
* check for json subtypes in validator

* formatting and deno_dist added

* review fix, string#match -> regexp#test

* format & lint
  • Loading branch information
ztiromoritz authored May 9, 2024
1 parent f7faf38 commit aebaa28
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
2 changes: 1 addition & 1 deletion deno_dist/validator/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const validator = <

switch (target) {
case 'json':
if (!contentType || !contentType.startsWith('application/json')) {
if (!contentType || !/^application\/([a-z-]+\+)?json/.test(contentType)) {
const message = `Invalid HTTP header: Content-Type=${contentType}`
throw new HTTPException(400, { message })
}
Expand Down
13 changes: 13 additions & 0 deletions src/validator/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,19 @@ describe('Malformed JSON', () => {
expect(res.status).toBe(400)
})

it('Should return 200 response, for request with Content-Type which is a subtype like application/merge-patch+json', async () => {
const res = await app.request('http://localhost/post', {
method: 'POST',
headers: {
'Content-Type': 'application/merge-patch+json',
},
body: JSON.stringify({
any: 'thing',
}),
})
expect(res.status).toBe(200)
})

it('Should return 400 response, if Content-Type header does not start with application/json', async () => {
const res = await app.request('http://localhost/post', {
method: 'POST',
Expand Down
2 changes: 1 addition & 1 deletion src/validator/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const validator = <

switch (target) {
case 'json':
if (!contentType || !contentType.startsWith('application/json')) {
if (!contentType || !/^application\/([a-z-]+\+)?json/.test(contentType)) {
const message = `Invalid HTTP header: Content-Type=${contentType}`
throw new HTTPException(400, { message })
}
Expand Down

0 comments on commit aebaa28

Please sign in to comment.