Search code examples
javascriptsqlnode.jspostgresqltypeorm

Raw SQL in Typeorm Where Find Options


await this.newsRepository.findAndCount({
        select: {
          id: true,
          publishedAt: true,
          isDisplayed: true,
          priority: true,
          availableTo: true,
          availableFrom: true,
          useAvailablePeriod: true,
        },
        where: [
          {
            status: NewsStatus.PUBLISHED,
            newsCategories: { seoName: params.categorySeoName },
            useAvailablePeriod: true,
            availableFrom: `< ${new Date()} OR IS NULL`,
            availableTo: `> ${new Date()} OR IS NULL`,
            publishedAt: LessThanOrEqual(new Date()),
          },
          {
            status: NewsStatus.PUBLISHED,
            newsCategories: { seoName: params.categorySeoName },
            useAvailablePeriod: false,
            publishedAt: LessThanOrEqual(new Date()),
          },
        ],
        order: { publishedAt: 'DESC', priority: 'DESC' },
      });

How can I use a similar construction as shown with the availableFrom and availableTo parameters or something similar in order not to fill in a huge number of array elements in where.

I don't want to use Query Builder. Is there any way to get around Or without writing a huge amount of data to the where array?

I tried to write all these Or as elements of the where array, but then the where construction is too large.


Solution

  • From https://github.com/typeorm/typeorm/blob/master/docs/find-options.md

    import { Raw } from "typeorm"
    
    const loadedPosts = await dataSource.getRepository(Post).findBy({
        currentDate: Raw((alias) => `${alias} > :date`, { date: "2020-10-06" }),
    })
    

    will execute following query:

    SELECT * FROM "post" WHERE "currentDate" > '2020-10-06'