在自定义验证内部访问时,参数属性为null



我有一个自定义验证,可以访问contextparameter属性,但值始终是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上下文值(如queryheadersbody(中提取的值的列表。作为一种解决方法,可以从ctx属性访问参数的原始数据,例如ctx.request.queryctx.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
//
})
}

最新更新