orange-dragonfly-model 0.11.0 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/model.js +29 -3
- package/package.json +1 -1
package/components/model.js
CHANGED
|
@@ -2,9 +2,7 @@ const ORM = require('orange-dragonfly-orm')
|
|
|
2
2
|
const validate = require('orange-dragonfly-validator')
|
|
3
3
|
|
|
4
4
|
class ValidationException extends Error {
|
|
5
|
-
|
|
6
|
-
return {}
|
|
7
|
-
}
|
|
5
|
+
info = {}
|
|
8
6
|
}
|
|
9
7
|
|
|
10
8
|
class Model extends ORM.ActiveRecord {
|
|
@@ -12,6 +10,14 @@ class Model extends ORM.ActiveRecord {
|
|
|
12
10
|
return false
|
|
13
11
|
}
|
|
14
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Returns list of unique keys
|
|
15
|
+
* @returns Array[] List of unique keys
|
|
16
|
+
*/
|
|
17
|
+
static get UNIQUE_KEYS () {
|
|
18
|
+
return []
|
|
19
|
+
}
|
|
20
|
+
|
|
15
21
|
/**
|
|
16
22
|
* Returns schema for the model (Orange Dragonfly Validator format)
|
|
17
23
|
* @return object
|
|
@@ -158,6 +164,25 @@ class Model extends ORM.ActiveRecord {
|
|
|
158
164
|
return await this.save(new_data)
|
|
159
165
|
}
|
|
160
166
|
|
|
167
|
+
/**
|
|
168
|
+
* Checks uniqueness of the object based on UNIQUE_KEYS
|
|
169
|
+
*/
|
|
170
|
+
async checkUniqueness (exception_mode = false, ignore_null = false) {
|
|
171
|
+
for (const fields of this.constructor.UNIQUE_KEYS) {
|
|
172
|
+
if (!await this.isUnique(fields, ignore_null)) {
|
|
173
|
+
if (exception_mode) {
|
|
174
|
+
const ex = new ValidationException('Object is not unique')
|
|
175
|
+
for (const field of fields) {
|
|
176
|
+
ex.info[field] = 'Part of the unique key'
|
|
177
|
+
}
|
|
178
|
+
throw ex
|
|
179
|
+
}
|
|
180
|
+
return false
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return true
|
|
184
|
+
}
|
|
185
|
+
|
|
161
186
|
async _preSave () {
|
|
162
187
|
if (this.constructor.IGNORE_EXTRA_FIELDS) {
|
|
163
188
|
const rules = this.constructor.validation_rules
|
|
@@ -166,6 +191,7 @@ class Model extends ORM.ActiveRecord {
|
|
|
166
191
|
}
|
|
167
192
|
}
|
|
168
193
|
await super._preSave()
|
|
194
|
+
await this.checkUniqueness(true, true)
|
|
169
195
|
await this.validate()
|
|
170
196
|
}
|
|
171
197
|
|