-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy-schema.js
87 lines (63 loc) · 2.64 KB
/
proxy-schema.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
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
var ProxySchema = function (modelName, Extends, schema) {
//TODO: implement modelName somehow instead of PmroxySchemaClass
var ProxySchemaClass = function () {
//TODO: Use console.warn when wrong types are used
var self = this;
//Getter and setter checks on obj
Object.observe(self, function (changes) {
changes.forEach(function (change) {
//console.log(change.type, change.name, change.oldValue);
//Warn when new properties added
if(change.type == 'add' && !schema[change.name]){
console.warn('Unknown member "' + change.name + '" added to ' + modelName + ' instance.');
}
//Warn when wrong types assigned (updating)
if(change.type == 'update' && schema[change.name].name != self[change.name].constructor.name){
console.warn('"' + change.name + '" in ' + modelName + ' instance updated to ' + self[change.name].constructor.name + ' instead of ' + schema[change.name].name) + '.';
}
//Warn when wrong types assigned (adding)
if(change.type == 'add' && schema[change.name].name != self[change.name].constructor.name){
console.warn('"' + change.name + '" of type ' + self[change.name].constructor.name + ' instead of type ' + schema[change.name].name + ' added to ' + modelName + ' instance.');
}
if(change.type == 'delete' && schema[change.name]){
console.warn('Member "' + change.name + '" deleted from ' + modelName + ' instance.');
}
});
});
//Inherit from base class
//TODO: Is it a problem that members are added to the child's __proto__ and not Resource's __proto__?
Extends.apply(self, arguments);
//Add "stubs" for each member if not assigned by super constructor
_.keys(schema).forEach(function (key) {
if(key in self === false) {
self[key] = undefined;
}
});
};
ProxySchemaClass.prototype = Extends.prototype;
return ProxySchemaClass;
};
angular.module('ProxySchemaApp', ['ngResource'])
.directive('psEditExampleEntity', function (PersonResource) {
'use strict';
return {
templateUrl: 'edit-example-entity.html',
scope: {},
link: function (scope) {
//Note: Default value types will be validated
scope.person = new PersonResource({name: 'Johnny', age: 99});
}
}
})
.factory('PersonResource', function($resource) {
'use string';
var PersonResource = $resource('/api/people/:id', {}, {
update: {method: 'PUT'}
});
var Person = ProxySchema('Person', PersonResource, {
name: String,
age: Number
});
return Person;
})
;