I am using NestJS, typeORM and MongoDB. I want to write search filters but i see that it is not as proper as I want to.
It is the request DTO SearchLessonDto.ts
:
export class SearchLessonDto {
@Column()
@Expose({ name: 'title' })
title: string;
@Column()
@Expose({ name: 'categories' })
@Transform(DecodeStringArray)
categories: number[];
@Column()
@Expose({ name: 'is_published' })
isPublished: string;
@Column()
@Expose({ name: 'type' })
type: LessonTypeEnum;
filters(): NonNullable<unknown> {
const lessonSearchFilter: LessonSearchFilter = new LessonSearchFilter();
if (this.title) lessonSearchFilter.title = { $regex: this.title };
if (Array.isArray(this.categories) && this.categories.length)
lessonSearchFilter.categories = { $in: this.categories };
if (this.isPublished !== undefined && this.isPublished !== null)
lessonSearchFilter.isPublished = this.isPublished === 'true';
if (this.type !== null && this.type !== undefined)
lessonSearchFilter.type = this.type;
return lessonSearchFilter;
}
}
class LessonSearchFilter {
title: Record<string, string>;
categories: Record<string, number[]>;
isPublished: boolean;
type: LessonTypeEnum;
}
and it is the findAll service function:
async findAll(
searchLessonDto: SearchLessonDto,
): Promise<LessonResponseDto[]> {
const lessons: Lesson[] = await this.lessonRepository.find({
where: searchLessonDto.filters(),
});
return lessons.map((lesson: Lesson) => lesson.toResponse());
}
I just want to you give feedback about what i did here, is it proper way to do it or there other ways?