0
0

[API] Better appdata get/set endpoints (BREAKING)

This commit is contained in:
syuilo 2017-03-19 15:21:43 +09:00
parent afc06f255a
commit 31550ce1d9
2 changed files with 35 additions and 18 deletions

View File

@ -1,6 +1,7 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import Appdata from '../../../models/appdata';
/**
@ -14,10 +15,8 @@ import Appdata from '../../../models/appdata';
*/
module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) => {
// Get 'key' parameter
let key = params.key;
if (key === undefined) {
key = null;
}
const [key = null, keyError] = $(params.key).optional.nullable.string().match(/[a-z_]+/).$;
if (keyError) return rej('invalid key param');
if (isSecure) {
if (!user.data) {
@ -38,7 +37,9 @@ module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) =
const appdata = await Appdata.findOne({
app_id: app._id,
user_id: user._id
}, select);
}, {
fields: select
});
if (appdata) {
res(appdata.data);

View File

@ -1,6 +1,7 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import Appdata from '../../../models/appdata';
import User from '../../../models/user';
import serialize from '../../../serializers/user';
@ -16,17 +17,37 @@ import event from '../../../event';
* @return {Promise<any>}
*/
module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) => {
const data = params.data;
if (data == null) {
return rej('data is required');
// 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;
}
if (isSecure) {
const _user = await User.findOneAndUpdate(user._id, {
$set: {
data: Object.assign(user.data || {}, JSON.parse(data))
}
$set: { data }
});
res(204);
// Publish i updated event
@ -35,10 +56,6 @@ module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) =
includeSecrets: true
}));
} else {
const appdata = await Appdata.findOne({
app_id: app._id,
user_id: user._id
});
await Appdata.update({
app_id: app._id,
user_id: user._id
@ -46,12 +63,11 @@ module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) =
app_id: app._id,
user_id: user._id
}, {
$set: {
data: Object.assign((appdata || {}).data || {}, JSON.parse(data))
}
$set: { data }
}), {
upsert: true
});
res(204);
}
});