Skip to content

Commit

Permalink
Set HTTP Content-Type header on JSON response
Browse files Browse the repository at this point in the history
  • Loading branch information
paulshryock committed Jul 24, 2024
1 parent bff273f commit 6dc0654
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/routes/api/contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,10 @@ export class Handler {
statusText: 'Bad Request',
}),
{
headers: new Headers(DEFAULT_HEADERS),
headers: new Headers({
...DEFAULT_HEADERS,
'Content-Type': 'application/json',
}),
status: 400,
},
)
Expand All @@ -134,7 +137,10 @@ export class Handler {
statusText: 'Bad Request',
}),
{
headers: new Headers(DEFAULT_HEADERS),
headers: new Headers({
...DEFAULT_HEADERS,
'Content-Type': 'application/json',
}),
status: 400,
},
)
Expand Down Expand Up @@ -171,7 +177,13 @@ export class Handler {
})
: response.statusText
return new Response(body, {
headers: new Headers({ ...DEFAULT_HEADERS, ...(response.headers ?? {}) }),
headers: new Headers({
...DEFAULT_HEADERS,
...(response.headers ?? {}),
...('bodyFields' in response
? { 'Content-Type': 'application/json' }
: {}),
}),
status: response.status,
})
}
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/routes/api/contact.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ describe(PATH, () => {
).not.toBeNull(),
)

it('should return json content', async () =>
expect(
(await handler(request, {} as Context)).headers.get('Content-Type'),
).toBe('application/json'))

it('should return an error message in the body', async () =>
expect(
await (await handler(request, {} as Context)).json(),
Expand Down Expand Up @@ -177,6 +182,16 @@ describe(PATH, () => {
await (await handler(request, {} as Context)).json(),
).toHaveProperty(property)
})

it('should return json content', async () => {
const request = new Request(ROUTE, { body, headers, method })

expect(
(await handler(request, {} as Context)).headers.get(
'Content-Type',
),
).toBe('application/json')
})
})

describe('when all required fields are valid', () => {
Expand Down Expand Up @@ -317,6 +332,16 @@ describe(PATH, () => {
},
)

it('should return json content', async () => {
const request = new Request(ROUTE, { body, headers, method })

expect(
(
await new Handler(storage).handle(request, {} as Context)
).headers.get('Content-Type'),
).toBe('application/json')
})

it('should return a message in the body', async () => {
const request = new Request(ROUTE, { body, headers, method })

Expand Down

0 comments on commit 6dc0654

Please sign in to comment.