amberflo-metering-typescript
Version:
Amberflo metering client for TypeScript
86 lines • 2.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeShowDeprecationWarning = exports.validators = void 0;
function isSet(value) {
return value !== null && value !== undefined;
}
function required(name, value) {
if (!isSet(value))
throw new Error(`Field ${name} must be set`);
return true;
}
function valid(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
value.validate(name);
}
}
function positiveInteger(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
if (value <= 0)
throw new Error(`Field ${name} must be greater than 0`);
}
}
function positiveNumber(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
if (value <= 0)
throw new Error(`Field ${name} must be greater than 0`);
}
}
function nonEmptyStr(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
if (value.trim().length <= 0)
throw new Error(`Field ${name} may not be an empty string`);
}
}
function nonEmptyStrMap(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
Object.entries(value).forEach(([k, v]) => nonEmptyStr(`${name}.${k}`, v, false));
}
}
function nonEmptyList(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
if (value.length <= 0)
throw new Error(`Field ${name} may not be an empty list`);
value.forEach((x, i) => nonEmptyStr(`${name}.${i}`, x, false));
}
}
function nonEmptyListMap(name, value, nullable = true) {
if (!nullable)
required(name, value);
if (isSet(value)) {
Object.entries(value).forEach(([k, v]) => nonEmptyList(`${name}.${k}`, v, false));
}
}
exports.validators = {
required,
valid,
positiveInteger,
positiveNumber,
nonEmptyStr,
nonEmptyStrMap,
nonEmptyList,
nonEmptyListMap,
};
/**
* Use this function on backwards compatible constructors that used to be
* called without arguments. `value` should be the value of the last mandatory
* parameter.
*/
function maybeShowDeprecationWarning(typeName, value) {
if (!isSet(value))
console.log(new Date(), '[amberflo-metering]', 'WARN', `Using empty constructor of ${typeName} is deprecated`);
}
exports.maybeShowDeprecationWarning = maybeShowDeprecationWarning;
//# sourceMappingURL=validation.js.map