|
| 1 | +import { FilterQuery, Query } from 'mongoose'; |
| 2 | + |
| 3 | +class QueryBuilder<T> { |
| 4 | + public modelQuery: Query<T[], T>; |
| 5 | + public query: Record<string, unknown>; |
| 6 | + |
| 7 | + constructor(modelQuery: Query<T[], T>, query: Record<string, unknown>) { |
| 8 | + this.modelQuery = modelQuery; |
| 9 | + this.query = query; |
| 10 | + } |
| 11 | + |
| 12 | + //searching |
| 13 | + search(searchableFields: string[]) { |
| 14 | + if (this?.query?.searchTerm) { |
| 15 | + this.modelQuery = this.modelQuery.find({ |
| 16 | + $or: searchableFields.map( |
| 17 | + field => |
| 18 | + ({ |
| 19 | + [field]: { |
| 20 | + $regex: this.query.searchTerm, |
| 21 | + $options: 'i', |
| 22 | + }, |
| 23 | + } as FilterQuery<T>) |
| 24 | + ), |
| 25 | + }); |
| 26 | + } |
| 27 | + return this; |
| 28 | + } |
| 29 | + |
| 30 | + //filtering |
| 31 | + filter() { |
| 32 | + const queryObj = { ...this.query }; |
| 33 | + const excludeFields = ['searchTerm', 'sort', 'page', 'limit', 'fields']; |
| 34 | + excludeFields.forEach(el => delete queryObj[el]); |
| 35 | + |
| 36 | + this.modelQuery = this.modelQuery.find(queryObj as FilterQuery<T>); |
| 37 | + return this; |
| 38 | + } |
| 39 | + |
| 40 | + //sorting |
| 41 | + sort() { |
| 42 | + let sort = (this?.query?.sort as string) || '-createdAt'; |
| 43 | + this.modelQuery = this.modelQuery.sort(sort); |
| 44 | + |
| 45 | + return this; |
| 46 | + } |
| 47 | + |
| 48 | + //pagination |
| 49 | + paginate() { |
| 50 | + let limit = Number(this?.query?.limit) || 10; |
| 51 | + let page = Number(this?.query?.page) || 1; |
| 52 | + let skip = (page - 1) * limit; |
| 53 | + |
| 54 | + this.modelQuery = this.modelQuery.skip(skip).limit(limit); |
| 55 | + |
| 56 | + return this; |
| 57 | + } |
| 58 | + |
| 59 | + //fields filtering |
| 60 | + fields() { |
| 61 | + let fields = |
| 62 | + (this?.query?.fields as string)?.split(',').join(' ') || '-__v'; |
| 63 | + this.modelQuery = this.modelQuery.select(fields); |
| 64 | + |
| 65 | + return this; |
| 66 | + } |
| 67 | + |
| 68 | + //populating |
| 69 | + populate(populateFields: string[], selectFields: Record<string, unknown>) { |
| 70 | + this.modelQuery = this.modelQuery.populate( |
| 71 | + populateFields.map(field => ({ |
| 72 | + path: field, |
| 73 | + select: selectFields[field], |
| 74 | + })) |
| 75 | + ); |
| 76 | + return this; |
| 77 | + } |
| 78 | + |
| 79 | + //pagination information |
| 80 | + async getPaginationInfo() { |
| 81 | + const total = await this.modelQuery.model.countDocuments( |
| 82 | + this.modelQuery.getFilter() |
| 83 | + ); |
| 84 | + const limit = Number(this?.query?.limit) || 10; |
| 85 | + const page = Number(this?.query?.page) || 1; |
| 86 | + const totalPage = Math.ceil(total / limit); |
| 87 | + |
| 88 | + return { |
| 89 | + total, |
| 90 | + limit, |
| 91 | + page, |
| 92 | + totalPage, |
| 93 | + }; |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +export default QueryBuilder; |
0 commit comments