@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
71 lines (70 loc) • 2.31 kB
JavaScript
import SpruceError from '../errors/SpruceError.js';
import AbstractField from './AbstractField.js';
export 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;
}
export 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({
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 {
static generateTemplateDetails(options) {
return {
valueType: `${options.importAs}.DurationFieldValue${options.definition.isArray ? '[]' : ''}`,
};
}
validate(value, _) {
var _a;
const errors = [];
try {
buildDuration(value);
}
catch (err) {
errors.push({
code: 'INVALID_PARAMETER',
name: this.name,
originalError: err,
friendlyMessage: (_a = err.options) === null || _a === void 0 ? void 0 : _a.friendlyMessage,
});
}
return errors;
}
toValueType(value) {
return buildDuration(value);
}
}
DurationField.description = 'A span of time represented in { hours, minutes, seconds, ms }';
export default DurationField;