Validation service
strategy + factory method
by Artem
JavaScript
'use strict';
function Validator(strategy) {
Object.assign(this, {
strategy
});
}
Validator.prototype.validate = function() {
return this.strategy.execute();
};
function ValidationStrategy(config) {
throw new Error('Can\'t create an instance of abstract class!');
}
ValidationStrategy.prototype.execute = function() {
throw new Error('Can\'t call abstract method!');
};
function SimpleValidationStrategy(config) {
this.config = config;
}
SimpleValidationStrategy.prototype = Object.create(ValidationStrategy.prototype);
SimpleValidationStrategy.prototype.constructor = SimpleValidationStrategy;
SimpleValidationStrategy.prototype.execute = function() {
const QUERY_LENGTH = 2;
let result = this.config.params.query && this.config.params.query.length >= QUERY_LENGTH ? true : false;
return this.config.params.query && this.config.params.query.length >= QUERY_LENGTH ? true : false;
};
function AdvancedValidationStrategy(config) {
this.config = config;
}
AdvancedValidationStrategy.prototype = Object.create(ValidationStrategy.prototype);
AdvancedValidationStrategy.prototype.constructor = AdvancedValidationStrategy;
AdvancedValidationStrategy.prototype.execute = function() {
const QUERY_LENGTH = 2;
for (let param in this.config.params) {
if (this.config.params[param] && this.config.params[param].length >= QUERY_LENGTH) {
return true;
}
}
return false;
};
function StrategyFactory() {
this.createStrategy = function(config) {
let strategy;
switch (config.type) {
case 'simple':
{
strategy = new Validator(new SimpleValidationStrategy(config));
break;
}
case 'advanced':
{
strategy = new Validator(new AdvancedValidationStrategy(config));
break;
}
default:
{
throw new TypeError('Unspecified type for validation service!');
}
}
return strategy;
};
}
function ValidationService() {
...