2018-06-03 01:02:20 +08:00
|
|
|
import server from "./server.js";
|
|
|
|
|
2019-05-13 03:45:30 +08:00
|
|
|
let optionsReady;
|
|
|
|
|
|
|
|
const loadListeners = [];
|
|
|
|
|
2019-08-23 05:31:02 +08:00
|
|
|
class Options {
|
|
|
|
constructor(arr) {
|
|
|
|
this.arr = arr;
|
|
|
|
}
|
|
|
|
|
|
|
|
get(key) {
|
|
|
|
return this.arr[key];
|
|
|
|
}
|
|
|
|
|
2019-11-20 03:53:04 +08:00
|
|
|
getNames() {
|
|
|
|
return Object.keys(this.arr);
|
|
|
|
}
|
|
|
|
|
2019-08-23 05:31:02 +08:00
|
|
|
getJson(key) {
|
|
|
|
try {
|
|
|
|
return JSON.parse(this.arr[key]);
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getInt(key) {
|
|
|
|
return parseInt(this.arr[key]);
|
|
|
|
}
|
|
|
|
|
|
|
|
getFloat(key) {
|
|
|
|
return parseFloat(this.arr[key]);
|
|
|
|
}
|
|
|
|
|
|
|
|
is(key) {
|
|
|
|
return this.arr[key] === 'true';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function reloadOptions() {
|
2019-05-13 03:45:30 +08:00
|
|
|
optionsReady = new Promise((resolve, reject) => {
|
2019-08-23 05:31:02 +08:00
|
|
|
server.get('options').then(optionArr => {
|
|
|
|
const options = new Options(optionArr);
|
|
|
|
|
2019-05-13 03:45:30 +08:00
|
|
|
resolve(options);
|
|
|
|
|
|
|
|
for (const listener of loadListeners) {
|
|
|
|
listener(options);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
2019-08-23 05:31:02 +08:00
|
|
|
|
|
|
|
return optionsReady;
|
|
|
|
}
|
|
|
|
|
2019-10-07 03:35:26 +08:00
|
|
|
/**
|
|
|
|
* just waits for some options without triggering reload
|
|
|
|
*
|
|
|
|
* @return {Options}
|
|
|
|
*/
|
2019-08-23 05:31:02 +08:00
|
|
|
async function waitForOptions() {
|
|
|
|
return await optionsReady;
|
2019-05-13 03:45:30 +08:00
|
|
|
}
|
|
|
|
|
2019-08-23 05:31:02 +08:00
|
|
|
reloadOptions(); // initial load
|
2019-05-13 03:45:30 +08:00
|
|
|
|
|
|
|
function addLoadListener(listener) {
|
|
|
|
loadListeners.push(listener);
|
|
|
|
|
|
|
|
// useful when listener has been added after the promise resolved, but can cause double emit if not yet
|
|
|
|
// that should not be an issue though
|
|
|
|
optionsReady.then(listener);
|
|
|
|
}
|
2018-06-03 01:02:20 +08:00
|
|
|
|
|
|
|
export default {
|
2019-05-13 03:45:30 +08:00
|
|
|
addLoadListener,
|
2019-08-23 05:31:02 +08:00
|
|
|
reloadOptions,
|
|
|
|
waitForOptions
|
2018-06-03 01:02:20 +08:00
|
|
|
}
|