53. middleware を作る
シェアしよう
少し工夫が必要 - accepted / - tried
Express Middleware を使ったことありますか?
Middleware関数は同じインタフェースを持ち、順番通りに実行される。
app.use('/user/:id', function (req, res, next) {
next()
}, function (req, res, next) {
next(new Error('sth wrong'))
})
なのでMiddleware Systemを実装してください!
type Request = object
type NextFunc = (error?: any) => void
type MiddlewareFunc =
(req: Request, next: NextFunc) => void
type ErrorHandler =
(error: Error, req: Request, next: NextFunc) => void
class Middleware {
use(func: MiddlewareFunc | ErrorHandler) {
// do any async operations
// call next() to trigger next function
}
start(req: Request) {
// trigger all functions with a req object
}
}
上記の実装終わったら、Expressのような使い方が可能になる。
const middleware = new Middleware()
middleware.use((req, next) => {
req.a = 1
next()
})
middleware.use((req, next) => {
req.b = 2
next()
})
middleware.use((req, next) => {
console.log(req)
})
middleware.start({})
// {a: 1, b: 2}
use()
がErrorHandlerをサポートするのにご注意ください。ErrorHandlerに三つの引数があり、Middleware 関数の中にエラーが発生する時、またはnext()
に引数が渡されるときに実行される。
const middleware = new Middleware()
// throw an error at first function
middleware.use((req, next) => {
req.a = 1
throw new Error('sth wrong')
// or `next(new Error('sth wrong'))`
})
// since error occurs, this is skipped
middleware.use((req, next) => {
req.b = 2
})
// since error occurs, this is skipped
middleware.use((req, next) => {
console.log(req)
})
// since error occurs, this is called
middleware.use((error, req, next) => {
console.log(error)
console.log(req)
})
middleware.start({})
// Error: sth wrong
// {a: 1}
関連するリスト
Ideas and Concepts