/**
* Fetch users by projectId
*
* @param {String} projectId (required)
* @param {Object} options (to further narrow query) e.g. [postcode, disabled]
*/
api.prototype.getUsers = function(projectId, options, cb) {
let query = {
projectId,
type,
};
if (options.disabled) {
query.disabled = options.disabled;
}
if (options.postcode)) {
query.postcode = options.postcode;
}
request({
url: CONFIG.hostname + '/api/v' + CONFIG.version + '/users/find',
method: 'GET',
json: true,
qs: {
query,
options: ['_id', 'name', 'projectId', 'postcode', 'email', 'disabled']
}
}, function(err, res) {
that.responseCb(err, res, cb);
});
}
Q: Why does request A return the correctly filtered users by postcode, but request B filter fails?
// Request A
api.getUsers(projectId, { postcode: '123-456' }, (err, users) => { // pass });
// Request B
api.getUsers(projectId, { disabled: false }, (err, users) => { // fail });
A:
disabled
is false
so the api function finds the Object Key disabled
, but the boolean value fails the if condition.
The correct way to check for an Object Key existing:
if (Object.keys(options).indexOf('disabled') > -1) {
query.disabled = options.disabled;
}