Nestjsx/crud + typeorm + postgres - 仅在满足特定条件时过滤

时间:2021-06-04 18:08:59

标签: postgresql nestjs typeorm

我在我的用户控制器上使用这些过滤器,它们工作得很好。但是现在系统只在用户不是超级用户时才需要应用其中一些过滤器。我如何使用过滤器属性来检查用户是否是 su?实际代码如下:

@Crud({
    model: {
        type: User,
    },
    routes: {
        createOneBase: {
            returnShallow: true
        },
        updateOneBase: {
            returnShallow: true,
        },
        replaceOneBase: {
            returnShallow: true,
        },
        exclude: ['deleteOneBase', 'updateOneBase', 'createManyBase'],
    },
    params: {
        id: {
            field: 'id',
            type: 'number',
            primary: true,
        },
    },
    query: {
        join: {
            createdBy: { eager: true, exclude: ['password'] },
            updatedBy: { eager: true, exclude: ['password'] },
            members: { eager: true, alias: 'groups' },
            contacts: {eager: true, alias: 'contacts'},
            'members.group': { eager: true },
            userCompanies: { eager: true },
            'userCompanies.companyId': { eager: true }
        },
        filter: {
            exclude: {
                $eq: false,
            },
            'contacts.exclude': {
                $eq: false,
            },
            'userCompanies.exclude': {
                $eq: false,
            }
        },
        sort: [
            {
                field: 'id',
                order: 'ASC',
            }
        ]
    }
})

无论用户类型如何,都会应用的唯一一种是排除一种。

1 个答案:

答案 0 :(得分:0)

我自己使用 ParsedRequest 的覆盖方法解决了。

@Override('getManyBase')
async getMany(@ParsedRequest() req: CrudRequest, @UserReq() user: User) {
    if(!user.su) {
        req.parsed.filter.push({
            field: 'contacts.exclude',
            operator: '$eq',
            value: false
        },
        {
            field: 'userCompanies.exclude',
            operator: '$eq',
            value: false
        })
    }

    return await this.service.getMany(req);
}