-
Notifications
You must be signed in to change notification settings - Fork 8
/
apiService.js
642 lines (598 loc) · 20.5 KB
/
apiService.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
'use strict';
var httpinvoke = require('httpinvoke');
var _u = require('underscore');
var Q = require("q");
var UriTemplate = require('uritemplate');
var URI = require('URIjs');
var JSPath = require('jspath');
var jsonld = require('jsonld');
var config = require('./config')
var mimeTypes = ['application/json', 'application/ld+json', 'application/hal+json', 'text/javascript'];
var httpOpts = {
headers: {
'Accept': mimeTypes.join(", ")
}
};
//custom Error
function NotJSONError(message) {
this.message = message;
this.stack = Error().stack;
this.type = "NotJSONError";
}
NotJSONError.prototype = Object.create(Error.prototype);
NotJSONError.prototype.name = "NotJSONError";
// a new httpinvoke with a hook to fail on 4xx and 5xx statuses
httpinvoke = httpinvoke.hook('finished', function(err, output, status, headers) {
if(err) {
return arguments;
}
var res = {
body: output,
statusCode: status,
headers: headers
};
if(status >= 400 && status <= 499) {
res.error = new Error('Client error: ' + status);
return [res];
}
if(status >= 500 && status <= 599) {
res.error = new Error('Server error: ' + status);
return [res];
}
var format = headers['content-type'].split(";")[0];
if (mimeTypes.indexOf(format) === -1) {
//response not JSON
res.error = new NotJSONError('Format not JSON but '+ format.split("/")[1].toUpperCase());
return [res];
}
return arguments;
});
/*
* Private Helper Functions
*/
var buildParams = function(apiDesc) {
return keyValArrayToObject(apiDesc.parameters);
};
var deepCollect = function(obj, fn, maxDepth) {
var list = fn(obj);
if (maxDepth > 0 || maxDepth === undefined) {
if (obj instanceof Object) {
for (var key in obj) {
list = list.concat( deepCollect(obj[key], fn, maxDepth-1) );
}
} else if (obj instanceof Array) {
obj.forEach( function(item) {
list = list.concat( deepCollect(item, fn, maxDepth-1) );
});
}
}
return list;
};
// condition must be a predicate function
// action must be a function returning a promise
// returns the promise returned by the last call to action
var promiseWhile = function(condition, action) {
var deferred = Q.defer();
var loop = function(result) {
if (!condition()) {
deferred.resolve(result);
} else {
// if we wanted to break the loop on an error:
// return action().then(loop, deferred.reject);
return action().then(loop, loop);
}
};
loop();
return deferred.promise;
};
// [{ "key": "country", "val": "us"}] -> {"country": "us"}
var keyValArrayToObject = function(parsArr) {
var obj = {};
parsArr = parsArr || [];
parsArr.forEach( function(item) {
obj[item.key] = item.val;
});
return obj;
};
//adds links to obj
var setLinks = function(apiDesc, obj, links) {
if (links.length > 0 ) {
obj._links = {
"self": {}
};
links.forEach( function(link) {
var template;
var epId;
var prefix = config.host +"/"+ apiDesc._id +"/";
if (link.endpoint) {
epId = link.endpoint;
template = prefix + epId +"/"+ apiService.getEp(apiDesc, epId).url;
} else {
epId = "_";
}
obj._links[ link.rel ] = {
href: prefix + epId +"/"+ link.link,
"ns:template": template
};
});
}
};
/*
* Public Functions
*/
var apiService = {};
//httpinvoke and other promise-using libraries otherwise silently
// swallow exceptions when we're executing in their callbacks
apiService.wrapInTryCatch = function(fn, errCb, args) {
try {
return fn.apply(undefined, args);
} catch(e) {
console.error(e, e.stack);
if (errCb) {
errCb(e);
}
}
};
//
apiService.delay = function(time) {
var deferred = Q.defer();
setTimeout(function(){
deferred.resolve();
}, time);
return deferred.promise;
};
apiService.buildUrl = function(url, params) {
//see https://github.com/angular/angular.js/pull/3213
var uri = URI(url);
var pars = [];
params = params || {};
for (var key in params) {
uri.addSearch(key, params[key]);
};
return uri.toString(url + "?" + pars.join(""));
};
apiService.cleanString = function(str) {
//make str url-friendly
return str.replace(/(\s|\.|\/)/g, "-").replace(/[^a-zA-Z0-9-_]/g, '');
};
apiService.getApiDesc = function(apisArr, id) {
//returns object
return _u.findWhere( apisArr, { "_id": id } );
};
apiService.deleteApiDesc = function(containingObj, key, id) {
//only modifies containingObj
var arr = _u.filter( containingObj[key],
function(apiDesc){ return apiDesc._id != id; } );
containingObj[key] = arr;
};
apiService.getEp = function(apiDesc, epId) {
//returns object
return _u.findWhere( apiDesc._embedded["ns:endpoints"], { "_id": epId } );
};
apiService.deleteEp = function(apiDesc, epId) {
//only modifies apiDesc
apiDesc._embedded["ns:endpoints"] = _u.filter( apiDesc._embedded["ns:endpoints"],
function(ep){ return ep._id != epId; } );
};
apiService.getEntityClass = function(apiDesc, ecId) {
//returns object
return _u.findWhere( apiDesc.entityClasses, { "_id": ecId } );
};
apiService.deleteEntityClass = function(apiDesc, ecId) {
//only modifies apiDesc
apiDesc.entityClasses = _u.filter( apiDesc.entityClasses,
function(ec){ return ec._id != ecId; } );
};
//returns a string or false
apiService.getPaginationVarName = function(ep) {
var variable = _u.findWhere( ep.variables, { "isPaginationVar": true } );
return variable ? variable.key : false;
};
apiService.httpGet = function(url, apiDesc) {
var proxyUrl;
if (apiDesc) {
proxyUrl = apiService.buildUrl(config.proxy + url, buildParams(apiDesc));
} else {
proxyUrl = config.proxy + url;
}
return httpinvoke(proxyUrl, "GET", httpOpts)
.then( function(res) {
return JSON.parse(res.body);
});
};
// expands the URL from the URI Template in the specified endpoint
// variables is optional
apiService.endpointToUrl = function(ep, variables) {
var template = UriTemplate.parse(ep.url);
var vars = keyValArrayToObject(ep.variables);
if (variables) {
vars = _u.extend(vars, variables);
}
return template.expand(vars);
};
//returns the results, extracted from the response or false
apiService.extractResults = function(ep, response) {
if (ep === undefined) {
console.error("ep is undefined");
return;
}
if (ep.resultsPath == undefined || ep.resultsPath.length <= 0) {
return false
} else {
return JSPath.apply(ep.resultsPath, response);
}
};
//return links in obj (which is an Entity)
apiService.getEntityClassLinks = function(ec, obj, currentUrl) {
if (ec === undefined) {
console.error("ec is undefined");
return;
}
var links = [];
//custom links defined in ec (EntityClass) description
ec.links.forEach( function(link) {
var vars = {};
if (link.additionalVars) {
_u.filter(link.additionalVars, function(item) { return item.val; }).forEach( function(item) {
var res = JSPath.apply(item.val, obj);
if (res.length > 1) {
console.warn("JSPath result supposed to be singleton but contained " + res.length + " elements.");
}
vars[ item.key ] = res[0];
});
}
var template = UriTemplate.parse(link.val);
_u.extend(vars, obj);
//add currentUrl
var path = currentUrl.split("/");
for (var i=0; i<path.length; i++) {
vars["_path" + i] = path[i];
}
links.push( {
"rel": link.key,
"link": template.expand(vars),
"endpoint": link.endpoint
});
});
return links;
};
// maxDepth is optional
apiService.getRegexLinks = function (apiDesc, obj, maxDepth) {
var links = [];
var regexStr = apiDesc.linksRegex ? apiDesc.linksRegex : ("^"+apiDesc.baseURL);
if (regexStr != "^") {
var regex = new RegExp(regexStr);
deepCollect(obj, function(o) {
for (var key in o) {
var val = o[key];
if ( regex.test(val) ) {
links.push( {
"rel": key,
"link": val,
"endpoint": undefined
});
}
}
return [];
}, maxDepth);
}
return links;
};
//get HAL-like links from linkObj
apiService.getHalLinks = function (obj, url) {
var linkObj;
if (obj._links) {
linkObj = obj._links;
//delete obj._links;
} else {
linkObj = obj.links;
//delete obj.links;
}
var links = [];
for (var key in linkObj) {
var val = linkObj[key];
if (typeof val == "string") {
//simple link like Rotten Tomatoes
links.push( {
"rel": key,
"link": val,
"endpoint": undefined
});
} else if (val.href) {
//HAL link
//HAL spec currently doesn't say relative to what, assume to document URL
links.push( {
"rel": val.title ? val.title : key,
"link": URI(val.href).absoluteTo(url+"/").toString(),
"endpoint": undefined
});
}
};
return links;
};
// returns a Promise of an array of link objects
apiService.getJsonLdLinksPromise = function (obj, url) {
var endsWith = function (str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
};
//try to set baseUrl right
var contextType = typeof obj["@context"];
if (contextType === "string") {
//external context
var absoluteContext = URI(obj["@context"]).absoluteTo(url).toString();
obj["@context"] = [
absoluteContext, {
"@base": url
}
];
} else if (contextType === "object") {
//in-document context
obj["@context"]["@base"] = url;
}
return jsonld.promises().expand(obj) //if this breaks, just redownload from url to get baseUrl etc. right
.then( function(expanded) {
var isId = function(val, key) { return key == "@id"; };
var rawlinks = deepCollect(expanded, function(obj) {
return _u.filter(obj, isId);
});
var links = [];
rawlinks.forEach( function(link) {
//try to find originial key of link to use as rel, bit hacky, doesn't always work
var rel = link;
for( var key in obj) {
if ( endsWith(link, obj[key]) ) {
rel = key;
break;
}
}
//emit our links
links.push( {
"rel": rel,
"link": link,
"endpoint": undefined
});
});
return links;
}, function(err) {
console.error("Couldn't expand JSON-LD", err);
throw err;
});
};
apiService.getPaginationLinks = function(ep, url) {
var varName = ep ? apiService.getPaginationVarName(ep) : false;
if (varName) {
var template = UriTemplate.parse(ep.url);
var vars = keyValArrayToObject(ep.variables);
//extract current pagination number from url
var uri = new URI(url);
var pageNr = parseInt( uri.search(true)[varName] ) || 0;
vars[varName] = pageNr + 1;
var links = [{
"rel": "next",
"link": template.expand(vars),
"endpoint": undefined
}];
if (pageNr > _u.findWhere( ep.variables, { "isPaginationVar": true }).val ){
//generate previous link if not falling under default
vars[varName] = pageNr - 1;
links.push({
"rel": "previous",
"link": template.expand(vars),
"endpoint": undefined
});
}
return links;
} else {
return [];
}
};
// currently NOT returning a promise!
// TODO: decide whether it should and how to do JSON-LD
apiService.setAllLinks = function(apiDesc, ep, responseData, url) {
return apiService.wrapInTryCatch(function(){
// endpoint
var json = _u.clone(responseData);
//if http header == "application/ld+json"
//apiService.getJsonLdLinksPromise(json, url)
// .then( function(jsonLdLinks) {
// });
var globalLinks = apiService.getHalLinks(json, url)
//.concat(jsonLdLinks)
.concat(
apiService.getPaginationLinks(ep, url),
apiService.getRegexLinks(apiDesc, json, 1)
);
var setTitle = function(ec, obj) {
if (ec && ec.titlePath.length > 0) {
var res = JSPath.apply(ec.titlePath, obj);
if (Object.prototype.toString.call(res) === '[object Array]'
&& res.length === 1
&& typeof res[0] === "string"
&& res[0].length > 0) {
if (obj._links === undefined) {
obj._links = {};
}
if (obj._links.self === undefined) {
obj._links.self = {};
}
obj._links.self.title = res[0];
}
}
};
if (ep) {
var results = [];
var ec = apiService.getEntityClass(apiDesc, ep.resultType);
var extrRes = apiService.extractResults(ep, json);
// check: extrRes && Object.prototype.toString.call(extrRes) === '[object Array]'
if (ep.cardinality === 1) {
//singleton
extrRes = extrRes[0] || extrRes;
if (extrRes !== false) {
_u.extend(json, extrRes);
responseData = extrRes; //replace original object with extracted results
}
var entityLinks = ec ? apiService.getEntityClassLinks(ec, json, url) : [];
globalLinks = globalLinks.concat(entityLinks);
} else if(extrRes && extrRes instanceof Array) {
//multiple results entities: set their links
extrRes.forEach( function(originalResult) {
var result = _u.clone(originalResult);
var entityLinks = ec ? apiService.getEntityClassLinks(ec, result, url) : [];
setLinks(apiDesc, result,
apiService.getHalLinks(result, url)
.concat( entityLinks ) //must be last so custom properties take precedence
);
setTitle(ec, result);
results.push(result);
});
responseData._embedded = { "ns:results": results };
}
}
//set links in global object
_u.filter(globalLinks, function(link) {
if (ep && ["next", "previous", "prev"].indexOf(link.rel) != -1) {
// is next/prev link
link.endpoint = ep._id;
}
});
setLinks(apiDesc, responseData, globalLinks);
setTitle(ec, responseData);
return responseData;
});
};
// returns a promise with the standardized JSON
// variables and url are optional, if url provided that will be used instead of the one in ep
apiService.query = function (apiDesc, ep, variables, url) {
var expandedUrl = url ? apiService.buildUrl(url, variables) : apiService.endpointToUrl(ep, variables);
return apiService.httpGet(expandedUrl, apiDesc)
.then( function(response) {
return apiService.setAllLinks(apiDesc, ep, response, expandedUrl);
}, console.error);
};
apiService.unparsedQuery = function (apiDesc, ep, variables, url) {
var expandedUrl = url ? apiService.buildUrl(url, variables) : apiService.endpointToUrl(ep, variables);
return apiService.httpGet(expandedUrl, apiDesc);
};
// returns a promise of the filled in tree
// url is optional, default is baseURL
// progressCb is optional, called after every HTTP request with the updated tree as an argument
apiService.crawl = function(apiDesc, url, progressCb) {
var allLinks = [];
var globalTree = {
url: (url ? url : apiDesc.baseURL),
name: "Root"
};
//BFS using promiseWhile as a loop...
var next = [globalTree];
var i = 0;
var queue = [];
var finishIter = function() {
i++;
next = queue.shift();
progressCb(globalTree);
return apiService.delay(config.httpDelay).then( function(){
return globalTree;
});
};
var cleanName = function(url) {
var uri = new URI( url.replace(new RegExp("^"+apiDesc.baseURL), '') );
for (var key in buildParams(apiDesc) ) {
uri.removeQuery(key)
}
return uri.toString();
}
return promiseWhile( function() {
return (next && i<config.maxHttpIters);
}, function() {
var tree = next[0];
var parnt = next[1];
if (parnt) {
parnt.children.push(tree);
}
return apiService.httpGet(tree.url, apiDesc)
.then( function(json) {
//HTTP success
apiService.wrapInTryCatch( function() {
tree.children = [];
tree.response = json;
var richLinks = apiService.getHalLinks(json, tree.url).concat(
apiService.getRegexLinks(apiDesc, json)
);
var links = richLinks.map( function(link){ return link.link; } );
links.forEach( function(url) {
var child = {
url: url,
name: cleanName(url)
};
queue.push([child, tree]);
});
});
return finishIter();
}, function(res) {
//HTTP failure
var err = res.error || res;
tree.name = cleanName(tree.url);
tree.errMsg = err.message;
tree.statusCode = res.statusCode;
return finishIter();
});
});
};
// returns a JSON object according to the Swagger 2.0 spec https://github.com/wordnik/swagger-spec/blob/master/versions/2.0.md
apiService.swagger = function(apiDesc) {
var paths = {};
var regex = new RegExp("^" + apiDesc.baseURL.replace(/\/$/, ''));
apiDesc._embedded["ns:endpoints"].forEach( function(ep) {
var path = ep.url.replace(regex, '');
paths[path] = {
"get": {
"summary": ep.description,
"operationId": ep._id,
"responses": {
"default": {
"description": "Any response."
}
},
"parameters": ep.variables.map( function(variable){
return {
"name": variable.key,
"in": "path",
"required": true, //swagger 2.0 spec says if `in: 'path'` then `required: true`
"description": variable.val ? ('e.g. ' + variable.val) : undefined
};
})
}
};
});
var baseURI = URI(apiDesc.baseURL);
return {
"swagger": "2.0",
"info": {
"title": apiDesc.label,
"description": apiDesc.description || "",
"version": apiDesc.version || "",
},
"host": baseURI.authority().toString(),
"basePath": baseURI.path().toString().replace(/\/$/, ''),
"schemes": [ baseURI.protocol().toString() ],
"paths": paths
};
};
apiService.curies = function(apiDesc) {
return apiDesc.curies.map( function(cur){
return {
"name": cur.key,
"href": cur.val,
"templated": true
};
});
};
// Register module
if (typeof window === 'undefined') {
module.exports = apiService;
} else {
//angular
app.factory('apiService', function() {
return apiService;
});
}