I have working if/else that looks like this:
async invoke(request, response) {
const { deleted } = request.query;
let users = [];
if (deleted === 'true') {
users = await User.findAndCountAll({
where: {
deletedAt: { [Op.not]: null }
}
});
} else if (deleted === 'false') {
users = await User.findAndCountAll({
where: {
deletedAt: null
}
});
}
return response.send(users);
}
I am trying to make it one liner but the problem is { deleted } returning "undefined" and "true", and I need it to return "true" and "false
async invoke(request, response) { const { deleted } = request.query;
const deletedAt = deleted ? { [Op.not]: null } : null;
const users = await User.findAndCountAll({
where: {
deletedAt
}
});
return response.send(users);
}
CodePudding user response:
Assuming that the only two valid states for deleted
are "true"
and "false"
(odd that it's a string), then since the only difference in the findAndCountAll
calls is the value of deletedAt
, you can use the conditional operator:
async invoke(request, response) {
const { deleted } = request.query;
let users = await User.findAndCountAll({
where: {
deletedAt: deleted === 'true' ? { [Op.not]: null } : null
// −−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
});
return response.send(users);
}