我想使用 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必須在使用此背景關系的每個請求中定義型別。有沒有更好的辦法?
uj5u.com熱心網友回復:
您可以覆寫 expressRequest介面以包含您的context屬性。這樣您就不必在任何地方指定型別。它還將保留Request通常具有的所有其他屬性。
declare global {
namespace Express {
interface Request {
context: RequestContext
}
}
}
我建議不要使用該Request物件來存盤資訊。Express 建議使用res.locals屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312237.html
標籤:javascript 节点.js 打字稿 表达 依赖注入
