-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (44 loc) · 1.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
module.exports = function (schema, options = {}) {
let name = 'locks', values = [];
if (typeof options.field === 'string') name = options.field;
if (options.default instanceof Array) values = options.default;
schema.add({ [ name ]: { type: Array, default: values } });
if (options.helpers) {
schema.methods.lockAll = function () {
this[name] = [ '*' ];
};
schema.methods.lockField = function (field) {
if (this[name] instanceof Array) {
if (field === name) {
if (options.throw) throw new Error(`can't lock "${ field }"`);
} else if (!this[name].includes(field)) this[name].push(field);
}
};
schema.methods.unlockAll = function () {
this[name] = [];
};
schema.methods.unlockField = function (field) {
if (this[name] instanceof Array)
if (this[name].includes(field))
this[name] = this[name].filter(item => field !== item);
};
}
const validate = (instance, field) => {
if (instance.isModified(field))
if (!options.throw) instance.unmarkModified(field);
else throw new Error(`"${ field }" is locked!`);
};
schema.pre('save', function (next) {
if (this.isNew) return next();
if (this[name] instanceof Array)
this[name].forEach(field => {
if (field === '*')
Object.keys(schema.paths)
.filter(item => item !== name && item !== '__v')
.forEach(item => validate(this, item));
else validate(this, field);
});
next();
});
};