Skip to content

Instantly share code, notes, and snippets.

@chukaofili
Created May 19, 2016 08:01
Show Gist options
  • Save chukaofili/738ed982869dd812def3fdf6b2f8c6ea to your computer and use it in GitHub Desktop.
Save chukaofili/738ed982869dd812def3fdf6b2f8c6ea to your computer and use it in GitHub Desktop.
Sails Paginate Service
/**
* ExampleController.js
*/
module.exports = {
list: function(req, res) {
var perPage = req.query.per_page;
var currentPage = req.query.page;
var conditions = {active: true};
PaginationService.paginate(res, SailsModelHere, conditions, currentPage, perPage, [{name: 'AssociatedModel', query: {isDeleted: false}}], 'createdAt DESC');
},
}
/**
* PaginateService.js
*/
var _ = require('lodash');
module.exports = {
paginate: function(res, model, criteria, currentPage, perPage, populate_data, sort) {
var pagination = {
page: parseInt(currentPage) || 1,
limit: parseInt(perPage) || 20
};
var conditions = criteria || {};
var populate_data = populate_data || [];
model.count(conditions).then(function(count) {
var findQuery = model.find(conditions);
if (sort) {
findQuery = findQuery.sort(sort);
}
if (_.isArray(populate_data) && !_.isEmpty(populate_data)) {
_(populate_data).forEach(function(populate) {
if(_.isObject(populate)){
findQuery = findQuery.populate(populate.name, populate.query);
} else {
findQuery = findQuery.populate(populate);
}
});
}
findQuery = findQuery.paginate(pagination);
return [count, findQuery];
}).spread(function(count, data) {
var numberOfPages = Math.ceil(count / pagination.limit);
var nextPage = parseInt(pagination.page) + 1;
var meta = {
page: pagination.page,
perPage: pagination.limit,
previousPage: (pagination.page > 1) ? parseInt(pagination.page) - 1 : false,
nextPage: (numberOfPages >= nextPage) ? nextPage : false,
pageCount: numberOfPages,
total: count
}
return ResponseService.json(200, res, 'Data retrieved successfully', data, meta);
}).catch(function(err) {
return ResponseService.jsonResolveError(err, res);
});
},
}
/**
* ResponseService.js
*/
module.exports = {
json: function(status, res, message, data, meta) {
var response = {
message: message
};
if (typeof data !== 'undefined') {
response.data = data;
}
if (typeof meta !== 'undefined') {
response.meta = meta;
}
return res.status(status).json(response);
},
jsonResolveError: function(err, res, message) {
var response = {
message: 'Validation error has occured',
};
if (typeof message !== 'undefined') {
response.message = message;
}
if (err.Errors) {
response.errors = err.Errors;
return res.status(400).json(response);
}
var e = JSON.parse(JSON.stringify(err));
if (e.raw){
if(!_.isUndefined(e.raw[0].err)){
response.errors = e.raw[0].err.Errors;
} else {
response.errors = e.raw;
}
return res.status(400).json(response);
}
return res.negotiate(err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment