ssn/src/config.ts
2018-06-21 21:40:27 +02:00

60 lines
2.9 KiB
TypeScript

import { ISettings, Product } from './interfaces/ISettings';
import verifyProductName from './verifyProductName';
const settings: ISettings = {};
/** Sets the given setting to the given value. Throws an error if key is invalid, or value doesn't match the key. */
export const set = (key: string, value: any) => {
switch (key) {
case 'product':
//TODO: need to verify input (one of allowed products)
if (typeof value !== 'string') { throw new Error(`product must be a string but it's a "${typeof value}".`); }
if (!verifyProductName(value)) { throw new Error(`"${value}" is not an allowed product.`); }
settings.product = value as Product;
break;
case 'release':
//verify input (must be a number >=0, and >settings.from)
if (typeof value !== 'number') { throw new Error(`release must be a number but it's a "${typeof value}".`); }
if ((value | 0) !== value) { throw new Error(`release must be an integer but it's ${value}.`); }
if (value < 0) { throw new Error(`release must be a non-negative integer but it's ${value}.`); }
if (settings.from !== undefined && value <= settings.from ) { throw new Error(`release must be bigger than from but ${value} is not bigger than ${settings.from}.`); }
settings.release = value;
break;
case 'from':
//TODO: need to verify input (it's a number >=-1 and <setting.release)
if (typeof value !== 'number') { throw new Error(`from must be a number but it's a "${typeof value}".`); }
if ((value | 0) !== value) { throw new Error(`from must be an integer but it's ${value}.`); }
if (value < -1) { throw new Error(`from must be a non-negative integer or -1, but it's ${value}.`); }
if (settings.release !== undefined && value >= settings.release ) { throw new Error(`from must be smaller than release but ${value} is not smaller than ${settings.release}.`); }
settings.from = value;
break;
case 'outputType':
//need to verify input (it's info or file)
if (typeof value !== 'string') { throw new Error(`outputType must be a string but it's a "${typeof value}".`); }
if (value !== 'info' && value !== 'file') { throw new Error(`outputType must be "info" or "file" but it's "${value}".`); }
settings.outputType = value;
break;
default:
throw new Error(`The configuration setting ${key} does not exist.`);
}
};
/** Verify that all required settings were set. Throws an error if not. */
export const verify = () => {
if (settings.product === undefined) {
throw new Error('No product set.');
}
if (settings.release === undefined) {
throw new Error('No release set.');
}
if (settings.from === undefined) {
throw new Error('No from set.');
}
if (settings.outputType === undefined) {
throw new Error('No outputType set.');
}
return true;
};
/** Gets the value for the given setting. */
export const get = (key: string) => settings[key];