Skip to content

Commit 85b18a7

Browse files
committed
fix #64 with state detection after callback execution
1 parent c8c267d commit 85b18a7

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

index.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,12 @@ class API {
184184
if (mw[0].length > 0 && !matched) continue
185185

186186
// Promisify middleware
187-
await new Promise(r => {
188-
let rtn = mw[1](request,response,() => { r() })
187+
await new Promise(async r => {
188+
let rtn = await mw[1](request,response,() => { r() })
189189
if (rtn) response.send(rtn)
190+
if (response._state === 'done') r() // if state is done, resolve promise
190191
})
192+
191193
} // end for
192194

193195
// Execute the primary handler if in processing state
@@ -239,7 +241,7 @@ class API {
239241
if (response._state === 'processing') {
240242

241243
// Flag error state (this will avoid infinite error loops)
242-
response._state === 'error'
244+
response._state = 'error'
243245

244246
// Execute error middleware
245247
for (const err of this._errors) {

test/middleware.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,10 @@ api2.use('/test/testing',function(req,res,next) {
8686
next()
8787
})
8888

89+
api2.use('/test/error',function(req,res,next) {
90+
res.error(401,'Not Authorized')
91+
})
92+
8993

9094
api3.use(['/test','/test/:param1','/test2/*'],function(req,res,next) {
9195
req.testMiddlewareAll = true
@@ -166,6 +170,10 @@ api2.get('/test/:param1', function(req,res) {
166170
res.status(200).json({ method: 'get', middleware: req.testMiddleware ? true : false, middlewareWildcard: req.testMiddlewareWildcard ? true : false, middlewareParam: req.testMiddlewareParam ? true : false, middlewarePath: req.testMiddlewarePath ? true : false })
167171
})
168172

173+
api2.get('/test/error', function(req,res) {
174+
res.status(200).json({ message: 'should not get here' })
175+
})
176+
169177

170178
api3.get('/test', function(req,res) {
171179
res.status(200).json({ method: 'get', middleware: req.testMiddlewareAll ? true : false })
@@ -350,4 +358,13 @@ describe('Middleware Tests:', function() {
350358
}) // end it
351359

352360

361+
it('Trigger error in middleware', async function() {
362+
let _event = Object.assign({},event,{ path: '/test/error' })
363+
let result = await new Promise(r => api2.run(_event,{},(e,res) => { r(res) }))
364+
expect(result).to.deep.equal({
365+
headers: { 'content-type': 'application/json' },
366+
statusCode: 401, body: '{"error":"Not Authorized"}', isBase64Encoded: false })
367+
}) // end it
368+
369+
353370
}) // end MIDDLEWARE tests

0 commit comments

Comments
 (0)