Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add search support to graphQl query #118

Merged
merged 7 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/api/src/modules/notifications/dtos/query-options.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,9 @@ export class QueryOptionsDto {
@Field(() => [UniversalFilter], { nullable: true })
@IsOptional()
filters?: UniversalFilter[];

@Field(() => String, { nullable: true })
@IsOptional()
@IsString()
search?: string;
}
85 changes: 56 additions & 29 deletions apps/api/src/modules/notifications/notifications.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Equal, FindManyOptions, LessThan, Like, MoreThan, Not, Repository } from 'typeorm';
import { Brackets, Repository } from 'typeorm';
import { Notification } from './entities/notification.entity';
import {
DeliveryStatus,
Expand Down Expand Up @@ -103,58 +103,85 @@ export class NotificationsService {
},
});
}

async getAllNotifications(options: QueryOptionsDto): Promise<NotificationResponse> {
this.logger.log('Getting all active notifications with options');

const whereConditions = { status: Status.ACTIVE };
const queryBuilder = this.notificationRepository.createQueryBuilder('notification');

// Base where condition
queryBuilder.where('notification.status = :status', { status: Status.ACTIVE });

// Search functionality using OR condition
if (options.search) {
const searchableFields = ['createdBy', 'data', 'result'];
queryBuilder.andWhere(
new Brackets((qb) => {
searchableFields.forEach((field, index) => {
const condition = `notification.${field} LIKE :search`;

if (index === 0) {
qb.where(condition, { search: `%${options.search}%` });
} else {
qb.orWhere(condition, { search: `%${options.search}%` });
}
});
}),
);
}

// Applying filters
let filterIndex = 0;
options.filters?.forEach((filter) => {
const field = filter.field;
const value = filter.value;
const condition = `notification.${field}`;
const paramName = `value${filterIndex}`; // Unique parameter name issue: https://github.com/typeorm/typeorm/issues/3428

switch (filter.operator) {
case 'eq':
whereConditions[field] = Equal(value);
break;
case 'ne':
whereConditions[field] = Not(Equal(value));
queryBuilder.andWhere(`${condition} = :${paramName}`, { [paramName]: value });
break;
case 'contains':
if (typeof value === 'string') {
whereConditions[field] = Like(`%${value}%`);
queryBuilder.andWhere(`${condition} LIKE :${paramName}`, { [paramName]: `%${value}%` });
}

break;
case 'gt':
if (this.isDateField(field)) {
whereConditions[field] = MoreThan(new Date(value));
} else {
whereConditions[field] = MoreThan(value);
}

queryBuilder.andWhere(`${condition} > :${paramName}`, {
[paramName]: this.isDateField(filter.field) ? new Date(String(value)) : value,
});
break;
case 'lt':
if (this.isDateField(field)) {
whereConditions[field] = LessThan(new Date(value));
} else {
whereConditions[field] = LessThan(value);
}

queryBuilder.andWhere(`${condition} < :${paramName}`, {
[paramName]: this.isDateField(filter.field) ? new Date(String(value)) : value,
});
break;
case 'ne':
queryBuilder.andWhere(`${condition} != :${paramName}`, { [paramName]: value });
break;
}

filterIndex++;
});

const queryOptions: FindManyOptions<Notification> = {
where: whereConditions,
skip: options.offset,
take: options.limit,
order: options.sortBy
? { [options.sortBy]: options.sortOrder === SortOrder.ASC ? SortOrder.ASC : SortOrder.DESC }
: undefined,
};
// Pagination and Sorting
if (options.offset !== undefined) {
queryBuilder.skip(options.offset);
}

if (options.limit !== undefined) {
queryBuilder.take(options.limit);
}

if (options.sortBy) {
queryBuilder.addOrderBy(
`notification.${options.sortBy}`,
options.sortOrder === SortOrder.ASC ? SortOrder.ASC : SortOrder.DESC,
);
}

const [notifications, total] = await this.notificationRepository.findAndCount(queryOptions);
const [notifications, total] = await queryBuilder.getManyAndCount();

return { notifications, total, offset: options.offset, limit: options.limit };
}
Expand Down
Loading