forked from SpringRoll/SpringRoll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserData.js
104 lines (95 loc) · 2.47 KB
/
UserData.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { BellhopSingleton } from '../communication/BellhopSingleton';
const onReturn = Symbol('onReturn');
const READ = 'userDataRead';
const WRITE = 'userDataWrite';
const DELETE = 'userDataRemove';
/**
*
* Manages data between SpringRoll Container and SpringRoll
* @export
* @class UserData
*/
export class UserData {
/**
* Handles return
* @function
* @memberof UserData
* @name onReturn
* @param {*} data
* @param {number} [attempts=3]
* @param {string} METHOD
* @private
* @returns
* @static
*/
static [onReturn](METHOD, data, attempts = 3) {
return new Promise((resolve, reject) => {
let success = false;
let count = 0;
const onReturn = event => {
BellhopSingleton.off(METHOD, onReturn);
success = true;
resolve(event);
};
BellhopSingleton.on(METHOD, onReturn);
BellhopSingleton.send(METHOD, data);
const interval = setInterval(() => {
if (success) {
clearInterval(interval);
return;
}
if (count >= attempts) {
clearInterval(interval);
BellhopSingleton.off(METHOD, onReturn);
reject('No Response');
}
count++;
}, 100);
});
}
/**
* Gets data from SpringRoll Container
* @memberof UserData
* @param {string} name
* @return {Promise}
* @static
*/
static read(name) {
if (!BellhopSingleton.connected) {
const warning = `Could not complete read action for ${name}. Bellhop is not connected.`;
return Promise.reject(warning);
}
return this[onReturn](READ, name)
.then(({ data }) => {
return data;
});
}
/**
* Sends data to SpringRoll Container
* @memberof UserData
* @param {*} value
* @param {string} name
* @returns {Promise}
* @static
*/
static write(name, value) {
const warning = `Could not complete write action for ${name} with value ${value}. Bellhop is not connected.`;
return BellhopSingleton.connected
? this[onReturn](WRITE, { name, value })
: new Promise((_, reject) => reject(warning));
}
/**
* Removes data from SpringRoll Container
* @memberof UserData
* @param {string} name
* @static
*/
static delete(name) {
if (!BellhopSingleton.connected) {
const warning = `Could not complete read action for ${name}. Bellhop is not connected.`;
return Promise.reject(warning);
}
return this[onReturn](DELETE, name);
}
}
export default UserData;