Search code examples
nestjstypeormnode.js-typeorm

typeOrm using condition in where clause


@Injectable()

export class WeightPriceService { constructor(readonly dbContext: DbContext) {}

async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
    const { price } = await this.dbContext.tariffs.findOne({
        where: {
            type: tariffType ? tariffType : ,
            isActive: true,
            weight: { min: LessThan(weight), max: MoreThan(weight) },
        },
        relations: ['weight'],
    });


    return price;
}

}

Is "tariffType" parameter is true I would like to check "type:tariffType" else do not want to check "type"


Solution

  • You can use the spread operator for this.

    const obj = {
      ...(true && {my: 'obj'})
    };
    

    const truly = 1 === 1;
    const falsy = 1 !== 1;
    
    const myObject = {
      foo: 'bar',
      ...(truly && {my: 'data'}),
      ...(falsy && {other: 'data'}),
      something: 'else'
    };
    
    console.log(myObject);

    When the condition is True it will inject the object otherwise wouldn't add anything.

    In your case it would be

    async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
        const { price } = await this.dbContext.tariffs.findOne({
            where: {
                ...(tariffType && { type: tariffType }),
                isActive: true,
                weight: { min: LessThan(weight), max: MoreThan(weight) },
            },
            relations: ['weight'],
        });
    
    
        return price;
    }