-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
83 lines (72 loc) · 2.41 KB
/
index.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const VK_API_VERSION = "5.95";
let access_token = "";
let connect = null;
let store = [];
const subscribers = [];
const init = (params) => new Promise(async (resolve, reject) => {
if (!params || !params.access_token || !params.connect) return reject("required data not found in init params");
connect = params.connect;
access_token = params.access_token;
const keys = await __getAllKeys();
store = await __loadByKeys(keys);
await __updateSubscribers();
return resolve();
});
const subscribe = (f) => {
const id = subscribers.push(f);
return () => delete subscribers[id];
};
const get = (field) => store[field];
const set = (field, value) => new Promise((resolve, reject) => {
__updateByKey(field, value)
.then(() => {
if (value === "") delete store[field];
else store[field] = value;
__updateSubscribers();
return resolve();
})
.catch(() => reject("can't update value"));
});
// Helpers
const __getAllKeys = () => new Promise((resolve, reject) => {
connect.send("VKWebAppCallAPIMethod", {
"method": "storage.getKeys",
"params": {
"v": VK_API_VERSION,
"access_token": access_token
}
})
.then((result) => resolve(result.data.response))
.catch(() => reject("can't get all keys"))
});
const __loadByKeys = (keys = []) => new Promise((resolve, reject) => {
if (keys.length === 0) return resolve({});
connect.send("VKWebAppCallAPIMethod", {
"method": "storage.get",
"params": {
"v": VK_API_VERSION,
"keys": keys.join(','),
"access_token": access_token
}
})
.then((result) => resolve(result.data.response.reduce((a, x) => { a[x.key] = x.value; return a }, {})))
.catch(() => reject("can't load by keys"))
});
const __updateByKey = (key, value) => new Promise((resolve, reject) => {
connect.send("VKWebAppCallAPIMethod", {
"method": "storage.set",
"params": {
"v": VK_API_VERSION,
"key": key,
"value": value,
"access_token": access_token
}
})
.then(() => resolve())
.catch(() => reject("can't update value"));
});
const __updateSubscribers = () => new Promise((resolve) => {
subscribers.forEach((sub) => sub(store));
return resolve();
});
export default { init, get, set, subscribe };