@decaf-ts/decorator-validation
Version:
simple decorator based validation engine
74 lines • 2.36 kB
JavaScript
import { Validator } from "./Validator.js";
/**
* @summary Base Implementation of a Validator Registry
*
* @prop {Validator[]} [validators] the initial validators to register
*
* @class ValidatorRegistry
* @implements IValidatorRegistry<T>
*
* @category Validation
*/
export class ValidatorRegistry {
constructor(...validators) {
this.cache = {};
this.customKeyCache = {};
this.register(...validators);
}
/**
* @summary retrieves the custom keys
*/
getCustomKeys() {
return Object.assign({}, this.customKeyCache);
}
/**
* @summary retrieves the registered validators keys
*/
getKeys() {
return Object.keys(this.cache);
}
/**
* @summary Retrieves a validator
*
* @param {string} validatorKey one of the {@link ValidationKeys}
* @return {Validator | undefined} the registered Validator or undefined if there is nono matching the provided key
*/
get(validatorKey) {
if (!(validatorKey in this.cache))
return undefined;
const classOrInstance = this.cache[validatorKey];
if (Validator.isValidator(classOrInstance))
return classOrInstance;
const constructor = classOrInstance.default || classOrInstance;
const instance = new constructor();
this.cache[validatorKey] = instance;
return instance;
}
/**
* @summary Registers the provided validators onto the registry
*
* @param {T[] | ValidatorDefinition[]} validator
*/
register(...validator) {
validator.forEach((v) => {
if (Validator.isValidator(v)) {
// const k =
if (v.validationKey in this.cache)
return;
this.cache[v.validationKey] = v;
}
else {
const { validationKey, validator, save } = v;
if (validationKey in this.cache)
return;
this.cache[validationKey] = validator;
if (!save)
return;
const obj = {};
obj[validationKey.toUpperCase()] = validationKey;
this.customKeyCache = Object.assign({}, this.customKeyCache, obj);
}
});
}
}
//# sourceMappingURL=ValidatorRegistry.js.map