UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

67 lines (66 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DateField = void 0; var _utils = require("@backland/utils"); var _FieldType = require("./FieldType"); class DateField extends _FieldType.FieldType { constructor(def = {}) { super({ def: def, name: 'date' }); const { min, max, autoCreate } = def; let minTime = 0; let maxTime = 0; (0, _utils.expectedType)({ max, min }, 'date', true); if (min !== undefined) { minTime = min.getTime(); } if (max !== undefined) { maxTime = max.getTime(); } this.parse = this.applyParser({ parse: input => { (0, _utils.expectedType)({ value: input }, ['date', 'string', 'number']); const date = DateField.serialize(input); const inputTime = date.getTime(); if (minTime !== 0 && inputTime < minTime && min) { throw new Error(`${date.toISOString()} is less than the minimum ${min.toISOString()}.`); } if (maxTime !== 0 && inputTime > maxTime && max) { throw new Error(`${date.toISOString()} is more than the maximum ${max.toISOString()}.`); } return date; }, preParse(input) { if (autoCreate && input === undefined) { return new Date(); } return input; } }); } static create = (def = {}) => { return new DateField(def); }; static serialize(value) { const date = (0, _utils.dateSerialize)(value); if (!(date instanceof Date)) { throw new TypeError('Field error: value is not an instance of Date'); } return date; } } exports.DateField = DateField; //# sourceMappingURL=DateField.js.map