如何解决用于在nesjts中进行验证的自定义装饰器-在服务层上
我有一个Nest兔子服务订阅,收到兔子消息
@RabbitSubscribe({
exchange: 'test'.
routingKey: 'test',queue: 'q'
})
async handleEvent( msg: msgModel) {
console.log(message)
}
我有很多这样的订户,并且我想像通过validationPipe()在控制器中一样来验证此模型
但是validationPipe()或guard无法在简单服务上运行
所以我想创建一个自定义装饰器,它将获取消息并对其进行验证
像:
@CustomDec(msg)
@RabbitSubscribe({
exchange: 'test'.
routingKey: 'test',queue: 'q'
})
async handleEvent( msg: msgModel) {
console.log(message)
}
or
@RabbitSubscribe({
exchange: 'test'.
routingKey: 'test',queue: 'q'
})
async handleEvent( @customDec() msg: msgModel) {
console.log(message)
}
有可能这样做吗?
解决方法
使用method-decorator应该很简单。像这样:
function MsgValidator(target: any,propertyKey: string,descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const msgModel = args[0];
console.log("validating msg ...");
if(msgModel.message === "isExpectedMessage") {
console.log("OK")
}else {
console.log("NOK")
}
return originalMethod.apply(this,args);
}
}
用于:
@RabbitSubscribe({
exchange: 'test'.
routingKey: 'test',queue: 'q'
})
@MsgValidator
async handleEvent(msg: msgModel) {
console.log(msg)
}
上的示例版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。