gid-oss / dataui-nestjs-crud

NestJs CRUD for RESTful APIs
https://github.com/nestjsx/crud/wiki
MIT License
116 stars 29 forks source link

Tips: How to add customized filter conditions from backend service. #50

Open zgldh opened 2 months ago

zgldh commented 2 months ago

Sometimes your system need to add filter conditions after the HTTP request parsed.
For example you would like to filter records by current login user ID.

You would be like to do it as following:

public async getRecordsByUserId(req: CrudRequest, userId: number) {
    req.parsed.join.push({
      field: 'user',
    });
    const builder = await this.createBuilder(req.parsed, req.options, true);
    builder.andWhere('User.id = :userId', { userId });
    return this.doGetMany(builder, req.parsed, req.options);
}
zaro commented 2 months ago

@zgldh Thanks for the tip.

I am curious, is the @CrudAuth decorator not working for you ? Something like :

@CrudAuth({
  property: 'user',
  filter: (user: CurrentUser) => {
      return { 'User.id': { $eq: user.id } };
  },
})
@Controller(CONTROLLER_PATH)
export class SomeController {
}

This assumes that your currently logged in user is available in the user property of the request.

zgldh commented 2 months ago

Hi @zaro , that's a good solution.

For my use case, we may not need to perform a filter for all actions of a controller. Thus why I did it like that. But thanks anyway.