-
Notifications
You must be signed in to change notification settings - Fork 1
/
angular-models.js
316 lines (254 loc) · 8.08 KB
/
angular-models.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Angular Backbone Models
// (c) 2014 Evan Hobbs
// May be freely distributed under the MIT license.
(function(factory) {
//for AMD environments
if (typeof define === 'function' && define.amd) {
define(['underscore', 'angular'], function(_, angular) {
//if angular isn't exporting anyting then grab the window version
factory(angular || window.angular, _)
});
//Node/commonJS
} else if (typeof exports !== 'undefined') {
var _ = require('underscore');
require('angular');
//if angular doesn't export itself yet so just grab the window version
factory(window.angular, _);
// Where dependencies are already loaded as globals
} else {
factory(window.angular, window._);
}
}(function (angular, _){
//copied (lovingly) from backbone source code
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
/*jshint -W058 */
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
angular.module('angular-models', [])
.factory('sync', function($http){
var methodMap = {
'create': 'post',
'read': 'get',
'update': 'put',
'delete': 'delete',
'patch': 'put'
};
return function(method, model, options){
options = options || {};
var data, args;
//if it's a put or post request put the data in the body
if (_.contains(['create', 'update', 'patch'], method)) {
args = [model.url(), model.toJSON()];
}
else args = [model.url()];
var xhr = $http[methodMap[method]].apply(this, args);
xhr.then(options.success, options.error);
xhr.finally(options.finally);
return xhr;
}
})
/*========== Base Model ==========*/
.factory('Model', function($http, sync){
var Model = function(attributes, options){
this._isModel = true;
options = options || {};
this.atts = this.attributes = {};
attributes = _.defaults({}, attributes, _.result(this, 'defaults'));
this.options = options;
if (options.collection) this.collection = options.collection;
if (options.parse) attributes = this.parse(attributes);
this.set(attributes);
this.id = attributes[this.idAttribute];
this.initialize.apply(this, arguments);
}
Model.extend = extend;
_.extend(Model.prototype, {
idAttribute: 'id',
urlRoot: null,
url: function(){
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || '';
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
initialize: function(){},
parse: function(response){
return response;
},
set: function(key, val){
if (!key) return this;
var attrs = {};
//if the passed in key is an object than the key is the attrs
if (typeof key === 'object') attrs = key;
//otherwise construct the attrs from the key value;
else attrs[key] = val;
_.extend(this.attributes, attrs);
this.id = this.attributes[this.idAttribute];
},
get: function(attr) {
return this.attributes[attr];
},
toJSON: function(options) {
return _.clone(this.attributes);
},
save: function(options){
options = options || {};
var model = this;
var method = this.isNew() ? 'create' : 'update';
var success = options.success;
options.success = function(data, status, headers, config){
model.set(model.parse(data));
if (success) success(model, data, options);
}
return sync(method, this, options);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return !this.id;
},
destroy: function(){
var that = this;
if (this.collection) {
this.collection.remove(this);
}
var xhr = $http.delete(this.urlRoot+'/'+this.id);
return xhr;
},
fetch: function(options){
var xhr, that = this;
_.defaults(options, this.fetchData);
//do the request and preserve the promise
this._fetch = xhr = $http.get(this.urlRoot + '/' + this.id, { params: options})
//update model attributes when the model returns
xhr.then(function(response){
//only attempt to set model properties if we get back an object as opposed to
//error string
if (typeof response.data === 'object') {
that.id = response.data.id;
that.set(response.data);
}
});
return this._fetch;
},
fetchOnce: function(options) {
if (!this._fetch) this.fetch(options);
},
hasFetched: function(){
return typeof this._fetch !== 'undefined';
}
});
return Model;
})
/*========== Base Collection ==========*/
.factory('Collection', function($q, Model, $http){
var Collection = function(models, options){
options = options || {};
this.options = options;
this.models = [];
if (models) this.add(models);
};
Collection.extend = extend;
_.extend(Collection.prototype, {
Model: Model,
get: function(id){
//ensure the id is a number and not a number string
id = parseInt(id, 10);
return _.findWhere(this.models, { id: id });
},
each: function(fn){
_.each(this.models, fn, this);
},
remove: function(model){
var index = _.indexOf(this.models, model);
this.models.splice(index, 1);
},
toJSON: function(options) {
return _.map(this.models, function(model){ return model.toJSON(options); })
},
add: function(models){
console.log(models)
var that = this;
//ensure that models is an array even if an object is passed;
_.flatten([models], true);
_.each(models, function(newModel){
var model = that.get(newModel.id);
//if the model doesn't exist already create a new one
if (!model) {
model = new that.Model(newModel);
that.models.push(model);
//preserve a reference to the parent collection
model.collection = that;
//add and resolve a promise so it matches the pattern of individual model fetches
//even though this model hasn't been fetched by itself
var _fetch = $q.defer();
_fetch.resolve();
model._fetch = _fetch.promise;
}
//otherwise update the existing model
else {
model.set(newModel);
}
});
},
fetch: function(options){
var xhr, that = this;
options = options || {};
//grab the rest service from the model prototype -- assumes that all models will have
//one defined
this._fetch = xhr = $http.get(this.url, { params: options });
xhr.then(function(response){
if (typeof response.data !== 'string') that.add(response.data);
});
return this._fetch;
},
fetchOnce: function(options) {
if (!this._fetch) this.fetch(options);
},
/*
Method: startPolling
...starts a collection polling the API at a given interval
Parameters:
interval - integer value representing the number of micoseconds in between polls
*/
startPolling: function(interval){
var that = this;
interval = interval || 15000;
if (!this._polling) {
this.fetch();
this._polling = setInterval(function(){ that.fetch(); }, interval);
}
},
/*
Method: stopPolling
...cancels polling actions on a collection
*/
stopPolling: function(){
clearInterval(this._polling);
delete this._polling;
}
});
return Collection;
})
}));