UNPKG

2.27 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Validator');
7
8module.exports = class FilterValidator extends Base {
9
10 static async filterSplit (value, attr, model, validator) {
11 return StringHelper.split(value, validator.separator);
12 }
13
14 static async filterTrim (value) {
15 return typeof value === 'string' ? value.trim() : '';
16 }
17
18 constructor (config) {
19 super({
20 filter: null,
21 skipOnEmpty: false,
22 skipOnArray: false,
23 separator: ',',
24 ...config
25 });
26 this.prepareFilter();
27 }
28
29 prepareFilter () {
30 let filter = this.filter;
31 if (filter === null) {
32 throw new Error('Filter property must be set');
33 }
34 if (typeof filter === 'string') {
35 filter = `filter${StringHelper.toFirstUpperCase(filter)}`;
36 filter = this.constructor[filter];
37 if (typeof filter !== 'function') {
38 throw new Error(`Inline filter not found: ${this.filter}`);
39 }
40 } else if (typeof filter !== 'function') {
41 throw new Error('Filter must be function');
42 }
43 this.filter = filter;
44 }
45
46 async validateAttr (attr, model) {
47 const value = model.get(attr);
48 if (Array.isArray(value) && this.skipOnArray) {
49 return;
50 }
51 if (typeof this.filter === 'function') {
52 return this.executeFilter(value, attr, model);
53 }
54 if (value === null || value === undefined) {
55 return;
56 }
57 if (typeof value[this.filter] !== 'function') {
58 throw new Error(`Inline filter not found: ${this.filter}: in ${value.constructor.name}`);
59 }
60 model.set(attr, await value[this.filter]());
61 }
62
63 async executeFilter (value, attr, model) {
64 const result = await this.filter(...arguments, this);
65 result instanceof Message
66 ? this.addError(model, attr, result)
67 : model.set(attr, result);
68 }
69};
70
71const StringHelper = require('../helper/StringHelper');
72const Message = require('../i18n/Message');
\No newline at end of file