Files
ETAApi/lib/Handlers/Generic.handler.js

60 lines
1.8 KiB
JavaScript

"use strict";
const { ROOT_PATH, LIB_PATH, MODELS_PATH, HANDLERS_PATH } = process.env;
async function getPage( page, elements, Model, filter=null, projection=null){
const skip = elements * page;
const total = await Model.count( filter );
const list = await Model.find( filter , projection, { skip : skip , limit : elements } );
return {
total : total,
limit : elements,
skip : skip,
data : list
}
}
async function getPageQuery(page, elements, Model, filter=null, projection=null){
const skip = elements * page;
const total = await Model.count( filter );
return {
query : Model.find( filter , projection, { skip : skip , limit : elements } ),
total : total,
skip : skip
};
}
class GenericHandler{
constructor( Model, search_param, populate_list=null ) {
this.Model = Model;
this.search_param = search_param;
this.populate_list = populate_list || [];
}
async populateQuey( query ){
if( this.populate_list.length > 0 ){
query.populate( this.populate_list );
}
return await query.exec();
}
async getList( page, elements, filter=null, projection=null ){
const { query } = await getPageQuery( page , elements, this.Model, filter, projection );
return await this.populateQuey( query );
}
async findList( find_string, page, elements, projection=null ){
const search_param = this.search_param;
const re = new RegExp( find_string );
const filter = {};
filter[ search_param ] = { $regex: re, $options: 'i' };
return await this.getList( page, elements, filter, projection );
}
async getById( id, projection=null ){
const query = Model.findById( id, projection );
return await this.populateQuey( query );
}
};
module.exports = { getPage, getPageQuery, GenericHandler };