2016-12-29 07:49:51 +09:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
2017-03-19 15:21:43 +09:00
|
|
|
import $ from 'cafy';
|
2016-12-29 07:49:51 +09:00
|
|
|
import Appdata from '../../../models/appdata';
|
|
|
|
import User from '../../../models/user';
|
2017-01-21 21:08:40 +09:00
|
|
|
import serialize from '../../../serializers/user';
|
|
|
|
import event from '../../../event';
|
2016-12-29 07:49:51 +09:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Set app data
|
|
|
|
*
|
2017-03-01 17:37:01 +09:00
|
|
|
* @param {any} params
|
|
|
|
* @param {any} user
|
|
|
|
* @param {any} app
|
2016-12-29 07:49:51 +09:00
|
|
|
* @param {Boolean} isSecure
|
2017-03-01 17:37:01 +09:00
|
|
|
* @return {Promise<any>}
|
2016-12-29 07:49:51 +09:00
|
|
|
*/
|
2017-03-04 04:28:38 +09:00
|
|
|
module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) => {
|
2017-03-19 15:21:43 +09:00
|
|
|
// Get 'set' parameter
|
|
|
|
const [set, setError] = $(params.set).optional.object()
|
|
|
|
.pipe(obj => {
|
|
|
|
return Object.entries(obj).some(kv => {
|
|
|
|
const k = kv[0];
|
|
|
|
const v = kv[1];
|
|
|
|
return $(k).string().match(/[a-z_]+/).isNg() && $(v).string().isNg();
|
|
|
|
});
|
|
|
|
}).$;
|
|
|
|
if (setError) return rej('invalid set param');
|
|
|
|
|
|
|
|
// Get 'key' parameter
|
|
|
|
const [key, keyError] = $(params.key).optional.string().match(/[a-z_]+/).$;
|
|
|
|
if (keyError) return rej('invalid key param');
|
|
|
|
|
|
|
|
// Get 'value' parameter
|
|
|
|
const [value, valueError] = $(params.value).optional.string().$;
|
|
|
|
if (valueError) return rej('invalid value param');
|
|
|
|
|
|
|
|
let data = {};
|
|
|
|
if (set) {
|
|
|
|
data = set;
|
|
|
|
} else {
|
|
|
|
data[key] = value;
|
2016-12-29 07:49:51 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if (isSecure) {
|
2017-01-21 21:08:40 +09:00
|
|
|
const _user = await User.findOneAndUpdate(user._id, {
|
2017-03-19 15:21:43 +09:00
|
|
|
$set: { data }
|
2017-01-21 21:08:40 +09:00
|
|
|
});
|
2017-03-19 15:21:43 +09:00
|
|
|
|
2016-12-29 07:49:51 +09:00
|
|
|
res(204);
|
2017-01-21 21:08:40 +09:00
|
|
|
|
|
|
|
// Publish i updated event
|
|
|
|
event(user._id, 'i_updated', await serialize(_user, user, {
|
|
|
|
detail: true,
|
|
|
|
includeSecrets: true
|
|
|
|
}));
|
2016-12-29 07:49:51 +09:00
|
|
|
} else {
|
2017-01-17 11:11:22 +09:00
|
|
|
await Appdata.update({
|
2016-12-29 07:49:51 +09:00
|
|
|
app_id: app._id,
|
|
|
|
user_id: user._id
|
|
|
|
}, Object.assign({
|
|
|
|
app_id: app._id,
|
|
|
|
user_id: user._id
|
2017-01-21 21:08:40 +09:00
|
|
|
}, {
|
2017-03-19 15:21:43 +09:00
|
|
|
$set: { data }
|
2017-01-21 21:08:40 +09:00
|
|
|
}), {
|
2016-12-29 07:49:51 +09:00
|
|
|
upsert: true
|
|
|
|
});
|
2017-03-19 15:21:43 +09:00
|
|
|
|
2016-12-29 07:49:51 +09:00
|
|
|
res(204);
|
|
|
|
}
|
|
|
|
});
|