UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5/**
6 * attr must exist
7 * ['attr', 'exist']
8 * attr must exist, but its value will use attr2 to check for existence
9 * ['attr', 'exist', {targetAttr: 'attr2'}]
10 * attr1 and attr2 must exist together, and they both will receive error message
11 * [['attr1', 'attr2'], 'exist', {targetAttr: ['attr1', 'attr2']}]
12 * attr1 and attr2 must exist together, only attr1 will receive error message
13 * ['attr1', 'exist', {targetAttr: ['a1', 'a2']}]
14 */
15const Base = require('./Validator');
16
17module.exports = class ExistValidator extends Base {
18
19 constructor (config) {
20 super({
21 targetClass: null,
22 targetAttr: null, // can be array
23 filter: null,
24 ignoreCase: false,
25 ...config
26 });
27 }
28
29 getMessage () {
30 return this.createMessage(this.message, 'Value does not exist');
31 }
32
33 async validateAttr (attr, model) {
34 const values = this.resolveValues(attr, model);
35 const query = this.createQuery(values, attr, model);
36 if (!await query.count()) {
37 this.addError(model, attr, this.getMessage());
38 }
39 }
40
41 resolveValues (attr, model) {
42 const values = {};
43 const targetAttr = this.targetAttr || attr;
44 if (Array.isArray(targetAttr)) {
45 for (const name of targetAttr) {
46 values[name] = model.get(attr);
47 }
48 } else {
49 values[targetAttr] = model.get(attr);
50 }
51 return values;
52 }
53
54 createQuery (values, attr, model) {
55 const queryModel = this.targetClass ? model.spawn(this.targetClass) : model;
56 const query = queryModel.find();
57 if (this.ignoreCase) {
58 for (const name of Object.keys(values)) {
59 query.and(['LIKE', name, values[name]]);
60 }
61 } else {
62 query.and(values);
63 }
64 if (typeof this.filter === 'function') {
65 this.filter(query, model, attr);
66 } else if (typeof this.filter === 'string') {
67 query.and({[this.filter]: model.get(this.filter)});
68 } else if (this.filter) {
69 query.and(this.filter);
70 }
71 return query;
72 }
73};