UNPKG

ottoman

Version:
57 lines 2.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.referenceTypeFactory = exports.ReferenceType = void 0; const core_type_1 = require("./core-type"); const utils_1 = require("../../utils"); const is_model_1 = require("../../utils/is-model"); const errors_1 = require("../errors"); /** * The `Reference` type creates a relationship between two schemas. * * ## Options * * - **required** flag to define if the field is mandatory * - **validator** that will be applied to the field a validation function, validation object or string with the name of the custom validator * - **default** that will define the initial value of the field, this option allows a value or a function * - **immutable** that will define this field as immutable. Ottoman prevents you from changing immutable fields if the schema as configure like strict * * @example * ```typescript * const Cat = model('Cat', {name: String}); * const schema = new Schema({ * type: String, * isActive: Boolean, * name: String, * cats: [{ type: CatSchema, ref: 'Cat' }], * }); * const User = model('User', schema); * ``` */ class ReferenceType extends core_type_1.CoreType { constructor(name, schema, refModel, options) { super(name, ReferenceType.sName, options); this.schema = schema; this.refModel = refModel; } cast(value) { return value; } validate(value, strategy) { super.validate(value, strategy); if (this.isEmpty(value)) return value; if ((0, utils_1.is)(value, String)) { return String(value); } if (!(0, utils_1.is)(value, Object) && !(0, is_model_1.isModel)(value)) { throw new errors_1.ValidationError(`Property '${this.name}' must be of type '${this.typeName}'`); } this.checkValidator(value); return this.schema.validate(value); } } exports.ReferenceType = ReferenceType; ReferenceType.sName = 'Reference'; const referenceTypeFactory = (name, opts) => new ReferenceType(name, opts.schema, opts.refModel); exports.referenceTypeFactory = referenceTypeFactory; //# sourceMappingURL=reference-type.js.map