我正在尝试使用typescript在中间件中添加一个表示请求对象的属性。但是我无法弄清如何向该对象添加额外属性。如果可能,我希望不使用方括号表示。
我正在寻找一种解决方案,使我可以编写类似于以下内容的代码(如果可能):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
我正在尝试使用typescript在中间件中添加一个表示请求对象的属性。但是我无法弄清如何向该对象添加额外属性。如果可能,我希望不使用方括号表示。
我正在寻找一种解决方案,使我可以编写类似于以下内容的代码(如果可能):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
const auth = (req, res) => {
const user = // parse user from the header
if(!user)
return res.status(401).send({ result: 'unauthorized-error' })
req.user = user
return next()
}
app.get('/something', auth, (req, res) => {
// do something
})
const auth = (req) => {
return // parse user from the header
}
app.get('/something', (req, res) => {
const user = auth(req)
if(!user)
return res.status(401).send({ result: 'unauthorized-error' })
// do something
})
const auth = (req) => {
return // parse user from the header
}
const withUser = (callback: (foo, req, res) => void) => (req, res) => {
const user = auth(req)
if(!user)
return res.status(401).send({ result: 'unauthorized-error' })
return callback(user, req, res)
}
app.get('/something', withUser((user, req, res) => {
// do something
}))
const withFoo = (callback) => (req, res) => { /* ... */ }
const withBar = (callback) => (req, res) => { /* ... */ }
const withBaz = (callback) => (req, res) => { /* ... */ }
const withFooBarAndBaz = (callback) => (req,res) => {
withFoo((foo) =>
withBar((bar) =>
withBaz((baz) =>
callback({ foo, bar, baz }, req, res)
)(req,res)
)(req,res)
)(req,res)
}
app.get('/something', withFooBarAndBaz(({ foo, bar, baz }, req, res) => {
// do something with foo, bar and baz
}))
您可以使用语言代替不安全的变异来表达促进。
在我目前的解决方案之前,我使用了最初提出的方法来实现中间件,但有所不同的是我的身份验证函数会抛出错误,我可以捕获并返回正确的响应,所以我不需要在控制器中处理它。例如:
app.get('/something', withResponse((req) => {
const user = auth(req)
return success({
message: `Hi ${user.name}`
})
}))
(callback: (foo, req, res) => void) => (req, res) => {}
应该被理解为 (callback: (foo, req, res) => void) => ((req, res) => {})
吗?也就是说,这是一个接受 callback
并返回函数 (req, res) => {}
的函数? - Shuzheng只需将该属性添加到req.params对象中即可。
req.params.foo = "bar"