import { HttpError } from "@lib/error-handling/http-error"; import { populate } from "dotenv"; import { AnyKeys, Document, FilterQuery, Model } from "mongoose"; export const CrudService = ( model: Model ) => { return class CrudServiceClass { protected model: Model = model; async create(data: AnyKeys): Promise { return this.model.create(data); } async update( filter: FilterQuery, data: AnyKeys ): Promise { return this.model.findOneAndUpdate(filter, data, { new: true }); } async delete(filter: FilterQuery): Promise { return this.model.findOneAndDelete(filter); } async list( filter: FilterQuery, paginationOptions: { limit?: number; skip?: number; } = { limit: 10, skip: 0, }, options?: { populateObject: any } ): Promise<{ docs: ModelDoc[]; paginationData: { total: number; page: number; perPage: number; }; }> { const queryInstruction = this.model .find(filter) .limit(paginationOptions.limit) .skip(paginationOptions.skip) if (options?.populateObject) queryInstruction.populate(options.populateObject); const docs = await queryInstruction const total = await this.model.countDocuments(filter); const paginationData = { total: total, page: paginationOptions.skip, perPage: paginationOptions.limit, }; return { docs, paginationData }; } async findOne(filter: FilterQuery): Promise { return this.model.findOne(filter); } async findOneOrFail(filter: FilterQuery): Promise { const document = await this.findOne(filter); if (!document) throw new HttpError(404, "No Matching Result Found."); return document; } }; };