-
Notifications
You must be signed in to change notification settings - Fork 34
/
reste.js
679 lines (540 loc) · 22.1 KB
/
reste.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
var main = function() {
var reste = this;
// setup vars
var config = {},
requestHeaders = [];
// generic log handler in DEV mode
function log(message) {
if (config.debug && message) {
console.log('::RESTE::' + message);
}
}
// generic log handler in DEV mode
function warn(message) {
if (config.debug && message) {
console.warn('::RESTE::' + message);
}
}
// sets up the config, headers, adds methods
reste.config = function(args) {
config = args;
reste.setRequestHeaders(config.requestHeaders);
config.methods.forEach(function(method) {
reste.addMethod(method);
});
if (config.models) {
initModels();
config.models.forEach(function(model) {
reste.addModel(model);
});
}
};
reste.setUrl = function(url) {
config.url = url || config.url;
};
reste.getUrl = function() {
return config.url;
};
// makes an http request to a URL, as a POST / GET / currently,
// passing params and callback
function makeHttpRequest(args, onLoad, onError) {
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function parseJSON(text) {
if (isJSON(text)) {
return JSON.parse(text);
} else {
return text;
}
}
// debug the url
if (args.url.indexOf('http') >= 0) {
log(args.url);
} else {
log((config.url ? config.url + args.url : args.url));
}
if (args.params) {
log(JSON.stringify(args.params));
}
// create a client
var http = Ti.Network.createHTTPClient();
reste.clearCookies = function() {
if (http)
http.clearCookies(config.url);
};
var formEncode = false;
//set some defaults
http.setTimeout(config.timeout || 10000);
if (_.has(config, 'validatesSecureCertificate')) {
http.setValidatesSecureCertificate(config.validatesSecureCertificate);
}
// open the url and check if we're overrding with
// a local http based url
if (args.url.indexOf('http') >= 0) {
http.open(args.method, args.url);
} else {
http.open(args.method, (config.url ? config.url + args.url : args.url));
}
// load up any global request headers
requestHeaders.forEach(function(header) {
if (header.name === 'Content-Type' && header.value === 'application/x-www-form-urlencoded') {
formEncode = true;
}
http.setRequestHeader(header.name, typeof header.value === 'function' ? header.value() : header.value);
log('Setting global header - ' + header.name + ': ' + ( typeof header.value === 'function' ? header.value() : header.value));
});
// non-global headers
if (args.headers) {
// load up any request headers
for (var header in args.headers) {
if (header === 'Content-Type' && args.headers[header] === 'application/x-www-form-urlencoded') {
formEncode = true;
} else if (header === 'Content-Type' && args.headers[header] === 'application/json') {
formEncode = false;
}
http.setRequestHeader(header, typeof args.headers[header] === 'function' ? args.headers[header]() : args.headers[header]);
log('Setting local header - ' + header + ': ' + ( typeof args.headers[header] === 'function' ? args.headers[header]() : args.headers[header]));
}
}
// security manager (Pro / Enterprise)
if (_.has(config, 'securityManager')) {
http.setSecurityManager(config.securityManager);
}
// events
http.onload = function(e) {
// get the response parsed
var response = parseJSON(http.responseText);
if (config.onLoad) {
config.onLoad(response, onLoad);
} else if (onLoad) {
onLoad(response);
}
};
http.onerror = function(e) {
e.url = args.url;
function retry() {
log('Retrying...');
makeHttpRequest(args, onLoad, onError);
}
var error;
if (config.errorsAsObjects) {
error = e;
error.content = parseJSON(http.responseText);
warn('Errors will be returned as objects.');
} else {
error = parseJSON(http.responseText);
warn('Future versions of RESTe will return errors as objects. Use config.errorsAsObjects = true to support this now and update your apps!');
}
// if local error, handle it
if (onError) {
onError(error, retry);
} else if (config.onError) {
// otherwise go to global handler
config.onError(error, retry);
} else if (onLoad) {
// otherwise revert to the onLoad callback
onLoad(error, retry);
} else {
// and if reste's not specified, error!
throw 'RESTe :: No error handler / callback for: ' + args.url;
}
};
function send() {
// go
log(args.params);
if (args.params && (args.method === 'POST' || args.method === 'PUT')) {
if (formEncode) {
http.send(args.params);
} else {
http.send(JSON.stringify(args.params));
}
} else {
http.send();
}
}
args.params = args.params || {};
var beforePost = args.beforePost || config.beforePost;
var beforeSend = args.beforeSend || config.beforeSend;
if (args.method === 'POST' && typeof beforePost === 'function') {
// initialise empty params in case it's undefined
beforePost(args.params, function(e) {
args.params = e;
send();
});
} else if ( typeof beforeSend === 'function') {
beforeSend(args.params, function(e) {
args.params = e;
send();
});
} else {
send();
}
}
// set Requestheaders
reste.setRequestHeaders = function(headers) {
requestHeaders = [];
for (var header in headers) {
requestHeaders.push({
name : header,
value : headers[header]
});
}
};
// change/add requestHeader
reste.changeRequestHeader = function(header) {
var changed = false;
_.each(requestHeaders, function(item) {
if (item.name === Object.keys(header)[0]) {
item.value = header[Object.keys(header)[0]];
changed = true;
}
});
if (!changed) {
// add it
requestHeaders.push({
name : Object.keys(header)[0],
value : header[Object.keys(header)[0]]
});
}
};
// removes an item from the requestHeader
reste.removeRequestHeaderItem = function(delItem) {
requestHeaders = _.filter(requestHeaders, function(item) {
return !(item.name === delItem);
});
};
// add a new method
reste.addMethod = function(args) {
log(args.requestHeaders);
reste[args.name] = function(params, onLoad, onError) {
var body,
method = 'GET',
url,
deferred;
if (args.post)
method = 'POST';
if (args.get)
method = 'GET';
if (args.put)
method = 'PUT';
if (args.delete)
method = 'DELETE';
url = args[method.toLowerCase()] || args.get;
if (config.Q && !onLoad && typeof (params) != 'function') {
deferred = config.Q.defer();
onLoad = deferred.resolve;
onError = deferred.reject;
}
if (!onLoad && typeof (params) === 'function') {
onLoad = params;
} else {
for (var param in params) {
if (param === 'body') {
body = params[param];
} else {
while (url.indexOf('<' + param + '>') >= 0) {
if ( typeof params[param] === 'object') {
url = url.replace('<' + param + '>', JSON.stringify(params[param]));
} else {
url = url.replace('<' + param + '>', params[param]);
}
}
}
}
}
if (args.onLoad) {
// save the original callback
var originalOnLoad = onLoad;
// change the callback to be the one specified
onLoad = function(e) {
args.onLoad(e, originalOnLoad);
};
}
if (args.onError) {
// change the callback to be the one specified
onError = function(e) {
args.onError(e, onLoad);
};
}
if (args.expects) {
// look for explicityly required parameters
args.expects.forEach(function(expectedParam) {
if ((method === 'POST' && params.body) ? !params.body[expectedParam] : !params[expectedParam]) {
throw 'RESTe :: missing parameter ' + expectedParam + ' for method ' + args.name;
}
});
makeHttpRequest({
url : url,
method : method,
params : body,
headers : args.requestHeaders || args.headers,
beforePost : args.beforePost,
beforeSend : args.beforeSend
}, onLoad, onError);
} else {
var m,
missing = [],
re = /(\<\w*\>)/g;
//work out which parameters are required
if (config.autoValidateParams) {
while (( m = re.exec(url)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
missing.push(m[0]);
}
}
if (missing.length > 0) {
throw 'RESTe :: missing parameter/s ' + missing + ' for method ' + args.name;
} else {
makeHttpRequest({
url : url,
method : method,
params : body,
headers : args.requestHeaders || args.headers,
beforePost : args.beforePost,
beforeSend : args.beforeSend
}, onLoad, onError);
}
}
if (deferred) {
return deferred.promise;
}
};
};
// Hacktastic section where we override the Alloy.createModel method
// only call and run this section if we need it; if models are defined
reste.createModel = function(name, attributes) {
var model = new Backbone.Model(attributes);
// if we have a config based transfor for th emodel
// then attach this to the model, or create a default
if (reste.modelConfig && reste.modelConfig[name] && reste.modelConfig[name].transform) {
model.transform = function(model, transform) {
if (transform) {
this.__transform = transform(this);
} else {
this.__transform = reste.modelConfig[name].transform(this);
}
return this.__transform;
};
} else {
model.transform = function(model, transform) {
if (transform) {
this.__transform = transform(this);
} else {
this.__transform = this.toJSON();
}
return this.__transform;
};
}
model._type = name;
return model;
};
reste.createCollection = function(name, content) {
if (!Alloy.Collections[name]) {
Alloy.Collections[name] = new Backbone.Collection();
}
if ( content instanceof Array) {
// on-the-fly collection, so populate from array
Alloy.Collections[name].reset(content);
// and override fetch to trigger a change event
Alloy.Collections[name].fetch = function() {
Alloy.Collections[name].trigger('change');
};
} else {
throw 'No Array specified for createCollection';
}
};
function initModels() {
// add a new model definition
reste.addModel = function(args) {
reste.modelConfig = reste.modelConfig || {};
// storing a reference to the model definition in config
reste.modelConfig[args.name] = args;
var model = Backbone.Model.extend({
_type : args.name,
_method : args.name,
transform : function(model, transform) {
if (transform) {
this.__transform = transform(this);
} else if (args.transform) {
this.__transform = args.transform(this);
} else {
this.__transform = this.toJSON();
}
return this.__transform;
}
});
if (args.collections) {
args.collections.forEach(function(collection) {
Alloy.Collections[collection.name] = Alloy.Collections[collection.name] || new Backbone.Collection();
Alloy.Collections[collection.name]._type = args.name;
Alloy.Collections[collection.name]._name = collection.name;
Alloy.Collections[collection.name].model = model;
});
}
};
// Intercept sync to handle collections / models
Backbone.sync = function(method, model, options) {
log('Backbone.sync: ' + method + ' ' + model._type);
var modelConfig = reste.modelConfig[model._type];
var body,
onError;
// if this is a collection, get the data and complete
if ( model instanceof Backbone.Collection && modelConfig && modelConfig.collections) {
var collectionConfig = _.where(modelConfig.collections, {
name: model._name
})[0];
var methodCall = reste[collectionConfig.read];
methodCall(options, function(response) {
if ((response != null) && (response != undefined)) {
// check if we have a return property
if (response[collectionConfig.content]) {
response[collectionConfig.content].forEach(function(item) {
item.id = item[modelConfig.id];
});
if (options.success) options.success(response[collectionConfig.content]);
Alloy.Collections[collectionConfig.name].trigger('sync');
} else {
// otherwise just return an array with the response
response.forEach(function(item) {
item.id = item[modelConfig.id];
});
if (options.success) options.success(response);
Alloy.Collections[collectionConfig.name].trigger('sync');
}
}
}, function(response) {
if (options.error) {
options.error(response);
}
});
} else if ( model instanceof Backbone.Model) {
if (model.get('id') && method === 'create') {
method = 'update';
}
if (method === 'update') {
params = {};
// if we're specifying attributes to changes
// just update those
if (options.changes) {
params.body = {};
for (var attr in options.changes) {
params.body[attr] = model.get(attr);
}
}
// update!
params[modelConfig.id] = model.get('id');
params.body = params.body || model.toJSON();
// remove any ids from the body
delete params.body.id;
delete params.body[modelConfig.id];
// change to change the attributes before sending
if (modelConfig.beforeUpdate) {
params.body = modelConfig.beforeUpdate(params.body);
}
options.error ? onError = function(e) {
options.error(e);
} : onError = null;
reste[modelConfig.update](params, function(e) {
// calls error handler if we have it defined and 201 returned
if (e.code > 200) {
onError(e);
} else {
// otherwise pass to success
options.success(e);
}
}, onError);
}
if (method === 'read') {
if (modelConfig.read) {
if (model[modelConfig.id]) {
options[modelConfig.id] = model[modelConfig.id];
} else if (model.get('id')) {
options[modelConfig.id] = model.get('id');
}
options.error ? onError = function(e) {
options.error(e);
} : onError = null;
reste[modelConfig.read](options, function(e) {
if (modelConfig.content) {
var result = e[modelConfig.content];
if (result.length === 1) {
//result is an array with value as first entry
options.success(result[0]);
}
else {
//result is not an array
options.success(result);
}
} else {
// calls error handler if we have it defined and 201+ returned
if (e.code > 200) {
onError(e);
} else {
// otherwise pass to success
options.success(e);
}
}
}, onError);
}
}
if (method === 'create') {
body = model.toJSON();
// remove any ids from the body
delete body.id;
delete body[modelConfig.id];
// change to change the attributes before sending
if (modelConfig.beforeDelete) {
body = modelConfig.beforeDelete(body);
}
options.error ? onError = function(e) {
options.error(e);
} : onError = null;
reste[modelConfig.create]({
body : body
}, function(e) {
// calls error handler if we have it defined and 201+ returned
if (e.code > 200) {
onError(e);
} else {
// otherwise pass to success
e.id = e[modelConfig.id];
model.set('id', e[modelConfig.id]);
options.success(e);
}
}, onError);
}
if (method === 'delete') {
body = {};
body[modelConfig.id] = model.get('id');
body.body = model.toJSON();
// change to change the attributes before sending
if (modelConfig.beforeCreate) {
body.body = modelConfig.beforeCreate(body.body);
}
options.error ? onError = function(e) {
options.error(e);
} : onError = null;
reste[modelConfig.delete](body, function(e) {
// calls error handler if we have it defined and 201+ returned
if (e.code > 200) {
onError(e);
} else {
// otherwise pass to success
options.success(e);
}
}, onError);
}
}
};
}
return reste;
};
module.exports = main;