Skip to content

Instantly share code, notes, and snippets.

@chris-jamieson
Created November 26, 2017 13:44
Show Gist options
  • Save chris-jamieson/992634a88a2cf138c52b971681d4629a to your computer and use it in GitHub Desktop.
Save chris-jamieson/992634a88a2cf138c52b971681d4629a to your computer and use it in GitHub Desktop.
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);
}
@atubijessica
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment