我有一个自定义验证,可以访问context
的parameter
属性,但值始终是undefined
。
这是我的代码:
function isValidVersion() {
return val.custom(async (val, i) => {
const appIdIdx = i.route.action.parameters.findIndex(x => x.name === "appId")
if (appIdIdx === -1)
throw new Error(`No appId parameter found in ${i.route.controller.name}.${i.route.action.name}`)
const appId = i.ctx.parameters![appIdIdx] //<--- the parameters is undefined
//other code
//
})
}
我该怎么解决?
parameters
值只有在验证过程完成后才可用,因为它是用净化/验证的值填充的。
所以,是的,您不能在验证过程中访问parameters
属性。
仅供参考,parameters
属性只是从http上下文值(如query
、headers
或body
(中提取的值的列表。作为一种解决方法,可以从ctx
属性访问参数的原始数据,例如ctx.request.query
或ctx.request.body
。
例如,如果从您的查询URL中提取的appId
,您的代码将简单地为:
function isValidVersion() {
return val.custom(async (val, i) => {
const appId = i.ctx.request.query.appid
if (!appId)
throw new Error(`No appId parameter found in ${i.route.controller.name}.${i.route.action.name}`)
//other code
//
})
}