@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
77 lines (76 loc) • 2.6 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reduceDurationToMs = reduceDurationToMs;
exports.buildDuration = buildDuration;
const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
const AbstractField_1 = __importDefault(require("./AbstractField"));
function reduceDurationToMs(duration) {
const d = buildDuration(duration);
let ms = 0;
ms += d.ms;
ms += d.seconds * 1000;
ms += d.minutes * 60 * 1000;
ms += d.hours * 60 * 60 * 1000;
return ms;
}
function buildDuration(value) {
let totalMs = 0;
if (typeof value === 'string') {
totalMs = parseInt(value, 10);
}
else if (typeof value === 'number') {
totalMs = value;
}
else if (typeof value === 'object') {
totalMs += typeof value.ms === 'number' ? value.ms : 0;
totalMs += typeof value.seconds === 'number' ? value.seconds * 1000 : 0;
totalMs +=
typeof value.minutes === 'number' ? value.minutes * 1000 * 60 : 0;
totalMs +=
typeof value.hours === 'number' ? value.hours * 1000 * 60 * 60 : 0;
}
if (typeof totalMs !== 'number') {
throw new SpruceError_1.default({
code: 'INVALID_PARAMETERS',
parameters: ['na'],
friendlyMessage: `\`${value}\` is not a valid duration!`,
});
}
const ms = totalMs % 1000;
totalMs = (totalMs - ms) / 1000;
const seconds = totalMs % 60;
totalMs = (totalMs - seconds) / 60;
const minutes = totalMs % 60;
const hours = (totalMs - minutes) / 60;
return { hours, minutes, seconds, ms };
}
class DurationField extends AbstractField_1.default {
static generateTemplateDetails(options) {
return {
valueType: `${options.importAs}.DurationFieldValue${options.definition.isArray ? '[]' : ''}`,
};
}
validate(value, _) {
const errors = [];
try {
buildDuration(value);
}
catch (err) {
errors.push({
code: 'INVALID_PARAMETER',
name: this.name,
originalError: err,
friendlyMessage: err.options?.friendlyMessage,
});
}
return errors;
}
toValueType(value) {
return buildDuration(value);
}
}
DurationField.description = 'A span of time represented in { hours, minutes, seconds, ms }';
exports.default = DurationField;