@lucaspaganini/value-objects
Version:
TypeScript first validation and class creation library
56 lines • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.VOAny = void 0;
var errors_1 = require("./errors");
/**
* Function to create a value object constructor with many inner value
* object constructors to attempt instantiation.
* Useful if you're expecting one of many value objects.
*
* @template VOC Value object constructor type to make an wrapper of.
* @param VOCs Array of value object constructor to attempt instantiation in order.
* @return Class constructor that accepts all that the inner value object
* constructors would accept and tries to instantiate one of the inner
* value object constructors in the order that they were given.
* The class created by `VOAny` wraps the inner classes and
* exposes the one used for instantiation through the `.value`
* property. Calling {@link VOAnyInstance.valueOf} will call
* `valueOf()` for that inner class.
*
* @example
* ```typescript
* class Email { ... }
* class UserName { ... }
* class EmailOrUserName extends VOAny([Email, UserName]) {}
*
* new EmailOrUserName('lucas@example.com').value // Email
* new EmailOrUserName('lucas').value // UserName
* ```
*/
var VOAny = function (VOCs) {
if (VOCs.length < 1)
throw new errors_1.MinLengthError(1, VOCs.length);
return /** @class */ (function () {
function class_1(raw) {
var errors = [];
for (var _i = 0, VOCs_1 = VOCs; _i < VOCs_1.length; _i++) {
var VO = VOCs_1[_i];
try {
var valueObject = new VO(raw);
this.value = valueObject;
return;
}
catch (err) {
errors.push(err);
}
}
throw errors;
}
class_1.prototype.valueOf = function () {
return this.value.valueOf();
};
return class_1;
}());
};
exports.VOAny = VOAny;
//# sourceMappingURL=any.js.map