-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkoa-timeout.js
More file actions
31 lines (27 loc) · 840 Bytes
/
koa-timeout.js
File metadata and controls
31 lines (27 loc) · 840 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export default (time, { status = 408 } = {}) => (ctx, next) => {
let timer
const timeout = new Promise((resolve, reject) => {
timer = setTimeout(() => {
ctx.state.timeout = true
ctx.status = status
ctx.body = `Request timedout: ${time}ms`
reject(new Error(`Request timedout: ${time}ms`))
}, time)
})
const clear = clearTimeout.bind({}, timer)
return Promise
.race([ timeout, next() ])
.then(clear)
.catch((ex) => {
clear()
if (ctx.state.timeout) return ctx.throw(408, 'Request timeout')
throw ex
})
}
export const shortCircuit = (...middlewares) => {
const wrapped = middlewares.map(middleware => (ctx, next) => {
if (ctx.state && ctx.state.timeout) return
return middleware(ctx, next)
})
return middlewares.length === 1 ? wrapped[0] : wrapped
}