@tasolutions/express-core
Version:
All libs for express
120 lines (106 loc) • 3.47 kB
JavaScript
;
module.exports = {
/**
* Handle mapping query
* @param Collection
* @param query
* return object
*/
filter: function (Collection, query) {
let options = {};
// Get entity
const schema = Collection.conn.base.modelSchemas[Collection.name].paths;
for (let item in schema) {
if (query[item])
options[item] = query[item];
}
return options;
},
/**
* Thí function merge collections
* @param collection
* @param page
* @param numLimit
* @param getAll
* @returns {Promise<{totalItems: *, limit: *, totalPages: *, currentPage: *, items: *}>}
*/
paginate: async (collection, page = 1, numLimit = 10, totalDocs = 0, cusCurrentPage = 0, getAll = false) => {
if (!Array.isArray(collection)) {
throw `Expect array and got ${typeof collection}`;
}
// get all data
if (getAll) {
return {
docs: collection,
totalDocs: collection.length,
limit: -1,
totalPages: 1,
currentPage: 1,
pagingCounter: 1,
hasPrevPage: false,
hasNextPage: false,
prev: null,
next: null
}
}
const currentPage = cusCurrentPage ? parseInt(cusCurrentPage) : parseInt(page);
const count = totalDocs ? totalDocs : collection.length;
const limit = parseInt(numLimit);
const offset = (page - 1) * limit;
const paginatedItems = collection.slice(offset, offset + limit);
const labelPagingCounter = (page - 1) * limit + 1;
if (typeof offset !== 'undefined') {
page = Math.ceil((offset + 1) / limit);
}
page = cusCurrentPage ? currentPage : page;
let labelHasPrevPage = false;
let labelHasNextPage = false;
let labelPrevPage = null;
let labelNextPage = null;
const pages = limit > 0 ? Math.ceil(count / limit) || 1 : null;
// Set prev page
if (page > 1) {
labelHasPrevPage = true;
labelPrevPage = page - 1;
} else if (page == 1 && typeof offset !== 'undefined' && offset !== 0) {
labelHasPrevPage = true;
labelPrevPage = 1;
} else {
labelPrevPage = null;
}
// Set next page
if (page < pages) {
labelHasNextPage = true;
labelNextPage = page + 1;
} else {
labelNextPage = null;
}
if(limit) {
return {
docs: paginatedItems,
totalDocs: count,
limit,
totalPages: Math.ceil(count / limit),
currentPage,
pagingCounter: labelPagingCounter,
hasPrevPage: labelHasPrevPage,
hasNextPage: labelHasNextPage,
prev: labelPrevPage,
next: labelNextPage
}
} else {
return {
docs: [],
totalDocs: count,
limit: 0,
totalPages: null,
currentPage: null,
pagingCounter: null,
hasPrevPage: false,
hasNextPage: false,
prev: null,
next: null
}
}
}
}