Bal*_*des 1 javascript dependency-injection node.js express typescript
我想使用 Express 和 TypeScript 向所有请求处理程序公开一个值。我希望能够从中间件(或其他方式)“注入”这个值,重点是应该很容易模拟它,以防万一我需要。
我想出了这个解决方案:
// The context type, I'd like to be able to inject this using the middleware below.
// In a real scenario think of this like a database connection, etc.
type RequestContext = {
foo: string
}
// The type enriching the Request type with the context field
type HasContext = {
context: RequestContext
}
// Middleware attaching the context to the request
const contextMiddleware =
(context: RequestContext) =>
(req: Request & Partial<HasContext>, _res: Response, next: NextFunction) => {
req.context = context
next()
}
// Now an actual route using the extra type
const mainRoute = express.Router().get('/test', (req: Request & HasContext, res) => {
res.json({ context: req.context })
})
// Adding the middlewares and listen
app.use(contextMiddleware({ foo: 'bar' }))
app.use(mainRoute)
app.listen(8000)
Run Code Online (Sandbox Code Playgroud)
我的问题:
Request & HasContext必须在使用此上下文的每个请求中定义该类型。有没有更好的办法?您可以覆盖快速Request接口以包含您的context属性。这样您就不必在任何地方指定类型。它还将保留Request通常具有的所有其他属性。
declare global {
namespace Express {
interface Request {
context: RequestContext
}
}
}
Run Code Online (Sandbox Code Playgroud)
我建议不要使用该Request对象来存储信息。Express 建议使用res.locals属性。
| 归档时间: |
|
| 查看次数: |
6837 次 |
| 最近记录: |