This repository has been archived by the owner on Jun 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
amygdala.js
553 lines (478 loc) · 17 KB
/
amygdala.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
'use strict';
// CommonJS check so we can require dependencies
if (typeof module === 'object' && module.exports) {
var each = require('lodash/collection/each');
var partial = require('lodash/function/partial');
var debounce = require('lodash/function/debounce');
var clone = require('lodash/lang/clone');
var isString = require('lodash/lang/isString');
var isObject = require('lodash/lang/isObject');
var isFunction = require('lodash/lang/isFunction');
var isArray = require('lodash/lang/isArray');
var isEmpty = require('lodash/lang/isEmpty');
var defaults = require('lodash/object/defaults');
var map = require('lodash/collection/map');
var filter = require('lodash/collection/filter');
var findWhere = require('lodash/collection/findWhere');
var sortBy = require('lodash/collection/sortBy');
var Q = require('q');
var EventEmitter = require('wolfy87-eventemitter');
}
var Amygdala = function(options) {
// Initialize a new Amygdala instance with the given schema and options.
//
// params:
// - options (Object)
// - config (apiUrl, headers)
// - schema
this._config = options.config;
this._schema = options.schema;
this._headers = this._config.headers;
// if not apiUrl is defined, use current location origin
if (!this._config.apiUrl) {
this._config.apiUrl = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
// memory data storage
this._store = {};
this._changeEvents = {};
if (this._config.localStorage) {
each(this._schema, function(value, key) {
// check each schema entry for localStorage data
// TODO: filter out apiUrl and idAttribute
var storageCache = window.localStorage.getItem('amy-' + key);
if (storageCache) {
this._set(key, JSON.parse(storageCache), {'silent': true} );
}
}.bind(this));
// store every change on local storage
// when localStorage is set to true
this.on('change', function(type) {
this.setCache(type, this.findAll(type));
}.bind(this));
}
};
Amygdala.prototype = clone(EventEmitter.prototype);
// ------------------------------
// Helper methods
// ------------------------------
Amygdala.prototype.serialize = function serialize(obj) {
// Translates an object to a querystring
if (!isObject(obj)) {
return obj;
}
var pairs = [];
each(obj, function(value, key) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
Amygdala.prototype.ajax = function ajax(method, url, options) {
// Sends an Ajax request, converting the data into a querystring if the
// method is GET.
//
// params:
// -method (string): GET, POST, PUT, DELETE
// -url (string): The url to send the request to.
// -options (Object)
//
// options
// - data (Object): Will be converted to a querystring for GET requests.
// - contentType (string): A value for the Content-Type request header.
// - headers (Object): Additional headers to add to the request.
var query;
options = options || {};
if (!isEmpty(options.data) && method === 'GET') {
query = this.serialize(options.data);
url = url + '?' + query;
}
var request = new XMLHttpRequest();
var deferred = Q.defer();
request.open(method, url, true);
request.onload = function() {
// status 200 OK, 201 CREATED, 20* ALL OK
if (request.status.toString().substr(0, 2) === '20') {
deferred.resolve(request);
} else {
deferred.reject(request);
}
};
request.onerror = function() {
deferred.reject(new Error('Unabe to send request to ' + JSON.stringify(url)));
};
if (!isEmpty(options.contentType)) {
request.setRequestHeader('Content-Type', options.contentType);
}
if (!isEmpty(options.headers)) {
each(options.headers, function(value, key) {
if (isFunction(value)) {
request.setRequestHeader(key,value());
}
else {
request.setRequestHeader(key, value);
}
});
}
request.send(method === 'GET' ? null : options.data);
return deferred.promise;
}
// ------------------------------
// Internal utils methods
// ------------------------------
Amygdala.prototype._getURI = function(type, params) {
var url;
// get absolute uri for api endpoint
if (!this._schema[type] || !this._schema[type].url) {
throw new Error('Invalid type. Acceptable types are: ' + Object.keys(this._schema));
}
url = this._config.apiUrl + this._schema[type].url;
// if the `idAttribute` specified by the schema or config
// exists as a key in `params` append it's value to the url,
// and remove it from `params` so it's not sent in the query string.
if (params && this._getIdAttribute(type) in params) {
url += params[this._getIdAttribute(type)];
delete params[this._getIdAttribute(type)];
}
return url;
},
Amygdala.prototype._getIdAttribute = function(type) {
// schema may override idAttribute
return this._schema[type].idAttribute || this._config.idAttribute;
},
Amygdala.prototype._emitChange = function(type) {
// TODO: Add tests for debounced events
if (!this._changeEvents[type]) {
this._changeEvents[type] = debounce(partial(function(type) {
// emit changes events
this.emit('change', type);
// change:<type>
this.emit('change:' + type);
// TODO: compare the previous object and trigger change events
}.bind(this), type), 150);
}
this._changeEvents[type]();
}
// ------------------------------
// Internal data sync methods
// ------------------------------
Amygdala.prototype._set = function(type, response, options) {
// Adds or Updates an item of `type` in this._store.
//
// type: schema key/store (teams, users)
// ajaxResponse: response to store in local cache
// initialize store for this type (if needed)
// and store it under `store` for easy access.
var store = this._store[type] ? this._store[type] : this._store[type] = {};
var schema = this._schema[type];
var wrappedResponse = false;
if (isString(response)) {
// If the response is a string, try JSON.parse.
try {
response = JSON.parse(response);
} catch(e) {
throw('Invalid JSON from the API response.');
}
}
if (!isArray(response)) {
// The response isn't an array. We need to figure out how to handle it.
if (schema.parse) {
// Prefer the schema's parse method if one exists.
response = schema.parse(response);
// if it's still not an array, wrap it around one
if (!isArray(response)) {
response = [response];
}
} else {
// Otherwise, just wrap it in an array and hope for the best.
response = [response];
wrappedResponse = true;
}
}
each(response, function(obj) {
// store the object under this._store['type']['id']
store[obj[this._getIdAttribute(type)]] = obj;
// handle oneToMany relations
each(this._schema[type].oneToMany, function(relatedType, relatedAttr) {
var related = obj[relatedAttr];
// check if obj has a `relatedAttr` that is defined as a relation
if (related) {
// check if attr value is an array,
// if it's not empty, and if the content is an object and not a string
if (Object.prototype.toString.call(related) === '[object Array]' &&
related.length > 0 &&
Object.prototype.toString.call(related[0]) === '[object Object]') {
// if related is a list of objects,
// populate the relation `table` with this data
this._set(relatedType, related);
// and replace the list of objects within `obj`
// by a list of `id's
obj[relatedAttr] = map(related, function(item) {
return item[this._getIdAttribute(type)];
}.bind(this));
}
}
}.bind(this));
// handle foreignKey relations
each(this._schema[type].foreignKey, function(relatedType, relatedAttr) {
var related = obj[relatedAttr];
// check if obj has a `relatedAttr` that is defined as a relation
if (related) {
// check if `obj[relatedAttr]` value is an object (FK should not be arrays),
// if it's not empty, and if the content is an object and not a string
if (Object.prototype.toString.call(related) === '[object Object]') {
// if related is an object,
// populate the relation `table` with this data
this._set(relatedType, [related]);
// and replace the list of objects within `item`
// by a list of `id's
obj[relatedAttr] = related[this._getIdAttribute(type)];
}
}
}.bind(this));
// obj.related()
// set up a related method to fetch other related objects
// as defined in the schema for the store.
obj.getRelated = partial(function(schema, obj, attributeName) {
if (schema.oneToMany && attributeName in schema.oneToMany) {
//
// if oneToMany relation
//
// loop through each id in the obj
// and return the full related object list as the response
return obj[attributeName].map(function(value) {
// find in related `table` by id
return this.find(schema.oneToMany[attributeName], value);
}.bind(this)).filter(function(value) {
// filter out undefined/null values
return !!value;
});
} else if (schema.foreignKey && attributeName in schema.foreignKey) {
//
// else, if foreignKey relation
//
//
// find in related `table` by id
return this.find(schema.foreignKey[attributeName], obj[attributeName]);
}
return null;
}.bind(this), schema, obj);
// emit change events
if (!options || options.silent !== true) {
this._emitChange(type);
}
}.bind(this));
// return our data as the original api call's response
return wrappedResponse && response.length === 1 ? response[0] : response;
};
Amygdala.prototype._setAjax = function(type, request, options) {
return this._set(type, request.response, options);
}
Amygdala.prototype._remove = function(type, object) {
// Removes an item of `type` from this._store.
//
// type: schema key/store (teams, users)
// response: response to store in local cache
this._emitChange(type);
// delete object of type by id
delete this._store[type][object[this._getIdAttribute(type)]]
};
Amygdala.prototype._validateURI = function(url) {
// convert paths to full URLs
// TODO: DRY UP
if (url.indexOf('/') === 0) {
return this._config.apiUrl + url;
}
return url;
}
// ------------------------------
// Public data sync methods
// ------------------------------
Amygdala.prototype._get = function(url, params) {
// AJAX post request wrapper
// TODO: make this method public in the future
// Request settings
var settings = {
'data': params,
'headers': this._headers
};
return this.ajax('GET', this._validateURI(url), settings);
}
Amygdala.prototype.get = function(type, params, options) {
// GET request for `type` with optional `params`
//
// type: schema key/store (teams, users)
// params: extra queryString params (?team=xpto&user=xyz)
// options: extra options
// - url: url override
// Default to the URI for 'type'
options = options || {};
defaults(options, {'url': this._getURI(type, params)});
return this._get(options.url, params)
.then(partial(this._setAjax, type).bind(this));
};
Amygdala.prototype._post = function(url, data) {
// AJAX post request wrapper
// TODO: make this method public in the future
// Request settings
var settings = {
'data': data ? JSON.stringify(data) : null,
'contentType': 'application/json',
'headers': this._headers
};
return this.ajax('POST', this._validateURI(url), settings);
}
Amygdala.prototype.add = function(type, object, options) {
// POST/PUT request for `object` in `type`
//
// type: schema key/store (teams, users)
// object: object to update local and remote
// options: extra options
// - url: url override
// Default to the URI for 'type'
options = options || {};
defaults(options, {'url': this._getURI(type)});
// Dynamic URL is now accepted in post
object.url ? options.url = object.url : null;
return this._post(options.url, object)
.then(partial(this._setAjax, type).bind(this));
};
Amygdala.prototype._put = function(url, data) {
// AJAX put request wrapper
// TODO: make this method public in the future
// Request settings
var settings = {
'data': JSON.stringify(data),
'contentType': 'application/json',
'headers': this._headers
};
return this.ajax('PUT', this._validateURI(url), settings);
}
Amygdala.prototype.update = function(type, object) {
// POST/PUT request for `object` in `type`
//
// type: schema key/store (teams, users)
// object: object to update local and remote
var url = object.url;
if (!url && this._getIdAttribute(type) in object) {
url = this._getURI(type, object);
}
if (!url) {
throw new Error('Missing required object.url or ' + this._getIdAttribute(type) + ' attribute.');
}
return this._put(url, object)
.then(partial(this._setAjax, type).bind(this));
};
Amygdala.prototype._delete = function(url, data) {
// AJAX delete request wrapper
// TODO: make this method public in the future
var settings = {
'data': JSON.stringify(data),
'contentType': 'application/json',
'headers': this._headers
};
return this.ajax('DELETE', this._validateURI(url), settings);
}
Amygdala.prototype.remove = function(type, object) {
// DELETE request for `object` in `type`
//
// type: schema key/store (teams, users)
// object: object to update local and remote
var url = object.url;
if (!url && this._getIdAttribute(type) in object) {
url = this._getURI(type, object);
}
if (!url) {
throw new Error('Missing required object.url or ' + this._getIdAttribute(type) + ' attribute.');
}
return this._delete(url, object)
.then(partial(this._remove, type, object).bind(this));
};
// ------------------------------
// Public cache methods
// ------------------------------
Amygdala.prototype.setCache = function(type, objects) {
if (!type) {
throw new Error('Missing schema type parameter.');
}
if (!this._schema[type]) {
throw new Error('Invalid type. Acceptable types are: ' + Object.keys(this._schema));
}
return window.localStorage.setItem('amy-' + type, JSON.stringify(objects));
};
Amygdala.prototype.getCache = function(type) {
if (!type) {
throw new Error('Missing schema type parameter.');
}
if (!this._schema[type] || !this._schema[type].url) {
throw new Error('Invalid type. Acceptable types are: ' + Object.keys(this._schema));
}
return JSON.parse(window.localStorage.getItem('amy-' + type));
};
// ------------------------------
// Public query methods
// ------------------------------
Amygdala.prototype.findAll = function(type, query) {
// find a list of items within the store. (THAT ARE NOT STORED IN BACKBONE COLLECTIONS)
var store = this._store[type];
var orderBy;
var reverseMatch;
var results;
if (!store || !Object.keys(store).length) {
return [];
}
if (query === undefined) {
// query is empty, no object is returned
results = map(store, function(item) { return item; });
} else if (Object.prototype.toString.call(query) === '[object Object]') {
// if query is an object, assume it specifies filters.
results = filter(store, function(item) { return findWhere([item], query); });
} else {
throw new Error('Invalid query for findAll.');
}
orderBy = this._schema[type].orderBy;
if (orderBy) {
// match the orderBy attribute for the presence
// of a reverse flag
reverseMatch = orderBy.match(/^-([\w-]{0,})$/);
if (reverseMatch !== null) {
// if we have two matches, we have a reverse flag
orderBy = orderBy.replace('-', '');
}
results = sortBy(results, function(item) {
return item[orderBy].toString().toLowerCase();
}.bind(this));
if (reverseMatch !== null) {
// reverse the results
results = results.reverse();
}
}
return results;
};
Amygdala.prototype.find = function(type, query) {
// find a specific within the store. (THAT ARE NOT STORED IN BACKBONE COLLECTIONS)
var store = this._store[type];
if (!store || !Object.keys(store).length) {
return undefined;
}
if (query === undefined) {
// query is empty, no object is returned
return undefined;
} else if (Object.prototype.toString.call(query) === '[object Object]') {
// if query is an object, return the first match for the query
return findWhere(store, query);
} else {
// if query is a String or Number, assume it stores the key/url value
// Object.prototype.toString.call(query) === '[object String]'
// Object.prototype.toString.call(query) === '[object Number]'
return store[query];
}
};
// expose via CommonJS, AMD or as a global object
if (typeof module === 'object' && module.exports) {
module.exports = Amygdala;
} else if (typeof define === 'function' && define.amd) {
define(function() {
return Amygdala;
});
} else {
window.Amygdala = Amygdala;
}