master
Smile 2024-08-23 18:04:52 +01:00
parent 28673688fb
commit f5bd8252a5
1 changed files with 26 additions and 11 deletions

View File

@ -2,16 +2,30 @@
const advancedResult =(model)=> async (req, res, next) => {
//search : l'information que je cherche
//fields : les colonnes je veux utiliser pour la recherche
const fields = req.query.fields;
const search = req.query.search;
let page = req.query.page;
let limit = req.query.limit;
let rows = req.query.rows;
let reqQuery = {...req.query};
const noField = ['page','rows', 'fields', 'search','sort','select'];
noField.forEach(param=> delete reqQuery[param]);
//4. Create query string
let queryStr = JSON.stringify(reqQuery);
//5. Create operators mongo db query ['$lte'] = 30
queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in|ne|or|nin)\b/g, match => `$${match}`);
let find = JSON.parse(queryStr);
console.log("varien", find);
let find = {}
//Recherche
if (fields) {
//search = be
// mark , model, matrcle
//Recherche l'element search dans le tableau de propriété fields
const query = {
$or: fields.map(property => ({
@ -28,32 +42,33 @@ const advancedResult =(model)=> async (req, res, next) => {
}
//Pagination
page = parseInt(page, 10) || 1;
limit = parseInt(limit, 10) || 3000;
const startIndex = (page - 1) * limit; //1, 1-1 = 0
const endIndex = page * limit;
page = parseInt(page, 10) || 0;
rows = parseInt(rows, 10) || 3000;
const startIndex = page * rows;
const endIndex = page * rows;
const total = await model.find(find).countDocuments();
//declaration
let query = model.find(find);
query = query.skip(startIndex).limit(limit); // (5,8) 5,6,7,8,9,10,11, 12
query = query.skip(startIndex).limit(rows); // (5,8) 5,6,7,8,9,10,11, 12
//exécuté
let results = await query;
const pagination = {};
if (endIndex < total) {
pagination.next = {
page: page + 1,
limit
rows
};
}
if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit
rows
};
}
@ -62,10 +77,10 @@ const advancedResult =(model)=> async (req, res, next) => {
count: results.length,
pagination: pagination,
data: results,
startIndex: startIndex + 1,
startIndex: startIndex,
endIndex: results.length,
totalRecords: total,
limit: Number(limit),
rows: Number(rows),
page: page
};
next();