UNPKG

@amirmarmul/waba-common

Version:

![GitHub release](https://img.shields.io/github/v/release/amirmarmul/waba-common?style=flat-square)

126 lines (125 loc) 3.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mongoosePaginate = exports.PaginationModel = void 0; class PaginationModel { meta = { limit: 0, offset: 0, total: undefined, }; docs = []; } exports.PaginationModel = PaginationModel; function mongoosePaginate(schema) { schema.statics.paginate = async function paginate(options, onError) { // INIT let query = options?.query ?? {}; let aggregate = options?.aggregate ?? undefined; let populate = options?.populate ?? undefined; let select = options?.select ?? undefined; let search = options?.search ?? undefined; let sort = options?.sort ?? '-_id'; let projection = options?.projection ?? {}; // PAGING const limit = parseInt(options?.page?.limit) > 0 ? parseInt(options?.page?.limit) : 0; const skip = parseInt(options?.page?.offset) > 0 ? parseInt(options?.page?.offset) : 0; // SEARCHING if (search && search.value && search.fields && search.fields.length) { let searchQuery = { '$regex': search.value, '$options': 'i', }; if (search.fields?.length == 1) { query[search.fields[0]] = searchQuery; } else { if (!query.$or) { query.$or = []; } search.fields.forEach(function (el) { let obj = {}; obj[el] = searchQuery; query.$or.push(obj); }); } } // QUERY let docsPromise; if (aggregate != undefined) { var mQuery = this.aggregate(aggregate); if (select != undefined) { mQuery = mQuery.project(select); } } else { var mQuery = this.find(query, projection); if (select != undefined) { mQuery = mQuery.select(select); } if (populate != undefined) { mQuery = mQuery.populate(populate); } } if (sort != undefined) { mQuery = mQuery.sort(sort); } if (limit > 0) { mQuery = mQuery.skip(skip); mQuery = mQuery.limit(limit); } docsPromise = mQuery.exec(); // COUNTING let countPromise; if (aggregate != undefined) { countPromise = this.aggregate(aggregate).count('count'); } else { countPromise = this.countDocuments(query).exec(); } // PERFORM try { const [counts, docs] = await Promise.all([countPromise, docsPromise]); let count = 0; if (aggregate != undefined) { if (counts != undefined && counts[0] != undefined && counts[0]['count'] != undefined) { count = counts[0]['count']; } } else { count = counts; } const myModel = new PaginationModel(); myModel.meta.total = count; myModel.meta.offset = skip; if (limit > 0) { myModel.meta.limit = limit; } if (limit == 0) { myModel.meta.limit = 0; } myModel.docs = docs; return myModel; } catch (error) { if (onError != undefined) { onError(error); } return undefined; } }; const options = { virtuals: true, transform: function (doc, ret) { ret.id = ret._id; delete ret.__v; } }; schema.set('toJSON', options); schema.set('toObject', options); } exports.mongoosePaginate = mongoosePaginate;