validata
Version:
Type safe data validation and sanitization
54 lines • 2.1 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.maybeAsDateTime = exports.asDateTime = exports.maybeDateTime = exports.isDateTime = void 0;
const luxon_1 = require("luxon");
const common_1 = require("./common");
const types_1 = require("./types");
const check = (value) => {
return value instanceof luxon_1.DateTime;
};
const convert = (value) => {
if (value instanceof Date) {
const utc = luxon_1.DateTime.fromJSDate(value, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc;
}
if (typeof value === 'number' && !Number.isNaN(value)) {
const utc = luxon_1.DateTime.fromMillis(value, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc;
}
if (typeof value === 'string' && value) {
const utc = luxon_1.DateTime.fromISO(value, { zone: 'utc' });
if (!utc.isValid)
return undefined;
return utc;
}
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);
if (options.maxFuture) {
const max = luxon_1.DateTime.utc().plus(options.maxFuture);
if (value > 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 (value < min) {
result.issues.push(types_1.Issue.forPath(path, value, 'max-past', { min }));
}
}
return result;
};
exports.isDateTime = (0, common_1.createIsCheck)('date', check, coerce, validate);
exports.maybeDateTime = (0, common_1.createMaybeCheck)('date', check, coerce, validate);
exports.asDateTime = (0, common_1.createAsCheck)('date', check, convert, coerce, validate);
exports.maybeAsDateTime = (0, common_1.createMaybeAsCheck)('date', check, convert, coerce, validate);
//# sourceMappingURL=date-time.js.map
;