Using Where Conditions

In many applications, there arises a need to construct dynamic queries to filter data from a database. The Where class provides a powerful tool for composing such queries. Let's walk through how to use it effectively.

1. Initializing Where

First, import the Where class into your file:

import { Where } from "@soapjs/soap";

Then, instantiate a new Where object:

const where = new Where();

2. Adding Conditions

You can add conditions to the Where object using various methods like isEq, isNotEq, isLt, isLte, isGt, isGte, isIn, isNotIn, and like.

where.valueOf("name").isEq("John");
where.valueOf("age").isGt(25).and.valueOf("status").isEq("active");

3. Combining Conditions

You can combine conditions using logical operators like and and or.

where.valueOf("age").isGt(25).or.valueOf("age").isLt(18);
where.valueOf("status").isEq("active").and.brackets((w) => {
    w.valueOf("age").isGt(25).or.valueOf("age").isLt(18);
});

4. Building the Condition

Once you've added all the desired conditions, you can build the final condition using the build method:

const condition = where.build();

Example Usage

Let's consider a scenario where we want to find all active customers aged between 18 and 30.

const where = new Where()
    .valueOf("status").isEq("active")
    .and.valueOf("age").isGte(18).and.valueOf("age").isLte(30);

const repository = ioc.get<CustomerRepository>(CustomerRepository.Token);
const params = new FindParams(100, 0, null, where);
const result = await repository.find(params);

Conclusion

The Where class offers a flexible and intuitive way to compose dynamic queries in TypeScript. By leveraging its methods for adding and combining conditions, you can easily construct complex filters for querying your data.

Last updated