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: send 204 response if null is returned from handler #154

Merged
merged 7 commits into from
Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
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 (type === 'object' && val.buffer) {
pi0 marked this conversation as resolved.
Show resolved Hide resolved
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 () => {
app.use('/number', () => 42)
expect(await request.get('/number').then(r => r.body)).toEqual(42)

app.use('/bool', () => true)
pi0 marked this conversation as resolved.
Show resolved Hide resolved
expect(await request.get('/bool').then(r => r.body)).toEqual(true)
})

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