validata
Version:
Type safe data validation and sanitization
55 lines • 2.24 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeAsDate = exports.asDate = exports.maybeDate = exports.isDate = void 0;
const luxon_1 = require("luxon");
const common_1 = require("./common");
const types_1 = require("./types");
const check = (value) => {
return value instanceof Date;
};
const convert = (value, options) => {
if (typeof value === 'number' && !Number.isNaN(value)) {
const utc = luxon_1.DateTime.fromMillis(value, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc.toJSDate();
}
if (typeof value === 'string' && value) {
if (options === null || options === void 0 ? void 0 : options.format) {
const utc = luxon_1.DateTime.fromFormat(value, options.format, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc.toJSDate();
}
const utc = luxon_1.DateTime.fromISO(value, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc.toJSDate();
}
return undefined;
};
const coerce = () => (next) => (value, path) => {
return next(value, path);
};
const validate = (value, path, options) => {
const result = (0, common_1.basicValidation)(value, path, options);
const dateTime = luxon_1.DateTime.fromJSDate(value);
if (options.maxFuture) {
const max = luxon_1.DateTime.utc().plus(options.maxFuture);
if (dateTime > max) {
result.issues.push(types_1.Issue.forPath(path, value, 'max-future', { max }));
}
}
if (options.maxPast) {
const min = luxon_1.DateTime.utc().minus(options.maxPast);
if (dateTime < min) {
result.issues.push(types_1.Issue.forPath(path, value, 'max-past', { min }));
}
}
return result;
};
exports.isDate = (0, common_1.createIsCheck)('date', check, coerce, validate);
exports.maybeDate = (0, common_1.createMaybeCheck)('date', check, coerce, validate);
exports.asDate = (0, common_1.createAsCheck)('date', check, convert, coerce, validate);
exports.maybeAsDate = (0, common_1.createMaybeAsCheck)('date', check, convert, coerce, validate);
//# sourceMappingURL=date.js.map
;