Notes/src/services/options.js

109 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-06-29 22:15:57 +02:00
const becca = require('../becca/becca');
2022-01-10 17:09:20 +01:00
const sql = require("./sql");
2021-05-01 21:52:22 +02:00
/** @returns {string|null} */
2022-01-12 19:32:23 +01:00
function getOptionOrNull(name) {
2022-01-02 21:20:56 +01:00
let option;
if (becca.loaded) {
option = becca.getOption(name);
2022-01-12 19:32:23 +01:00
} else {
2022-01-02 21:20:56 +01:00
// e.g. in initial sync becca is not loaded because DB is not initialized
option = sql.getRow("SELECT * FROM options WHERE name = ?", name);
}
2023-05-04 22:16:18 +02:00
2022-01-12 19:32:23 +01:00
return option ? option.value : null;
}
/** @returns {string} */
2022-01-12 19:32:23 +01:00
function getOption(name) {
const val = getOptionOrNull(name);
2017-11-02 20:48:02 -04:00
2022-01-12 19:32:23 +01:00
if (val === null) {
throw new Error(`Option '${name}' doesn't exist`);
2017-11-02 20:48:02 -04:00
}
2022-01-12 19:32:23 +01:00
return val;
2017-11-02 20:48:02 -04:00
}
/**
* @returns {integer}
*/
2020-06-20 12:31:38 +02:00
function getOptionInt(name) {
const val = getOption(name);
const intVal = parseInt(val);
if (isNaN(intVal)) {
2023-05-04 22:16:18 +02:00
throw new Error(`Could not parse '${val}' into integer for option '${name}'`);
}
return intVal;
}
/**
2023-01-05 23:38:41 +01:00
* @returns {boolean}
*/
2020-06-20 12:31:38 +02:00
function getOptionBool(name) {
const val = getOption(name);
if (!['true', 'false'].includes(val)) {
2023-05-04 22:16:18 +02:00
throw new Error(`Could not parse '${val}' into boolean for option '${name}'`);
}
return val === 'true';
}
2020-06-20 12:31:38 +02:00
function setOption(name, value) {
2020-07-24 23:14:31 +02:00
if (value === true || value === false) {
value = value.toString();
}
2022-01-02 21:20:56 +01:00
const option = becca.getOption(name);
if (option) {
option.value = value;
2020-06-20 12:31:38 +02:00
option.save();
}
else {
2020-06-20 12:31:38 +02:00
createOption(name, value, false);
}
}
2020-06-20 12:31:38 +02:00
function createOption(name, value, isSynced) {
// to avoid circular dependency, need to find better solution
const BOption = require('../becca/entities/boption');
new BOption({
2018-01-28 19:30:14 -05:00
name: name,
value: value,
isSynced: isSynced
}).save();
2017-11-02 20:48:02 -04:00
}
2020-06-20 12:31:38 +02:00
function getOptions() {
2021-05-01 21:52:22 +02:00
return Object.values(becca.options);
2018-09-06 11:54:04 +02:00
}
2020-06-20 12:31:38 +02:00
function getOptionsMap() {
2021-05-01 21:52:22 +02:00
const map = {};
for (const option of Object.values(becca.options)) {
map[option.name] = option.value;
}
return map;
2018-09-06 11:54:04 +02:00
}
2017-11-02 20:48:02 -04:00
module.exports = {
getOption,
getOptionInt,
getOptionBool,
2017-11-02 20:48:02 -04:00
setOption,
2018-09-06 11:54:04 +02:00
createOption,
getOptions,
2022-01-12 19:32:23 +01:00
getOptionsMap,
getOptionOrNull
2020-06-20 12:31:38 +02:00
};