用于在 nesjts 中进行验证的自定义装饰器 - 在服务层上
Custom decorator for validation in nesjts - on a service layer
我订阅了一个 nestjs 服务,它收到了兔子消息
@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)
}
上的示例
我订阅了一个 nestjs 服务,它收到了兔子消息
@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)
}
上的示例