expressify: Do not send response when already sent

This commit is contained in:
Jerko Steiner 2019-09-27 10:16:47 +07:00
parent a8d603dd59
commit ee29307e97
2 changed files with 29 additions and 8 deletions

View File

@ -26,24 +26,46 @@ describe('expressify', () => {
expressify(
createMiddleware(ctx => (ctx.req as any).id = 'test')))
app.get('/test', expressify(ctx => (ctx.req as any).id))
request(app)
await request(app)
.get('/test')
.expect(200)
.expect('"test"')
})
it('can send a response using a custom fn', () => {
it('can send a response using a custom fn', async () => {
const app = express()
app.use(
expressify(
createMiddleware(ctx => (ctx.req as any).id = 'test')))
app.get('/test',
expressify(ctx => (ctx.req as any).id, (res, value) => res.send(value)))
request(app)
await request(app)
.get('/test')
.expect(200)
.expect('test')
})
it('handles errors', async () => {
const app = express()
app.use(
expressify(
createMiddleware(ctx => { throw new Error('test') })))
await request(app)
.get('/test')
.expect(500)
})
it('does not crash nor hang when middleware sends a response', async () => {
const app = express()
app.use(
expressify(
createMiddleware(ctx => ctx.res.end('test'))))
await request(app)
.get('/test')
.expect(200)
.expect('test')
})
})
})

View File

@ -1,5 +1,4 @@
import { NextFunction, Request, Response } from 'express'
import { IncomingMessage, ServerResponse } from 'http'
import { Middleware } from './Middleware'
export const expressify = (
@ -13,9 +12,7 @@ export const expressify = (
) => {
let result: unknown
try {
const r: IncomingMessage = req
const rr: ServerResponse = res
result = await handleMiddleware({req: r, res: rr})
result = await handleMiddleware({req, res})
} catch (err) {
next(err)
return
@ -24,5 +21,7 @@ export const expressify = (
next()
return
}
sendResponse(res, result)
if (res.writable) {
sendResponse(res, result)
}
}