简体   繁体   中英

Prettier way to write this query?

hi is there a nicer / prettier way to write this query?

exports.list = function(req, res) {
if (req.user.roles.indexOf('admin') == 1) {
    Timesheet.find()
        .sort('-created').populate('user', 'displayName').exec(function (err, timesheets) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.jsonp(timesheets);
            }
        });
}
else {


Timesheet.find()
    .where('user').equals(req.user.id)
    .sort('-created').populate('user', 'displayName').exec(function (err, timesheets) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(timesheets);
        }
        });
}
};

only different is, if admin then add .where('user').equals(req.user.id)

To eliminate the duplicate code you can refactor the code to just alter the way the query is built based on whether the user is in the admin role:

exports.list = function(req, res) {
    var query = Timesheet.find();
    if (req.user.roles.indexOf('admin') !== 1) {
        query = query.where('user').equals(req.user.id);
    }
    query.sort('-created').populate('user', 'displayName').exec(function(err, timesheets) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(timesheets);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM