nestjsx / crud

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

Filter Date on DateTime #703

Open sonif opened 3 years ago

sonif commented 3 years ago

Hi,

I have problem filtering date. Can you give me example how to use filter Date on column DateTime (Ex : createdAt) ? I use $between or $cont it doesn't work for me

filter=createdAt||$cont||2021-05-02

SvaRgoS commented 3 years ago

I have the same question

Ripper346 commented 2 years ago

Did you solve this? From inspecting the query made I saw that the date passed is called with a toString. If I send 2021-10-30 I get in the query date LIKE '%Sat Oct 30 2021 02:00:00 GMT+0200 (Ora legale dell’Europa centrale)%' (my system is in italian)

EDIT: for anyone who lands here like me. My very ugly solution I came with requires the override like in this example:

export class OrdersController implements CrudController<Order> {
  constructor(
    public service: OrdersService,
  ) { }

  get base(): CrudController<Order> {
    return this;
  }

  @Override()
  async getMany(@ParsedRequest() req: CrudRequest): Promise<GetManyDefaultResponse<Order> | Order[]> {
    function search(searches) {
      if (searches.$and)
        search(searches.$and);
      if (searches.$or)
        search(searches.$or);
      if (Array.isArray(searches))
        searches.forEach(filter => {
          Object.keys(filter).filter(col => dateProp.includes(col)).forEach(col => {
            Object.keys(filter[col]).forEach(condition => {
              try {
                filter[col][condition] = moment(new Date(filter[col][condition])).format('YYYY-MM-DD');
              }
              catch { }
            });
          });
        });
    }
    let dateProp = ['date', 'createdAt', 'updatedAt'];
    search(req.parsed.search);
    return this.base.getManyBase(req);
  }
}

This converts all the properties of the entity that I defined in dateProp in the format that the db likes. If there is a more elegant solution I would like to know it. I tried to use class-transformer in the entity but the filters don't use them.