Created
November 26, 2017 13:44
-
-
Save chris-jamieson/992634a88a2cf138c52b971681d4629a to your computer and use it in GitHub Desktop.
Sequelize snippet for sorting (REST api)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
thanks