【问题标题】:Return empty object if the condition is met after loading Typeorm如果加载 Typeorm 后满足条件,则返回空对象
【发布时间】:2021-02-04 05:04:43
【问题描述】:

我有以下代码,如果满足条件,我希望它返回一个空对象。我无法将其作为查找条件,因为我希望它自动应用于我拥有的每个实体。

此对象已停用,我希望在执行加载后的函数时返回一个空对象,而不是返回该对象

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 {} //?
        }
    }
}

【问题讨论】:

    标签: node.js typeorm node.js-typeorm


    【解决方案1】:

    欢迎来到 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];
                  }
            }        
        }
    
    }
    

    【讨论】:

    • 这很好,在返回空对象时有效,但我认为返回空对象不会将其添加到结果列表中,这是我的客户实体查询结果的示例customers = [Client {id: 1 ....}, Client {id: 3 ....}, Client {}] 如果它被禁用,如何防止它被添加到结果列表中?
    • 您的问题很明确,即返回一个空对象,对于当前的问题,您为什么不将其添加到查询await this.Repository.find({where: {id: 4,disabled:true}}) 它会给您想要的结果
    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多