summaryrefslogtreecommitdiff
path: root/src/api/endpoints/i/appdata/get.ts
blob: a1a57fa13a39fbf2b4511ffb664fa9125b4be71e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * Module dependencies
 */
import $ from 'cafy';
import Appdata from '../../../models/appdata';

/**
 * Get app data
 *
 * @param {any} params
 * @param {any} user
 * @param {any} app
 * @param {Boolean} isSecure
 * @return {Promise<any>}
 */
module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) => {
	// Get 'key' parameter
	const [key = null, keyError] = $(params.key).optional.nullable.string().match(/[a-z_]+/).$;
	if (keyError) return rej('invalid key param');

	if (isSecure) {
		if (!user.data) {
			return res();
		}
		if (key !== null) {
			const data = {};
			data[key] = user.data[key];
			res(data);
		} else {
			res(user.data);
		}
	} else {
		const select = {};
		if (key !== null) {
			select[`data.${key}`] = true;
		}
		const appdata = await Appdata.findOne({
			app_id: app._id,
			user_id: user._id
		}, {
				fields: select
			});

		if (appdata) {
			res(appdata.data);
		} else {
			res();
		}
	}
});