Blame view

services/Model.service.js 11 KB
6e6aa9b0   Tarpit Grover   Basic Setup
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
(function (window, angular) {
    var module = angular.module('framework.services.model', []);

    module.provider('Model', modelsProvider);
    //module.service('DataContext', dataService);

    function modelsProvider() {
        var schemas = {

        };

        this.registerSchema = registerSchema;
        this.$get = buildService;

        function registerSchema(name, path, schema) {
            schemas[name] = [path, schema];
            return this;
        }

        buildService.$inject = ['$config', '$http', '$q'];
        function buildService($config, $http, $q) {
            var models = {};

            angular.forEach(schemas, function (value, key) {
                var modelName = key;
                var modelPath = value[0];
                var modelSchema = value[1];

                models[modelName] = BuildConstructor(modelPath, modelSchema);
            });

            return models;

            function Entity(apiEndpoint, schema, values) {
                this.$$apiLocation = apiEndpoint;
                this.$$schema = schema;
                this.$$originalValues = {};
                this.$$changedValues = {};
                this.$$foreignModels = {};

                this.$getChanges = getChanges;
                this.$validate = validateEntity;
                this.$save = saveEntity;
                this.$update = updateEntity;
                this.$patch = patchEntity;
                this.$delete = deleteEntity;
                this.$commit = commitEntity;
                this.$rollback = rollbackEntity;

                angular.forEach(schema, function (value, key) {
                    var fieldName = key,
                        fieldDef = value;

                    if (values[fieldName] !== undefined) {
                        if (typeof fieldDef.type === 'string' && values[fieldName] !== null) {
                            this.$$originalValues[fieldName] = new models[fieldDef.type](values[fieldName]);
                            this.$$foreignModels[fieldName] = fieldDef.type;
                        } else {
                            this.$$originalValues[fieldName] = values[fieldName];
                        }
                    } else {
                        this.$$originalValues[fieldName] = fieldDef.defaultValue;
                    }

                    Object.defineProperty(this, fieldName, {
                        configurable: false,
                        enumerable: true,
                        get: fieldDef.calculated || function () {
                            return this.$$changedValues.hasOwnProperty(fieldName) ?
                                this.$$changedValues[fieldName] : this.$$originalValues[fieldName];
                        },
                        set: function (value) {
                            if (angular.isUndefined(fieldDef.editable) || fieldDef.editable) {

                                this.$$changedValues[fieldName] = value; //CHECK: Cast to correct type??
                            }
                        }
                    });
                }, this);

                function getChanges() {
                    return this.$$changedValues;
                }
                function validateEntity() {
                } //TODO
                function saveEntity() {
                    return $http.post($config.API_ENDPOINT + this.$$apiLocation, this);
                }
                function updateEntity() {
                    var config = {
                        params: {
                            id: this.Id
                        }
                    };
                    return $http.put($config.API_ENDPOINT + this.$$apiLocation, this, config);
                }
                function patchEntity(skipSubObjects) {
                    var self = this;
                    var delta = angular.extend({ Id: this.Id }, this.$getChanges());
                    var config = {
                        params: {
                            id: this.Id
                        }
                    };
                    var request = $http.patch($config.API_ENDPOINT + this.$$apiLocation, delta, config);
                    request.success(function () {
                        self.$commit(true);
                    });
                    return request;
                }
                function deleteEntity() {
                    var config = {
                        params: {
                            id: this.Id
                        }
                    };
                    return $http.delete($config.API_ENDPOINT + this.$$apiLocation, config);
                }
                function commitEntity(skipSubObjects) {
                    angular.forEach(this.$$changedValues, function (value, key) {
                        var fieldName = key,
                            fieldValue = value;
                        this.$$originalValues[fieldName] = fieldValue
                    }, this);
                    this.$$changedValues = {};

                    if (skipSubObjects) return;
                    angular.forEach(this.$$foreignModels, function (value, key) {
                        this[key].$commit();
                    }, this);
                }
                function rollbackEntity(skipSubObjects) {
                    this.$$changedValues = {};

                    if (skipSubObjects) return;
                    angular.forEach(this.$$foreignModels, function (value, key) {
                        this[key].$rollback();
                    }, this);
                }
            }

            function Query(apiEndpoint, ctor) {
                var includes = [];
                var selects = [];
                var filters = [];
                var order = [];
                var modelCtor = ctor;
                this.include = include;
                this.select = select;
                this.filter = filter;
                this.where = filter;
                this.parseAs = parseAs;
                this.execute = execute;
                this.orderBy = orderBy;

                function parseAs(parser) {
                    modelCtor = parser;
                }

                function include() {
                    if (arguments.length === 2) {
                        if (angular.isObject(arguments[1])) {
                            //TODO: Process subquery
                        } else if (angular.isFunction(arguments[1])) {
                            //TODO: Process subquery
                        }
                    } else {
                        [].push.apply(includes, arguments);
                    }
                    return this;
                }

                function orderBy(prop) {
                	this.order.push(prop);
					//todo add dir and aliases
                }

                function select() {
                    [].push.apply(selects, arguments);
                    modelCtor = null;
                    return this;
                }

                function filter(key, op, value) {
                    if (arguments.length === 1) {
                        filters.push(key);
                    } else if (arguments.length === 3) {
                        switch (op) {
                            case '&&':
                                op = 'and';
                                break;
                            case '||':
                                op = 'or';
                                break;
                            case '=':
                            case '==':
                            case '===':
                                op = 'eq';
                                break;
                            case '!=':
                            case '!==':
                            case '!===':
                                op = 'ne';
                                break;
                            case '>':
                                op = 'gt';
                                break;
                            case '>=':
                                op = 'ge';
                                break;
                            case '<':
                                op = 'lt';
                                break;
                            case '<=':
                                op = 'le';
                                break;
                            default:
                                break;
                        }
                        filters.push(key + ' ' + op + ' ' + value);
                    }
                    return this;
                }

                function execute() {
                    var config = {};
                    config.params = _buildParams();
                    apiCall = $config.API_ENDPOINT + apiEndpoint;
                    return $http.get(apiCall, config).then(function (response) {
                        if (!modelCtor) {
                            return response.data;
                        } else {
                            if (angular.isArray(response.data)) {
                                var results = [];
                                angular.forEach(response.data, function (d) {
                                    results.push(new modelCtor(d));
                                });
                                return results;
                            } else {
                                return new modelCtor(response.data);
                            }
                        }
                    });
                }
                
                function _buildParams() {
                    var params = {};
                    if (includes.length) {
                        params.$expand = includes.join(',');
                    }
                    if (filters.length) {
                        params.$filter = filters.join(' and ');
                    }
                    if (selects.length) {
                        params.$select = selects.join(',');
                    }
                    return params;
                }
            }

            function ModelCache() {

            }

            function BuildConstructor(apiEndpoint, schema) {
                function ModelCtor(values) {
                    var values = values || {};

                    this.base = Entity;
                    this.base(apiEndpoint, schema, values);
                }

                ModelCtor.prototype = new Entity;
                ModelCtor.$schema = schema;
                ModelCtor.query = query;
                ModelCtor.getById = getById;

                var passon = ModelCtor;

                function query() {
                    return new Query(apiEndpoint, passon);
                }

                function getById(id) {
                    return new Query(apiEndpoint)
                        .filter('Id', 'eq', id);
                }

                return ModelCtor;
            }
        }
    }

    dataService.$inject = ['$config', '$http', '$q', 'Models'];
    function dataService($config, $http, $q, Models) {
        var entityIdMaps = {};
        var entityArrays = {};

    }
})(window, angular);