如何使用 express 和 typescript 正确共享上下文
How do I properly share context using express and 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)
我的问题:
- 这是使用 express 执行此操作的预期方式吗?我搜索了 API 但找不到更好的解决方案
- 额外的数据已附加到请求中。有没有其他方法可以在不改变请求或响应本身的情况下做到这一点?
- 必须在使用此上下文的每个请求中定义类型
Request & HasContext
。有没有更好的方法?
您可以覆盖快速 Request
接口以包含您的 context
属性。这样您就不必在任何地方指定类型。它还将保留 Request
通常具有的所有其他属性。
declare global {
namespace Express {
interface Request {
context: RequestContext
}
}
}
我建议不要使用 Request
对象来存储信息。快递推荐使用res.locals属性.
我想使用 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)
我的问题:
- 这是使用 express 执行此操作的预期方式吗?我搜索了 API 但找不到更好的解决方案
- 额外的数据已附加到请求中。有没有其他方法可以在不改变请求或响应本身的情况下做到这一点?
- 必须在使用此上下文的每个请求中定义类型
Request & HasContext
。有没有更好的方法?
您可以覆盖快速 Request
接口以包含您的 context
属性。这样您就不必在任何地方指定类型。它还将保留 Request
通常具有的所有其他属性。
declare global {
namespace Express {
interface Request {
context: RequestContext
}
}
}
我建议不要使用 Request
对象来存储信息。快递推荐使用res.locals属性.