-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (93 loc) · 2.86 KB
/
Copy pathindex.js
File metadata and controls
102 lines (93 loc) · 2.86 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var systemProps = [
{
name: 'createdDate',
type: 'number',
value: function(item, create, ctx) {
return new Date().getTime();
},
shouldUpdate: function(item, create, ctx) {
return create;
}
},
{
name: 'lastModifiedDate',
type: 'number',
value: function(item, create, ctx) {
return new Date().getTime();
},
shouldUpdate: function(item, create, ctx) {
return true;
}
},
{
name: 'createdBy',
type: 'string',
value: function(item, create, ctx) {
return (ctx.session.isRoot?
'(root)'
:(ctx.session.user?
ctx.session.user.id
:'(anonymous)'
)
);
},
// only update on create
// and if !(userEditable && prop set)
shouldUpdate: function(item, create, ctx, collectionProp) {
return create && !(collectionProp.userEditable && item.createdBy);
}
},
{
name: 'lastModifiedBy',
type: 'string',
value: function(item, create, ctx) {
return (ctx.session.isRoot?
'(root)'
:(ctx.session.user?
ctx.session.user.id
:'(anonymous)'
)
);
},
shouldUpdate: function(item, create, ctx, collectionProp) {
return true && !(collectionProp.userEditable && item.lastModifiedBy);
}
}
];
(function(Collection) {
var _save = Collection.prototype.save,
_validate = Collection.prototype.validate,
systemfieldsContexts = [];
// this is a bit ugly, because in order to have the ctx avaiable in validation, we need to get it out of the save method
Collection.prototype.save = function(ctx, fn) {
// save context for our custom validation hook
systemfieldsContexts.unshift(ctx);
//run default save
var res = _save.call(this, ctx, function() {
// drop context from our custom validation hook
systemfieldsContexts.shift();
return fn.apply(this, arguments);
});
return res;
};
Collection.prototype.validate = function(body, create) {
var res = _validate.apply(this, arguments), ctx = systemfieldsContexts.length && systemfieldsContexts[0];
// don't run if we were not instructed to
if(!ctx) {
return res;
}
var collectionProps = this.properties;
systemProps.forEach(function(systemProp) {
// we may only set properties that the user created
if(!collectionProps[systemProp.name] || !collectionProps[systemProp.name].type == systemProp.type) {
return;
}
// we may not want to set every property
if(!systemProp.shouldUpdate(body, create, ctx, collectionProps[systemProp.name])) {
return;
}
body[systemProp.name] = systemProp.value(body, create, ctx);
});
return res;
};
})(require('deployd/lib/resources/collection/index'));