问题描述
我有以下代码,如果满足条件,我希望它返回一个空对象。我无法将其作为查找条件,因为我希望它在我拥有的每个实体中自动应用。
此对象已停用,我希望在执行加载后的函数时,它不会返回该对象,而是返回一个空对象
await this.Repository.find({where: {id: 4}}) // This Object Entity Is disabled
import { EventSubscriber,EntitySubscriberInterface } from 'typeorm';
@EventSubscriber()
export class BaseSubscriber implements EntitySubscriberInterface {
async afterLoad(entity) {
if (entity.disabled){
return {} //?
}
}
}
解决方法
欢迎来到 SO,首先,如果您不确定所有具有 disabled
的实体是否可以将每个实体设为特定订阅者,我建议您。
对于您的问题,您可以通过删除道具来做一个返回空对象的技巧:
以下是具有特定实体订阅者的示例:
@EventSubscriber()
export class UserSubscriber implements EntitySubscriberInterface<User> {
listenTo() {
return User;
}
/**
* Called after entity is loaded.
*/
afterLoad(entity: User) {
if(entity.disabled) {
for (const prop of Object.getOwnPropertyNames(entity)) {
delete entity[prop];
}
}
}
}