Install Middleware – Step 4

Install Middleware – Step 4

Step 4: -Install Middleware

MiddleWare =>advance Result

const advancedResult =(model,populate)=>async(req,res,next)=>{
let query;
   //copy req.query
   const resquery={...req.query};
   //fiels to exclude
   const removefield=['select','sort','page','limit'];
   //loop over removefield and delete from reqquery
   removefield.forEach(param=>delete resquery[param]);
   console.log(resquery)
   let querystr = JSON.stringify(resquery);
   //create operator for relational value
   querystr =querystr.replace(/\b(gt|gte|lt|lte|in)\b/g, match=>`$${match}`);
   console.log(querystr);
   //Finding resorce
   query=model.find(JSON.parse(querystr));
   //select fields
   if(req.query.select){
    const fields=req.query.select.split(',').join(' ');
    query=query.select(fields);
   }
   //sort
if(req.query.sort){
    const sortby=req.query.sort.split(',').join(' ');
    query=query.sort(sortby);
   }
   else{
       query=query.sort('-created')
   }
   //pagination
   const page= parseInt(req.query.page,10)|| 1;
   const limit= parseInt(req.query.limit,10)|| 5;
   const startIndex= (page - 1)* limit;
   const endIndex= page * limit;
   const total=await model.countDocuments();

   query=query.skip(startIndex).limit(limit);

   if(populate)
   {
       query=query.populate(populate);
   }

   //execute query
   const results= await query;
   //pagination result
   const pagination={};
   if(endIndex<total)
   {
       pagination.next={
           page:page+1,
           limit
       }
   }
   if(startIndex>0)
   {
       pagination.prev={
           page:page-1,
           limit
       }
   }
   res.advancedResult={
       success:true,
       count:results.length,
       pagination,
       data:results
   }
   next();
}
module.exports=advancedResult;

util=>errorresponse.js

class ErrorResponse extends Error{
    constructor(message,statusCode){
        super(message);
        this.statusCode=statusCode;
    }
}
module.exports = ErrorResponse;

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*