octonom
Version:
Object Document Mapper for any database
59 lines • 2.54 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../errors");
const schema_1 = require("./schema");
// TODO: catch date changes (it's an object!)
class DateSchema {
constructor(options = {}) {
this.options = options;
}
create(value, sanitizeOptions = {}) {
const sanitizedValue = this.sanitize(value, sanitizeOptions);
if (sanitizedValue === undefined) {
return undefined;
}
return {
parent: sanitizeOptions.parent,
schema: this,
value: new Date(sanitizedValue),
};
}
toObject(instance) {
return instance.value;
}
validate(instance) {
return __awaiter(this, void 0, void 0, function* () {
if (this.options.min !== undefined && instance.value < this.options.min) {
throw new errors_1.ValidationError(`Date must not be before ${this.options.min.toISOString()}.`, 'date-min', instance.parent);
}
if (this.options.max !== undefined && instance.value > this.options.max) {
throw new errors_1.ValidationError(`Date must not be after ${this.options.max.toISOString()}.`, 'date-max', instance.parent);
}
yield schema_1.validate(this.options, instance);
});
}
sanitize(value, sanitizeOptions = {}) {
if (value === undefined && sanitizeOptions.defaults) {
return typeof this.options.default === 'function'
? this.options.default()
: this.options.default;
}
if (value === undefined) {
return undefined;
}
if (!(value instanceof Date)) {
throw new errors_1.SanitizationError('Value is not a date.', 'no-date', sanitizeOptions.parent);
}
return value;
}
}
exports.DateSchema = DateSchema;
//# sourceMappingURL=date.js.map