I have a situation in my backend. Using Nestjs along with typeorm, Following CQRS pattern in code.
I have various scenarios in codebase where I have to filter table and retrieve the data (entities). The problem is the filtering criteria is dynamic. E.g. I have a table college with fields (id uuid, name, address, speciality_field (mechanical, automobile, CS, Electrical), owner_group) etc Now there are various scenarios in code where I have to filter college entity with name, sometimes id, sometimes speciality_field + address.
Solutions I tried : Now i can create different query for each of the criteria and QueryHandler for each of those query
This will soon create a lot of queries in my codebase and make me loose track of them, giving birth to code redundancy or even dead code
Then I decided to come up with another solution which is having a single query handler but with flexible/ dynamic parameters as depicted below
query definition
export class GetCollegesQuery {
constructor(public readonly queryData : Record<string,any>[]){}
}
queryHandler
@QueryHandler(GetCollegesQuery)
export class GetCollegesQueryHandler implements IQueryHandler<GetCollegesQuery> {
async execute(query: GetCollegesQuery): Promise<any> {
const collegeRepository = dataSource.getRepository(College);
const colleges = await collegeRepository.find({
where : query.queryData
})
if (!colleges.length) {
return new NotFoundException();
}
return colleges;
}
}
sample usecase
@Get()
async getBranches(
@Query('speciality') speciality: string,
@Query('location') location: string,
){
return await this.queryBus.execute(new GetBranchesQuery([{speciality : speciality}, {location : address }]));
}
Question This is just something i came up with and not sure if this is the best way to solve it.
is there any design pattern or approach to tackle this ???