node.js - 如果加载 Typeorm 后满足条件,则返回空对象
问题描述
我有以下代码,如果满足条件,我希望它返回一个空对象。我不能作为查找的条件,因为我希望它自动应用于我拥有的每个实体。
该对象已停用,我希望在执行加载后的函数时返回一个空对象,而不是返回该对象
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];
}
}
}
}