Skip to content

Instantly share code, notes, and snippets.

@aogilvie
Last active November 2, 2021 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aogilvie/d695953b8d504dba2856688ed1b46d6f to your computer and use it in GitHub Desktop.
Save aogilvie/d695953b8d504dba2856688ed1b46d6f to your computer and use it in GitHub Desktop.
JavaScript Code Trap Example #1
/**
 * 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment