1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | const Base = require('./Validator');
|
16 |
|
17 | module.exports = class ExistValidator extends Base {
|
18 |
|
19 | constructor (config) {
|
20 | super({
|
21 | targetClass: null,
|
22 | targetAttr: null,
|
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 | };
|