Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequelize snippet for sorting (REST api)
// snippet to help feed sort parameters into Sequelize query
// following Vinay Sahni's best practices (http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api)
// e.g. https://my-url.com/api/v1/sausages?sort=-createdAt,name
function list (req, res, next) {
const findOptions = {
order: [],
};
// handle sorting / ordering
if (req.query.sort) {
const sorts = req.query.sort.split(',');
_.each(sorts, (sort) => {
let field = sort;
let order = 'ASC';
if (sort.charAt(0) === '-') {
order = 'DESC';
field = sort.substring(1); // everything after first char
}
findOptions.order.push([field, order]);
});
} else {
// default ordering (createdAt)
findOptions.order.push(['createdAt', 'DESC']);
}
// run the query
models.Sausage.findAndCountAll(findOptions)
.then((result) => {
const rows = result.rows.map((row) => {
const row = row.get({ plain: true });
return row;
});
res.set('Total-Count', result.count); // set count value to res.headers
return res.status(httpStatus.OK).json(rows);
})
.catch(next);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.