UNPKG

1.15 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./ExistValidator');
7
8module.exports = class UniqueValidator extends Base {
9
10 getMessage () {
11 return this.createMessage(this.message, 'Value has already been taken');
12 }
13
14 async validateAttr (attr, model) {
15 const targetClass = this.targetClass || model.constructor;
16 const values = this.resolveValues(attr, model);
17 const query = this.createQuery(values, attr, model);
18 const ids = await query.limit(2).column(targetClass.PK);
19 if (this.checkExists(ids, model, targetClass)) {
20 this.addError(model, attr, this.getMessage());
21 }
22 }
23
24 checkExists (ids, model, targetClass) {
25 if (ids.length === 1) {
26 if (targetClass === model.constructor) {
27 return !model.getId() || !CommonHelper.isEqual(model.getId(), ids[0]);
28 }
29 } else if (ids.length === 0) {
30 return false;
31 }
32 return true;
33 }
34};
35
36const CommonHelper = require('../helper/CommonHelper');
\No newline at end of file