forked from carlos8f/node-relations
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.js
More file actions
59 lines (53 loc) · 1.31 KB
/
context.js
File metadata and controls
59 lines (53 loc) · 1.31 KB
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
49
50
51
52
53
54
55
56
57
58
59
function copy (obj) {
if (Array.isArray(obj)) {
return obj.slice();
}
else if (typeof obj === 'object') {
var c = {};
Object.keys(obj).forEach(function (k) {
c[k] = copy(obj[k]);
});
return c;
}
return obj;
}
function Context (name, structure) {
this.name = name;
this.roles = copy(structure) || {};
this.update();
}
module.exports = Context;
Context.prototype.update = function () {
var ctx = this;
this.verbs = Object.keys(ctx.roles).reduce(function (verbs, role) {
ctx.roles[role].forEach(function (verb) {
if (typeof verbs[verb] === 'undefined') {
verbs[verb] = [];
}
verbs[verb].push(role);
});
return verbs;
}, {});
};
Context.prototype.updateRole = function (name, verbs) {
this.roles[name] = copy(verbs);
this.update();
};
Context.prototype.addRole = function (name, verbs) {
if (typeof this.roles[name] !== 'undefined') {
var err = new Error('role already defined: ' + name);
err.code = 'ER_DUP_ROLE';
throw err;
}
this.updateRole(name, verbs);
};
Context.prototype.removeRole = function (name) {
delete this.roles[name];
this.update();
};
Context.prototype.getRoles = function (verb) {
var ctx = this;
return Object.keys(ctx.roles).filter(function (role) {
return (ctx.roles[role].indexOf(verb) >= 0);
});
};