如何重构具有子查询有点不同的查询

时间:2018-10-18 10:48:44

标签: node.js typescript nestjs typeorm

我正在尝试重构有效的代码,但时间太长... 以下两个函数几乎具有相同的查询,我只是在第二个函数中添加一个条件以获取created_at。

/**
 * Get cashiers by merchant
 * @param {OutletsEntity} outlets
 * @param u_name - first name or last name of user
 * @returns query sql
 */
public queryCashiersCount(outlets: OutletsEntity[], u_name) {
    // Get cashiers by merchant
    let query = this.userRepository.createQueryBuilder('user')
        .where(qb => {
            const subQuery = qb.subQuery()
                .select('outlet_roles.user_id')
                .from(OutletRoleEntity, 'outlet_roles')
                .where('outlet_roles.outlet_id IN (:outlet_ids)')
                .getQuery();
            return 'user.id IN ' + subQuery;
        })
        .setParameter('outlet_ids', outlets.map((outlet) => outlet.id));
    if (u_name) {
        query.where('user.first_name like :name OR user.last_name like :name', {name: '%' + u_name + '%'})
    }
    return query;
}

/**
 * Get cashiers by merchant
 * @param {OutletsEntity} outlets
 * @param u_name - first name or last name of user
 * @param created_date - pagination last user created at
 * -- example (1538327889000) timestamp || (2018-09-28T17:18:11.000Z) ISOString - isvalid() => true
 * @returns query sql
 */
public queryCashiersByCreation(outlets: OutletsEntity[], u_name, created_date, option) {
    // const extra_query = created_date ? `user.created_at < ${created_date}` : 'user.created_at IS NOT NULL';

    // Get cashiers by merchant
    let query = this.userRepository.createQueryBuilder('user')
        .where(qb => {
            const subQuery = qb.subQuery()
                .select('outlet_roles.user_id')
                .from(OutletRoleEntity, 'outlet_roles')
                .where('outlet_roles.outlet_id IN (:outlet_ids)')
                // .andWhere(':extra_query', {extra_query: extra_query})
                .andWhere('user.created_at < :created_date', {created_date})
                .getQuery();
            return 'user.id IN ' + subQuery;
        })
        .setParameter('outlet_ids', outlets.map((outlet) => outlet.id))
        // .setParameter('extra_query', extra_query)
        .orderBy('user.created_at', 'DESC');
    if (u_name !== undefined) {
        query.where('user.first_name like :name OR user.last_name like :name', {name: '%' + u_name + '%'})
    }
    return query;
}

我在想将查询提取到另一个函数subQueryForCashiers中,该函数将被其他两个函数中的每个调用。但是我被卡住了,因为如果我尝试在queryCashiersCount中进行操作,它将返回我所有出纳员,而没有考虑到outlet_id

.setParameter('outlet_ids', outlets.map((outlet) => outlet.id));

对于queryCashiersByCreation,我无法在subQuery中添加第二个条件

.andWhere('user.created_at < :created_date', {created_date})

有人知道我该怎么做吗?

0 个答案:

没有答案