ottoman
Version:
Ottoman Couchbase ODM
76 lines • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.embedTypeFactory = exports.EmbedType = void 0;
const core_type_1 = require("./core-type");
const is_model_1 = require("../../utils/is-model");
const utils_1 = require("../../utils");
const errors_1 = require("../errors");
const cast_strategy_1 = require("../../utils/cast-strategy");
/**
* `EmbedType` will allow declaration of path as another schema, set type to the sub-schema's instance.
*
* ## 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
* ```javascript
* const userSchema = new Schema({
* name: String,
* email: Schema.Types.String,
* createAt: Date,
* });
*
* const schema = new Schema({
* ...
* user: userSchema
* });
* ```
* You can also use a JavaScript plain Object as value for an `EmbedType`.
* Therefore the below example will behave the same as the example above.
*
* ```javascript
* const schema = new Schema({
* ...
* user: {
* name: String,
* email: String,
* createAt: Date,
* }
* });
* ```
* @tip
* `EmbedType` will allow you to easily reuse existing schemas into new ones using composition.
*/
class EmbedType extends core_type_1.CoreType {
constructor(name, schema, options) {
super(name, EmbedType.sName, options);
this.schema = schema;
}
cast(value, strategy = cast_strategy_1.CAST_STRATEGY.DEFAULT_OR_DROP) {
if (!(0, utils_1.is)(value, Object) && !(0, is_model_1.isModel)(value)) {
return (0, cast_strategy_1.checkCastStrategy)(value, strategy, this);
}
else {
return (0, cast_strategy_1.cast)(value, this.schema, { strategy });
}
}
validate(value, strategy) {
value = super.validate(value, strategy);
if (this.isEmpty(value))
return 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.EmbedType = EmbedType;
EmbedType.sName = 'Embed';
const embedTypeFactory = (name, schema) => new EmbedType(name, schema);
exports.embedTypeFactory = embedTypeFactory;
//# sourceMappingURL=embed-type.js.map