-
Notifications
You must be signed in to change notification settings - Fork 21
/
external-references.js
119 lines (98 loc) · 3.29 KB
/
external-references.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
/*
* Orange angular-swagger-ui - v0.3.0
*
* (C) 2015 Orange, all right reserved
* MIT Licensed
*/
'use strict';
angular.module('sw.plugin.externalReferences', ['sw.plugins'])
.factory('externalReferences', function ($http, $q, $window, plugins) {
var deferred;
return {
/**
* Module entry point
*/
execute: function (url, swagger) {
deferred = $q.defer();
loadExternalReferences(url, swagger);
return deferred.promise;
}
};
function onError (error) {
deferred.reject(error);
}
/**
* Load external definition
*/
function getUrl (externalUrl, callback) {
var options = {
method: 'GET',
url: externalUrl
};
plugins
.execute(plugins.BEFORE_LOAD, options)
.then(function () {
$http(options).then(callback, onError);
})
.catch(onError);
}
/**
* Generate external URL
*/
function getExternalUrl (baseUrl, $ref) {
if (!angular.isString($ref)) {
return '';
}
var parts = $ref.split('#/');
var externalUrl = parts[0];
if (externalUrl && (externalUrl.indexOf('http') !== 0)) {
// relative url
if (externalUrl.indexOf('/') === 0) {
var swaggerUrlParts = $window.URL.parse(baseUrl);
externalUrl = swaggerUrlParts.protocol + '//' + swaggerUrlParts.host + externalUrl;
} else {
var pos = baseUrl.lastIndexOf('/');
externalUrl = baseUrl.substring(0, pos) + '/' + externalUrl;
}
}
return externalUrl;
}
/**
* Find and resolve external definitions
*/
function loadExternalReferences (baseUrl, swagger) {
var loading = 0;
function load (url, obj) {
loading++;
getUrl(url, function (json) {
loading--;
var subPath = obj.$ref.split('#/')[1];
var subJson = subPath ? json.data[subPath] : json.data;
angular.extend(obj, subJson);
delete obj.$ref;
if (loading === 0) {
deferred.resolve(true);
}
});
}
function iterate (obj) {
angular.forEach(obj, function (v, k) {
if (k === '$ref') {
var externalUrl = getExternalUrl(baseUrl, v);
if (externalUrl) {
load(externalUrl, obj);
}
} else if (angular.isObject(v) || angular.isArray(v)) {
iterate(v);
}
});
}
iterate(swagger);
if (!loading) {
deferred.resolve(false);
}
}
})
.run(function (plugins, externalReferences) {
plugins.add(plugins.BEFORE_PARSE, externalReferences);
});