127.0.0.1:8000 watch-together / master server / routes / api / account / prefs.js
master

Tree @master (Download .tar.gz)

prefs.js @masterraw · history · blame

const utils = require("../../../utils");

module.exports = {
    post: {
        "set": function(req, res) {
            utils.query(
                "SELECT * FROM user_prefs WHERE user_id=?",
                [req.user.user_id]
            ).catch(utils.handle_err.sql(res)).then(function([prefs]) {
                let valid_prefs = Object.keys(prefs).reduce(function(acc, pref) {
                    if (pref === "user_id") {
                        return acc;
                    }
                    return Object.assign(acc, {
                        [pref]: 1
                    });
                }, {});

                for (const pref_to_update of Object.keys(req.body)) {
                    if (!valid_prefs[pref_to_update]) {
                        res.locals.log.general.error(pref_to_update, "is not a valid pref");
                        return utils.reject("Invalid Request")
                    }
                }

                return utils.query("UPDATE user_prefs" + utils.set_where(
                    req.body, {
                        user_id: req.user.user_id
                    }
                )).catch(utils.handle_err.sql(res))
            }).then(function(result) {
                res.send(utils.ok({
                    message: result.changedRows ? "Preferences Updated" : "Preferences Unchanged"
                }));
            }).catch(utils.handle_err.res(res, "Error Updating Preferences"));
        }
    }
}