How to perform a search with conditional where parameters using Sequelize
that's pretty awesome. thank you. i use your ideas like that:
app.get('/', function (req, res) {
..
let foo = await Foo.findAll(
{
offset: parseInt(req.query.offset | 0),
limit: parseInt(req.query.limit | 10),
where: getFooConditions(req),
...
}
function getFooConditions(req) {
fooConditions = {};
// Query param date
if (req.query.date) {
fooCondtions.start = {
[Op.gte]: moment(parseInt(req.query.date)).utc().startOf('day'),
[Op.lte]: moment(parseInt(req.query.date)).utc().endOf('day')
}
}
// Query param name
if (req.query.name) {
fooCondtions.name = {
[Op.like]: '%' + (req.query.name) + '%'
}
}
// Query param id
if (req.query.id) {
fooCondtions.id = {
[Op.equals]: '%' + (req.query.id) + '%'
}
}
return fooConditions;
}
You can just prepare object with needed conditions. Simple and easy to understand
var whereStatement = {};
if(searchParams.id)
whereStatement.id = searchParams.id;
if(searchParams.username)
whereStatement.username = {$like: '%' + searchParams.username + '%'};
models.user.findAll({
where: whereStatement
});