Skip to content

Commit

Permalink
feat: send 204 response if null is returned from handler (#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Aug 1, 2022
1 parent cb5f096 commit dbd465f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,11 @@ export function createAppEventHandler (stack: Stack, options: AppOptions) {
return send(event, val, MIMES.html)
} else if (isStream(val)) {
return sendStream(event, val)
} else if (val === null) {
event.res.statusCode = 204
return send(event)
} else if (type === 'object' || type === 'boolean' || type === 'number' /* IS_JSON */) {
if (val && (val as Buffer).buffer) {
if (val.buffer) {
return send(event, val)
} else if (val instanceof Error) {
throw createError(val)
Expand Down
2 changes: 1 addition & 1 deletion src/utils/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { MIMES } from './consts'

const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn: Function) => fn()

export function send (event: CompatibilityEvent, data: any, type?: string): Promise<void> {
export function send (event: CompatibilityEvent, data?: any, type?: string): Promise<void> {
if (type) {
defaultContentType(event, type)
}
Expand Down
17 changes: 17 additions & 0 deletions test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@ describe('app', () => {
expect(res.body).toEqual({ url: '/' })
})

it('can return a 204 response', async () => {
app.use('/api', () => null)
const res = await request.get('/api')

expect(res.statusCode).toBe(204)
expect(res.text).toEqual('')
expect(res.ok).toBeTruthy()
})

it('can return primitive values', async () => {
const values = [true, false, 42, 0, 1]
for (const value of values) {
app.use(`/${value}`, () => value)
expect(await request.get(`/${value}`).then(r => r.body)).toEqual(value)
}
})

it('can return Buffer directly', async () => {
app.use(() => Buffer.from('<h1>Hello world!</h1>', 'utf8'))
const res = await request.get('/')
Expand Down

0 comments on commit dbd465f

Please sign in to comment.