ottoman
Version:
Ottoman Couchbase ODM
57 lines • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayTypeFactory = exports.ArrayType = void 0;
const core_type_1 = require("./core-type");
const utils_1 = require("../../utils");
const errors_1 = require("../errors");
const cast_strategy_1 = require("../../utils/cast-strategy");
/**
* Array type supports arrays of [SchemaTypes](/docs/api/classes/schema.html) and arrays of subdocuments.
*
* ## Options
*
* - **required** flag to define if the field is mandatory
* - **validator** that will be applied to the field, allowed function, object or string with the name of the custom validator
* - **default** that will define the initial value of the field, allowed and value or function to generate it
* - **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 postSchemaDef = new Schema({
* postTags: [String],
* comments: [{ type: commentSchema, ref: 'Comment' }],
* });
* ```
*/
class ArrayType extends core_type_1.CoreType {
constructor(name, itemType, options) {
super(name, ArrayType.sName, options);
this.itemType = itemType;
}
cast(value, strategy = cast_strategy_1.CAST_STRATEGY.DEFAULT_OR_DROP) {
if ((0, utils_1.is)(value, Array)) {
return (0, cast_strategy_1.ensureArrayItemsType)(value, this.itemType, strategy);
}
return (0, cast_strategy_1.checkCastStrategy)(value, strategy, this);
}
validate(value, strict = true) {
value = super.validate(value, strict);
if (this.isEmpty(value))
return value;
if (!(0, utils_1.is)(value, Array)) {
throw new errors_1.ValidationError(`Property '${this.name}' must be of type '${this.typeName}'`);
}
const _value = value;
const _valueResult = [];
this.checkValidator(_value);
for (const key in _value) {
_valueResult.push(this.itemType.validate(_value[key], strict));
}
return _valueResult;
}
}
exports.ArrayType = ArrayType;
ArrayType.sName = Array.name;
const arrayTypeFactory = (name, item, options) => new ArrayType(name, item, options);
exports.arrayTypeFactory = arrayTypeFactory;
//# sourceMappingURL=array-type.js.map