grape-swagger-rails 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +5 -0
  3. data/.rubocop_todo.yml +61 -0
  4. data/.travis.yml +5 -2
  5. data/CHANGELOG.md +11 -0
  6. data/CONTRIBUTING.md +13 -10
  7. data/Gemfile +6 -0
  8. data/README.md +58 -2
  9. data/RELEASING.md +1 -1
  10. data/Rakefile +6 -6
  11. data/app/assets/images/grape_swagger_rails/favicon-16x16.png +0 -0
  12. data/app/assets/images/grape_swagger_rails/favicon-32x32.png +0 -0
  13. data/app/assets/images/grape_swagger_rails/favicon.ico +0 -0
  14. data/app/assets/javascripts/grape_swagger_rails/application.js +2 -3
  15. data/app/assets/javascripts/grape_swagger_rails/backbone-min.js +14 -37
  16. data/app/assets/javascripts/grape_swagger_rails/handlebars-2.0.0.js +28 -0
  17. data/app/assets/javascripts/grape_swagger_rails/jquery-1.8.0.min.js +1 -1
  18. data/app/assets/javascripts/grape_swagger_rails/marked.js +1272 -0
  19. data/app/assets/javascripts/grape_swagger_rails/swagger-oauth.js +133 -54
  20. data/app/assets/javascripts/grape_swagger_rails/swagger-ui.min.js +13 -1
  21. data/app/assets/javascripts/grape_swagger_rails/underscore-min.js +6 -32
  22. data/app/assets/javascripts/grape_swagger_rails/underscore-min.map +1 -0
  23. data/app/assets/stylesheets/grape_swagger_rails/print.css +1172 -0
  24. data/app/assets/stylesheets/grape_swagger_rails/screen.css.erb +68 -13
  25. data/app/assets/stylesheets/grape_swagger_rails/style.css +250 -0
  26. data/app/assets/stylesheets/grape_swagger_rails/typography.css +26 -0
  27. data/app/views/grape_swagger_rails/application/index.html.erb +15 -10
  28. data/config/routes.rb +1 -1
  29. data/grape-swagger-rails.gemspec +7 -3
  30. data/lib/grape-swagger-rails.rb +4 -3
  31. data/lib/grape-swagger-rails/version.rb +1 -1
  32. data/lib/tasks/swagger_ui.rake +43 -44
  33. data/spec/dummy/bin/rails +2 -2
  34. data/spec/dummy/bin/rake +1 -1
  35. data/spec/dummy/bin/spring +6 -6
  36. data/spec/dummy/config.ru +1 -1
  37. data/spec/dummy/config/application.rb +2 -1
  38. data/spec/dummy/config/environments/development.rb +3 -0
  39. data/spec/dummy/config/environments/production.rb +1 -1
  40. data/spec/dummy/config/environments/test.rb +4 -1
  41. data/spec/features/grape-swagger-rails_spec.rb +1 -1
  42. data/spec/features/swagger_spec.rb +71 -27
  43. data/spec/spec_helper.rb +1 -1
  44. metadata +108 -45
  45. data/app/assets/javascripts/grape_swagger_rails/handlebars-1.0.0.js +0 -2278
  46. data/app/assets/javascripts/grape_swagger_rails/shred.bundle.js +0 -2765
  47. data/app/assets/javascripts/grape_swagger_rails/shred/content.js +0 -193
  48. data/app/assets/javascripts/grape_swagger_rails/swagger.js +0 -1603
@@ -1,193 +0,0 @@
1
-
2
- // The purpose of the `Content` object is to abstract away the data conversions
3
- // to and from raw content entities as strings. For example, you want to be able
4
- // to pass in a Javascript object and have it be automatically converted into a
5
- // JSON string if the `content-type` is set to a JSON-based media type.
6
- // Conversely, you want to be able to transparently get back a Javascript object
7
- // in the response if the `content-type` is a JSON-based media-type.
8
-
9
- // One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).
10
-
11
- // The `Content` constructor takes an options object, which *must* have either a
12
- // `body` or `data` property and *may* have a `type` property indicating the
13
- // media type. If there is no `type` attribute, a default will be inferred.
14
- var Content = function(options) {
15
- this.body = options.body;
16
- this.data = options.data;
17
- this.type = options.type;
18
- };
19
-
20
- Content.prototype = {
21
- // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.
22
- //
23
- // toString: function() { return this.body; }
24
- //
25
- // Commented out, but I've forgotten why. :/
26
- };
27
-
28
-
29
- // `Content` objects have the following attributes:
30
- Object.defineProperties(Content.prototype,{
31
-
32
- // - **type**. Typically accessed as `content.type`, reflects the `content-type`
33
- // header associated with the request or response. If not passed as an options
34
- // to the constructor or set explicitly, it will infer the type the `data`
35
- // attribute, if possible, and, failing that, will default to `text/plain`.
36
- type: {
37
- get: function() {
38
- if (this._type) {
39
- return this._type;
40
- } else {
41
- if (this._data) {
42
- switch(typeof this._data) {
43
- case "string": return "text/plain";
44
- case "object": return "application/json";
45
- }
46
- }
47
- }
48
- return "text/plain";
49
- },
50
- set: function(value) {
51
- this._type = value;
52
- return this;
53
- },
54
- enumerable: true
55
- },
56
-
57
- // - **data**. Typically accessed as `content.data`, reflects the content entity
58
- // converted into Javascript data. This can be a string, if the `type` is, say,
59
- // `text/plain`, but can also be a Javascript object. The conversion applied is
60
- // based on the `processor` attribute. The `data` attribute can also be set
61
- // directly, in which case the conversion will be done the other way, to infer
62
- // the `body` attribute.
63
- data: {
64
- get: function() {
65
- if (this._body) {
66
- return this.processor.parser(this._body);
67
- } else {
68
- return this._data;
69
- }
70
- },
71
- set: function(data) {
72
- if (this._body&&data) Errors.setDataWithBody(this);
73
- this._data = data;
74
- return this;
75
- },
76
- enumerable: true
77
- },
78
-
79
- // - **body**. Typically accessed as `content.body`, reflects the content entity
80
- // as a UTF-8 string. It is the mirror of the `data` attribute. If you set the
81
- // `data` attribute, the `body` attribute will be inferred and vice-versa. If
82
- // you attempt to set both, an exception is raised.
83
- body: {
84
- get: function() {
85
- if (this._data) {
86
- return this.processor.stringify(this._data);
87
- } else {
88
- return this._body.toString();
89
- }
90
- },
91
- set: function(body) {
92
- if (this._data&&body) Errors.setBodyWithData(this);
93
- this._body = body;
94
- return this;
95
- },
96
- enumerable: true
97
- },
98
-
99
- // - **processor**. The functions that will be used to convert to/from `data` and
100
- // `body` attributes. You can add processors. The two that are built-in are for
101
- // `text/plain`, which is basically an identity transformation and
102
- // `application/json` and other JSON-based media types (including custom media
103
- // types with `+json`). You can add your own processors. See below.
104
- processor: {
105
- get: function() {
106
- var processor = Content.processors[this.type];
107
- if (processor) {
108
- return processor;
109
- } else {
110
- // Return the first processor that matches any part of the
111
- // content type. ex: application/vnd.foobar.baz+json will match json.
112
- var main = this.type.split(";")[0];
113
- var parts = main.split(/\+|\//);
114
- for (var i=0, l=parts.length; i < l; i++) {
115
- processor = Content.processors[parts[i]]
116
- }
117
- return processor || {parser:identity,stringify:toString};
118
- }
119
- },
120
- enumerable: true
121
- },
122
-
123
- // - **length**. Typically accessed as `content.length`, returns the length in
124
- // bytes of the raw content entity.
125
- length: {
126
- get: function() {
127
- if (typeof Buffer !== 'undefined') {
128
- return Buffer.byteLength(this.body);
129
- }
130
- return this.body.length;
131
- }
132
- }
133
- });
134
-
135
- Content.processors = {};
136
-
137
- // The `registerProcessor` function allows you to add your own processors to
138
- // convert content entities. Each processor consists of a Javascript object with
139
- // two properties:
140
- // - **parser**. The function used to parse a raw content entity and convert it
141
- // into a Javascript data type.
142
- // - **stringify**. The function used to convert a Javascript data type into a
143
- // raw content entity.
144
- Content.registerProcessor = function(types,processor) {
145
-
146
- // You can pass an array of types that will trigger this processor, or just one.
147
- // We determine the array via duck-typing here.
148
- if (types.forEach) {
149
- types.forEach(function(type) {
150
- Content.processors[type] = processor;
151
- });
152
- } else {
153
- // If you didn't pass an array, we just use what you pass in.
154
- Content.processors[types] = processor;
155
- }
156
- };
157
-
158
- // Register the identity processor, which is used for text-based media types.
159
- var identity = function(x) { return x; }
160
- , toString = function(x) { return x.toString(); }
161
- Content.registerProcessor(
162
- ["text/html","text/plain","text"],
163
- { parser: identity, stringify: toString });
164
-
165
- // Register the JSON processor, which is used for JSON-based media types.
166
- Content.registerProcessor(
167
- ["application/json; charset=utf-8","application/json","json"],
168
- {
169
- parser: function(string) {
170
- return JSON.parse(string);
171
- },
172
- stringify: function(data) {
173
- return JSON.stringify(data); }});
174
-
175
- var qs = require('querystring');
176
- // Register the post processor, which is used for JSON-based media types.
177
- Content.registerProcessor(
178
- ["application/x-www-form-urlencoded"],
179
- { parser : qs.parse, stringify : qs.stringify });
180
-
181
- // Error functions are defined separately here in an attempt to make the code
182
- // easier to read.
183
- var Errors = {
184
- setDataWithBody: function(object) {
185
- throw new Error("Attempt to set data attribute of a content object " +
186
- "when the body attributes was already set.");
187
- },
188
- setBodyWithData: function(object) {
189
- throw new Error("Attempt to set body attribute of a content object " +
190
- "when the data attributes was already set.");
191
- }
192
- }
193
- module.exports = Content;
@@ -1,1603 +0,0 @@
1
- // swagger.js
2
- // version 2.0.37
3
-
4
- var __bind = function(fn, me){
5
- return function(){
6
- return fn.apply(me, arguments);
7
- };
8
- };
9
-
10
- log = function(){
11
- log.history = log.history || [];
12
- log.history.push(arguments);
13
- if(this.console){
14
- console.log( Array.prototype.slice.call(arguments)[0] );
15
- }
16
- };
17
-
18
- if (!Array.prototype.indexOf) {
19
- Array.prototype.indexOf = function(obj, start) {
20
- for (var i = (start || 0), j = this.length; i < j; i++) {
21
- if (this[i] === obj) { return i; }
22
- }
23
- return -1;
24
- }
25
- }
26
-
27
- if (!('filter' in Array.prototype)) {
28
- Array.prototype.filter= function(filter, that /*opt*/) {
29
- var other= [], v;
30
- for (var i=0, n= this.length; i<n; i++)
31
- if (i in this && filter.call(that, v= this[i], i, this))
32
- other.push(v);
33
- return other;
34
- };
35
- }
36
-
37
- if (!('map' in Array.prototype)) {
38
- Array.prototype.map= function(mapper, that /*opt*/) {
39
- var other= new Array(this.length);
40
- for (var i= 0, n= this.length; i<n; i++)
41
- if (i in this)
42
- other[i]= mapper.call(that, this[i], i, this);
43
- return other;
44
- };
45
- }
46
-
47
- Object.keys = Object.keys || (function () {
48
- var hasOwnProperty = Object.prototype.hasOwnProperty,
49
- hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
50
- DontEnums = [
51
- 'toString',
52
- 'toLocaleString',
53
- 'valueOf',
54
- 'hasOwnProperty',
55
- 'isPrototypeOf',
56
- 'propertyIsEnumerable',
57
- 'constructor'
58
- ],
59
- DontEnumsLength = DontEnums.length;
60
-
61
- return function (o) {
62
- if (typeof o != "object" && typeof o != "function" || o === null)
63
- throw new TypeError("Object.keys called on a non-object");
64
-
65
- var result = [];
66
- for (var name in o) {
67
- if (hasOwnProperty.call(o, name))
68
- result.push(name);
69
- }
70
-
71
- if (hasDontEnumBug) {
72
- for (var i = 0; i < DontEnumsLength; i++) {
73
- if (hasOwnProperty.call(o, DontEnums[i]))
74
- result.push(DontEnums[i]);
75
- }
76
- }
77
-
78
- return result;
79
- };
80
- })();
81
-
82
- var SwaggerApi = function(url, options) {
83
- this.url = null;
84
- this.debug = false;
85
- this.basePath = null;
86
- this.authorizations = null;
87
- this.authorizationScheme = null;
88
- this.info = null;
89
- this.useJQuery = false;
90
-
91
- options = (options||{});
92
- if (url)
93
- if (url.url)
94
- options = url;
95
- else
96
- this.url = url;
97
- else
98
- options = url;
99
-
100
- if (options.url != null)
101
- this.url = options.url;
102
-
103
- if (options.success != null)
104
- this.success = options.success;
105
-
106
- if (typeof options.useJQuery === 'boolean')
107
- this.useJQuery = options.useJQuery;
108
-
109
- this.failure = options.failure != null ? options.failure : function() {};
110
- this.progress = options.progress != null ? options.progress : function() {};
111
- if (options.success != null)
112
- this.build();
113
- }
114
-
115
- SwaggerApi.prototype.build = function() {
116
- var _this = this;
117
- this.progress('fetching resource list: ' + this.url);
118
- var obj = {
119
- useJQuery: this.useJQuery,
120
- url: this.url,
121
- method: "get",
122
- headers: {
123
- accept: "application/json"
124
- },
125
- on: {
126
- error: function(response) {
127
- if (_this.url.substring(0, 4) !== 'http') {
128
- return _this.fail('Please specify the protocol for ' + _this.url);
129
- } else if (response.status === 0) {
130
- return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
131
- } else if (response.status === 404) {
132
- return _this.fail('Can\'t read swagger JSON from ' + _this.url);
133
- } else {
134
- return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
135
- }
136
- },
137
- response: function(resp) {
138
- var responseObj = resp.obj || JSON.parse(resp.data);
139
- _this.swaggerVersion = responseObj.swaggerVersion;
140
- if (_this.swaggerVersion === "1.2") {
141
- return _this.buildFromSpec(responseObj);
142
- } else {
143
- return _this.buildFrom1_1Spec(responseObj);
144
- }
145
- }
146
- }
147
- };
148
- var e = (typeof window !== 'undefined' ? window : exports);
149
- e.authorizations.apply(obj);
150
- new SwaggerHttp().execute(obj);
151
- return this;
152
- };
153
-
154
- SwaggerApi.prototype.buildFromSpec = function(response) {
155
- if (response.apiVersion != null) {
156
- this.apiVersion = response.apiVersion;
157
- }
158
- this.apis = {};
159
- this.apisArray = [];
160
- this.consumes = response.consumes;
161
- this.produces = response.produces;
162
- this.authSchemes = response.authorizations;
163
- if (response.info != null) {
164
- this.info = response.info;
165
- }
166
- var isApi = false;
167
- var i;
168
- for (i = 0; i < response.apis.length; i++) {
169
- var api = response.apis[i];
170
- if (api.operations) {
171
- var j;
172
- for (j = 0; j < api.operations.length; j++) {
173
- operation = api.operations[j];
174
- isApi = true;
175
- }
176
- }
177
- }
178
- if (response.basePath)
179
- this.basePath = response.basePath;
180
- else if (this.url.indexOf('?') > 0)
181
- this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
182
- else
183
- this.basePath = this.url;
184
-
185
- if (isApi) {
186
- var newName = response.resourcePath.replace(/\//g, '');
187
- this.resourcePath = response.resourcePath;
188
- res = new SwaggerResource(response, this);
189
- this.apis[newName] = res;
190
- this.apisArray.push(res);
191
- } else {
192
- var k;
193
- for (k = 0; k < response.apis.length; k++) {
194
- var resource = response.apis[k];
195
- res = new SwaggerResource(resource, this);
196
- this.apis[res.name] = res;
197
- this.apisArray.push(res);
198
- }
199
- }
200
- if (this.success) {
201
- this.success();
202
- }
203
- return this;
204
- };
205
-
206
- SwaggerApi.prototype.buildFrom1_1Spec = function(response) {
207
- log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
208
- if (response.apiVersion != null)
209
- this.apiVersion = response.apiVersion;
210
- this.apis = {};
211
- this.apisArray = [];
212
- this.produces = response.produces;
213
- if (response.info != null) {
214
- this.info = response.info;
215
- }
216
- var isApi = false;
217
- for (var i = 0; i < response.apis.length; i++) {
218
- var api = response.apis[i];
219
- if (api.operations) {
220
- for (var j = 0; j < api.operations.length; j++) {
221
- operation = api.operations[j];
222
- isApi = true;
223
- }
224
- }
225
- }
226
- if (response.basePath) {
227
- this.basePath = response.basePath;
228
- } else if (this.url.indexOf('?') > 0) {
229
- this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
230
- } else {
231
- this.basePath = this.url;
232
- }
233
- if (isApi) {
234
- var newName = response.resourcePath.replace(/\//g, '');
235
- this.resourcePath = response.resourcePath;
236
- var res = new SwaggerResource(response, this);
237
- this.apis[newName] = res;
238
- this.apisArray.push(res);
239
- } else {
240
- for (k = 0; k < response.apis.length; k++) {
241
- resource = response.apis[k];
242
- res = new SwaggerResource(resource, this);
243
- this.apis[res.name] = res;
244
- this.apisArray.push(res);
245
- }
246
- }
247
- if (this.success) {
248
- this.success();
249
- }
250
- return this;
251
- };
252
-
253
- SwaggerApi.prototype.selfReflect = function() {
254
- var resource, resource_name, _ref;
255
- if (this.apis == null) {
256
- return false;
257
- }
258
- _ref = this.apis;
259
- for (resource_name in _ref) {
260
- resource = _ref[resource_name];
261
- if (resource.ready == null) {
262
- return false;
263
- }
264
- }
265
- this.setConsolidatedModels();
266
- this.ready = true;
267
- if (this.success != null) {
268
- return this.success();
269
- }
270
- };
271
-
272
- SwaggerApi.prototype.fail = function(message) {
273
- this.failure(message);
274
- throw message;
275
- };
276
-
277
- SwaggerApi.prototype.setConsolidatedModels = function() {
278
- var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
279
- this.modelsArray = [];
280
- this.models = {};
281
- _ref = this.apis;
282
- for (resource_name in _ref) {
283
- resource = _ref[resource_name];
284
- for (modelName in resource.models) {
285
- if (this.models[modelName] == null) {
286
- this.models[modelName] = resource.models[modelName];
287
- this.modelsArray.push(resource.models[modelName]);
288
- }
289
- }
290
- }
291
- _ref1 = this.modelsArray;
292
- _results = [];
293
- for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
294
- model = _ref1[_i];
295
- _results.push(model.setReferencedModels(this.models));
296
- }
297
- return _results;
298
- };
299
-
300
- SwaggerApi.prototype.help = function() {
301
- var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
302
- _ref = this.apis;
303
- for (resource_name in _ref) {
304
- resource = _ref[resource_name];
305
- log(resource_name);
306
- _ref1 = resource.operations;
307
- for (operation_name in _ref1) {
308
- operation = _ref1[operation_name];
309
- log(" " + operation.nickname);
310
- _ref2 = operation.parameters;
311
- for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
312
- parameter = _ref2[_i];
313
- log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
314
- }
315
- }
316
- }
317
- return this;
318
- };
319
-
320
- var SwaggerResource = function(resourceObj, api) {
321
- var _this = this;
322
- this.api = api;
323
- this.api = this.api;
324
- consumes = (this.consumes | []);
325
- produces = (this.produces | []);
326
- this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
327
- this.description = resourceObj.description;
328
-
329
- var parts = this.path.split("/");
330
- this.name = parts[parts.length - 1].replace('.{format}', '');
331
- this.basePath = this.api.basePath;
332
- this.operations = {};
333
- this.operationsArray = [];
334
- this.modelsArray = [];
335
- this.models = {};
336
- this.rawModels = {};
337
- this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
338
-
339
- if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
340
- this.addApiDeclaration(resourceObj);
341
- } else {
342
- if (this.path == null) {
343
- this.api.fail("SwaggerResources must have a path.");
344
- }
345
- if (this.path.substring(0, 4) === 'http') {
346
- this.url = this.path.replace('{format}', 'json');
347
- } else {
348
- this.url = this.api.basePath + this.path.replace('{format}', 'json');
349
- }
350
- this.api.progress('fetching resource ' + this.name + ': ' + this.url);
351
- obj = {
352
- url: this.url,
353
- method: "get",
354
- useJQuery: this.useJQuery,
355
- headers: {
356
- accept: "application/json"
357
- },
358
- on: {
359
- response: function(resp) {
360
- var responseObj = resp.obj || JSON.parse(resp.data);
361
- return _this.addApiDeclaration(responseObj);
362
- },
363
- error: function(response) {
364
- return _this.api.fail("Unable to read api '" +
365
- _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
366
- }
367
- }
368
- };
369
- var e = typeof window !== 'undefined' ? window : exports;
370
- e.authorizations.apply(obj);
371
- new SwaggerHttp().execute(obj);
372
- }
373
- }
374
-
375
- SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
376
- var pos, url;
377
- url = this.api.basePath;
378
- pos = url.lastIndexOf(relativeBasePath);
379
- var parts = url.split("/");
380
- var rootUrl = parts[0] + "//" + parts[2];
381
-
382
- if(relativeBasePath.indexOf("http") === 0)
383
- return relativeBasePath;
384
- if(relativeBasePath === "/")
385
- return rootUrl;
386
- if(relativeBasePath.substring(0, 1) == "/") {
387
- // use root + relative
388
- return rootUrl + relativeBasePath;
389
- }
390
- else {
391
- var pos = this.basePath.lastIndexOf("/");
392
- var base = this.basePath.substring(0, pos);
393
- if(base.substring(base.length - 1) == "/")
394
- return base + relativeBasePath;
395
- else
396
- return base + "/" + relativeBasePath;
397
- }
398
- };
399
-
400
- SwaggerResource.prototype.addApiDeclaration = function(response) {
401
- if (response.produces != null)
402
- this.produces = response.produces;
403
- if (response.consumes != null)
404
- this.consumes = response.consumes;
405
- if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
406
- this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
407
-
408
- this.addModels(response.models);
409
- if (response.apis) {
410
- for (var i = 0 ; i < response.apis.length; i++) {
411
- var endpoint = response.apis[i];
412
- this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
413
- }
414
- }
415
- this.api[this.name] = this;
416
- this.ready = true;
417
- return this.api.selfReflect();
418
- };
419
-
420
- SwaggerResource.prototype.addModels = function(models) {
421
- if (models != null) {
422
- var modelName;
423
- for (modelName in models) {
424
- if (this.models[modelName] == null) {
425
- var swaggerModel = new SwaggerModel(modelName, models[modelName]);
426
- this.modelsArray.push(swaggerModel);
427
- this.models[modelName] = swaggerModel;
428
- this.rawModels[modelName] = models[modelName];
429
- }
430
- }
431
- var output = [];
432
- for (var i = 0; i < this.modelsArray.length; i++) {
433
- model = this.modelsArray[i];
434
- output.push(model.setReferencedModels(this.models));
435
- }
436
- return output;
437
- }
438
- };
439
-
440
- SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, produces) {
441
- if (ops) {
442
- output = [];
443
- for (var i = 0; i < ops.length; i++) {
444
- o = ops[i];
445
- consumes = this.consumes;
446
- produces = this.produces;
447
- if (o.consumes != null)
448
- consumes = o.consumes;
449
- else
450
- consumes = this.consumes;
451
-
452
- if (o.produces != null)
453
- produces = o.produces;
454
- else
455
- produces = this.produces;
456
- type = (o.type||o.responseClass);
457
-
458
- if (type === "array") {
459
- ref = null;
460
- if (o.items)
461
- ref = o.items["type"] || o.items["$ref"];
462
- type = "array[" + ref + "]";
463
- }
464
- responseMessages = o.responseMessages;
465
- method = o.method;
466
- if (o.httpMethod) {
467
- method = o.httpMethod;
468
- }
469
- if (o.supportedContentTypes) {
470
- consumes = o.supportedContentTypes;
471
- }
472
- if (o.errorResponses) {
473
- responseMessages = o.errorResponses;
474
- for (var j = 0; j < responseMessages.length; j++) {
475
- r = responseMessages[j];
476
- r.message = r.reason;
477
- r.reason = null;
478
- }
479
- }
480
- o.nickname = this.sanitize(o.nickname);
481
- op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations);
482
- this.operations[op.nickname] = op;
483
- output.push(this.operationsArray.push(op));
484
- }
485
- return output;
486
- }
487
- };
488
-
489
- SwaggerResource.prototype.sanitize = function(nickname) {
490
- var op;
491
- op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
492
- op = op.replace(/((_){2,})/g, '_');
493
- op = op.replace(/^(_)*/g, '');
494
- op = op.replace(/([_])*$/g, '');
495
- return op;
496
- };
497
-
498
- SwaggerResource.prototype.help = function() {
499
- var op = this.operations;
500
- var output = [];
501
- var operation_name;
502
- for (operation_name in op) {
503
- operation = op[operation_name];
504
- var msg = " " + operation.nickname;
505
- for (var i = 0; i < operation.parameters; i++) {
506
- parameter = operation.parameters[i];
507
- msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
508
- }
509
- output.push(msg);
510
- }
511
- return output;
512
- };
513
-
514
- var SwaggerModel = function(modelName, obj) {
515
- this.name = obj.id != null ? obj.id : modelName;
516
- this.properties = [];
517
- var propertyName;
518
- for (propertyName in obj.properties) {
519
- if (obj.required != null) {
520
- var value;
521
- for (value in obj.required) {
522
- if (propertyName === obj.required[value]) {
523
- obj.properties[propertyName].required = true;
524
- }
525
- }
526
- }
527
- prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
528
- this.properties.push(prop);
529
- }
530
- }
531
-
532
- SwaggerModel.prototype.setReferencedModels = function(allModels) {
533
- var results = [];
534
- for (var i = 0; i < this.properties.length; i++) {
535
- var property = this.properties[i];
536
- var type = property.type || property.dataType;
537
- if (allModels[type] != null)
538
- results.push(property.refModel = allModels[type]);
539
- else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
540
- results.push(property.refModel = allModels[property.refDataType]);
541
- else
542
- results.push(void 0);
543
- }
544
- return results;
545
- };
546
-
547
- SwaggerModel.prototype.getMockSignature = function(modelsToIgnore) {
548
- var propertiesStr = [];
549
- for (var i = 0; i < this.properties.length; i++) {
550
- prop = this.properties[i];
551
- propertiesStr.push(prop.toString());
552
- }
553
-
554
- var strong = '<span class="strong">';
555
- var stronger = '<span class="stronger">';
556
- var strongClose = '</span>';
557
- var classOpen = strong + this.name + ' {' + strongClose;
558
- var classClose = strong + '}' + strongClose;
559
- var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
560
- if (!modelsToIgnore)
561
- modelsToIgnore = [];
562
- modelsToIgnore.push(this.name);
563
-
564
- for (var i = 0; i < this.properties.length; i++) {
565
- prop = this.properties[i];
566
- if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
567
- returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
568
- }
569
- }
570
- return returnVal;
571
- };
572
-
573
- SwaggerModel.prototype.createJSONSample = function(modelsToIgnore) {
574
- if(sampleModels[this.name]) {
575
- return sampleModels[this.name];
576
- }
577
- else {
578
- var result = {};
579
- var modelsToIgnore = (modelsToIgnore||[])
580
- modelsToIgnore.push(this.name);
581
- for (var i = 0; i < this.properties.length; i++) {
582
- prop = this.properties[i];
583
- result[prop.name] = prop.getSampleValue(modelsToIgnore);
584
- }
585
- modelsToIgnore.pop(this.name);
586
- return result;
587
- }
588
- };
589
-
590
- var SwaggerModelProperty = function(name, obj) {
591
- this.name = name;
592
- this.dataType = obj.type || obj.dataType || obj["$ref"];
593
- this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
594
- this.descr = obj.description;
595
- this.required = obj.required;
596
- if (obj.items != null) {
597
- if (obj.items.type != null) {
598
- this.refDataType = obj.items.type;
599
- }
600
- if (obj.items.$ref != null) {
601
- this.refDataType = obj.items.$ref;
602
- }
603
- }
604
- this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
605
- if (obj.allowableValues != null) {
606
- this.valueType = obj.allowableValues.valueType;
607
- this.values = obj.allowableValues.values;
608
- if (this.values != null) {
609
- this.valuesString = "'" + this.values.join("' or '") + "'";
610
- }
611
- }
612
- if (obj["enum"] != null) {
613
- this.valueType = "string";
614
- this.values = obj["enum"];
615
- if (this.values != null) {
616
- this.valueString = "'" + this.values.join("' or '") + "'";
617
- }
618
- }
619
- }
620
-
621
- SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) {
622
- var result;
623
- if ((this.refModel != null) && (modelsToIgnore.indexOf(prop.refModel.name) === -1)) {
624
- result = this.refModel.createJSONSample(modelsToIgnore);
625
- } else {
626
- if (this.isCollection) {
627
- result = this.toSampleValue(this.refDataType);
628
- } else {
629
- result = this.toSampleValue(this.dataType);
630
- }
631
- }
632
- if (this.isCollection) {
633
- return [result];
634
- } else {
635
- return result;
636
- }
637
- };
638
-
639
- SwaggerModelProperty.prototype.toSampleValue = function(value) {
640
- var result;
641
- if (value === "integer") {
642
- result = 0;
643
- } else if (value === "boolean") {
644
- result = false;
645
- } else if (value === "double" || value === "number") {
646
- result = 0.0;
647
- } else if (value === "string") {
648
- result = "";
649
- } else {
650
- result = value;
651
- }
652
- return result;
653
- };
654
-
655
- SwaggerModelProperty.prototype.toString = function() {
656
- var req = this.required ? 'propReq' : 'propOpt';
657
- var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
658
- if (!this.required) {
659
- str += ', <span class="propOptKey">optional</span>';
660
- }
661
- str += ')';
662
- if (this.values != null) {
663
- str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
664
- }
665
- if (this.descr != null) {
666
- str += ': <span class="propDesc">' + this.descr + '</span>';
667
- }
668
- return str;
669
- };
670
-
671
- var SwaggerOperation = function(nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations) {
672
- var _this = this;
673
-
674
- var errors = [];
675
- this.nickname = (nickname||errors.push("SwaggerOperations must have a nickname."));
676
- this.path = (path||errors.push("SwaggerOperation " + nickname + " is missing path."));
677
- this.method = (method||errors.push("SwaggerOperation " + nickname + " is missing method."));
678
- this.parameters = parameters != null ? parameters : [];
679
- this.summary = summary;
680
- this.notes = notes;
681
- this.type = type;
682
- this.responseMessages = (responseMessages||[]);
683
- this.resource = (resource||errors.push("Resource is required"));
684
- this.consumes = consumes;
685
- this.produces = produces;
686
- this.authorizations = authorizations;
687
- this["do"] = __bind(this["do"], this);
688
-
689
- if (errors.length > 0)
690
- this.resource.api.fail(errors);
691
-
692
- this.path = this.path.replace('{format}', 'json');
693
- this.method = this.method.toLowerCase();
694
- this.isGetMethod = this.method === "get";
695
-
696
- this.resourceName = this.resource.name;
697
- if(typeof this.type !== 'undefined' && this.type === 'void')
698
- this.type = null;
699
- else {
700
- this.responseClassSignature = this.getSignature(this.type, this.resource.models);
701
- this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
702
- }
703
-
704
- for(var i = 0; i < this.parameters.length; i ++) {
705
- var param = this.parameters[i];
706
- // might take this away
707
- param.name = param.name || param.type || param.dataType;
708
-
709
- // for 1.1 compatibility
710
- var type = param.type || param.dataType;
711
- if(type === 'array') {
712
- type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
713
- }
714
- param.type = type;
715
-
716
- if(type.toLowerCase() === 'boolean') {
717
- param.allowableValues = {};
718
- param.allowableValues.values = ["true", "false"];
719
- }
720
- param.signature = this.getSignature(type, this.resource.models);
721
- param.sampleJSON = this.getSampleJSON(type, this.resource.models);
722
-
723
- var enumValue = param["enum"];
724
- if(enumValue != null) {
725
- param.isList = true;
726
- param.allowableValues = {};
727
- param.allowableValues.descriptiveValues = [];
728
-
729
- for(var j = 0; j < enumValue.length; j++) {
730
- var v = enumValue[j];
731
- if(param.defaultValue != null) {
732
- param.allowableValues.descriptiveValues.push ({
733
- value: String(v),
734
- isDefault: (v === param.defaultValue)
735
- });
736
- }
737
- else {
738
- param.allowableValues.descriptiveValues.push ({
739
- value: String(v),
740
- isDefault: false
741
- });
742
- }
743
- }
744
- }
745
- else if(param.allowableValues != null) {
746
- if(param.allowableValues.valueType === "RANGE")
747
- param.isRange = true;
748
- else
749
- param.isList = true;
750
- if(param.allowableValues != null) {
751
- param.allowableValues.descriptiveValues = [];
752
- if(param.allowableValues.values) {
753
- for(var j = 0; j < param.allowableValues.values.length; j++){
754
- var v = param.allowableValues.values[j];
755
- if(param.defaultValue != null) {
756
- param.allowableValues.descriptiveValues.push ({
757
- value: String(v),
758
- isDefault: (v === param.defaultValue)
759
- });
760
- }
761
- else {
762
- param.allowableValues.descriptiveValues.push ({
763
- value: String(v),
764
- isDefault: false
765
- });
766
- }
767
- }
768
- }
769
- }
770
- }
771
- }
772
- this.resource[this.nickname] = function(args, callback, error) {
773
- return _this["do"](args, callback, error);
774
- };
775
- this.resource[this.nickname].help = function() {
776
- return _this.help();
777
- };
778
- }
779
-
780
- SwaggerOperation.prototype.isListType = function(type) {
781
- if (type && type.indexOf('[') >= 0) {
782
- return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
783
- } else {
784
- return void 0;
785
- }
786
- };
787
-
788
- SwaggerOperation.prototype.getSignature = function(type, models) {
789
- var isPrimitive, listType;
790
- listType = this.isListType(type);
791
- isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
792
- if (isPrimitive) {
793
- return type;
794
- } else {
795
- if (listType != null) {
796
- return models[listType].getMockSignature();
797
- } else {
798
- return models[type].getMockSignature();
799
- }
800
- }
801
- };
802
-
803
- SwaggerOperation.prototype.getSampleJSON = function(type, models) {
804
- var isPrimitive, listType, val;
805
- listType = this.isListType(type);
806
- isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
807
- val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
808
- if (val) {
809
- val = listType ? [val] : val;
810
- if(typeof val == "string")
811
- return val;
812
- else if(typeof val === "object") {
813
- var t = val;
814
- if(val instanceof Array && val.length > 0) {
815
- t = val[0];
816
- }
817
- if(t.nodeName) {
818
- var xmlString = new XMLSerializer().serializeToString(t);
819
- return this.formatXml(xmlString);
820
- }
821
- else
822
- return JSON.stringify(val, null, 2);
823
- }
824
- else
825
- return val;
826
- }
827
- };
828
-
829
- SwaggerOperation.prototype["do"] = function(args, opts, callback, error) {
830
- var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
831
- if (args == null) {
832
- args = {};
833
- }
834
- if (opts == null) {
835
- opts = {};
836
- }
837
- requestContentType = null;
838
- responseContentType = null;
839
- if ((typeof args) === "function") {
840
- error = opts;
841
- callback = args;
842
- args = {};
843
- }
844
- if ((typeof opts) === "function") {
845
- error = callback;
846
- callback = opts;
847
- }
848
- if (error == null) {
849
- error = function(xhr, textStatus, error) {
850
- return log(xhr, textStatus, error);
851
- };
852
- }
853
- if (callback == null) {
854
- callback = function(response) {
855
- var content;
856
- content = null;
857
- if (response != null) {
858
- content = response.data;
859
- } else {
860
- content = "no data";
861
- }
862
- return log("default callback: " + content);
863
- };
864
- }
865
- params = {};
866
- params.headers = [];
867
- if (args.headers != null) {
868
- params.headers = args.headers;
869
- delete args.headers;
870
- }
871
-
872
- var possibleParams = [];
873
- for(var i = 0; i < this.parameters.length; i++) {
874
- var param = this.parameters[i];
875
- if(param.paramType === 'header') {
876
- if(args[param.name])
877
- params.headers[param.name] = args[param.name];
878
- }
879
- else if(param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
880
- possibleParams.push(param);
881
- }
882
-
883
- if (args.body != null) {
884
- params.body = args.body;
885
- delete args.body;
886
- }
887
-
888
- if (possibleParams) {
889
- var key;
890
- for (key in possibleParams) {
891
- value = possibleParams[key];
892
- if (args[value.name]) {
893
- params[value.name] = args[value.name];
894
- }
895
- }
896
- }
897
-
898
- req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
899
- if (opts.mock != null) {
900
- return req;
901
- } else {
902
- return true;
903
- }
904
- };
905
-
906
- SwaggerOperation.prototype.pathJson = function() {
907
- return this.path.replace("{format}", "json");
908
- };
909
-
910
- SwaggerOperation.prototype.pathXml = function() {
911
- return this.path.replace("{format}", "xml");
912
- };
913
-
914
- SwaggerOperation.prototype.encodePathParam = function(pathParam) {
915
- var encParts, part, parts, _i, _len;
916
- pathParam = pathParam.toString();
917
- if (pathParam.indexOf("/") === -1) {
918
- return encodeURIComponent(pathParam);
919
- } else {
920
- parts = pathParam.split("/");
921
- encParts = [];
922
- for (_i = 0, _len = parts.length; _i < _len; _i++) {
923
- part = parts[_i];
924
- encParts.push(encodeURIComponent(part));
925
- }
926
- return encParts.join("/");
927
- }
928
- };
929
-
930
- SwaggerOperation.prototype.urlify = function(args) {
931
- var url = this.resource.basePath + this.pathJson();
932
- var params = this.parameters;
933
- for(var i = 0; i < params.length; i ++){
934
- var param = params[i];
935
- if (param.paramType === 'path') {
936
- if(args[param.name]) {
937
- // apply path params and remove from args
938
- var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
939
- url = url.replace(reg, this.encodePathParam(args[param.name]));
940
- delete args[param.name];
941
- }
942
- else
943
- throw "" + param.name + " is a required path param.";
944
- }
945
- }
946
-
947
- var queryParams = "";
948
- for(var i = 0; i < params.length; i ++){
949
- var param = params[i];
950
- if(param.paramType === 'query') {
951
- if (args[param.name] !== undefined) {
952
- if (queryParams !== '')
953
- queryParams += "&";
954
- queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
955
- }
956
- }
957
- }
958
- if ((queryParams != null) && queryParams.length > 0)
959
- url += '?' + queryParams;
960
- return url;
961
- };
962
-
963
- SwaggerOperation.prototype.supportHeaderParams = function() {
964
- return this.resource.api.supportHeaderParams;
965
- };
966
-
967
- SwaggerOperation.prototype.supportedSubmitMethods = function() {
968
- return this.resource.api.supportedSubmitMethods;
969
- };
970
-
971
- SwaggerOperation.prototype.getQueryParams = function(args) {
972
- return this.getMatchingParams(['query'], args);
973
- };
974
-
975
- SwaggerOperation.prototype.getHeaderParams = function(args) {
976
- return this.getMatchingParams(['header'], args);
977
- };
978
-
979
- SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) {
980
- var matchingParams = {};
981
- var params = this.parameters;
982
- for (var i = 0; i < params.length; i++) {
983
- param = params[i];
984
- if (args && args[param.name])
985
- matchingParams[param.name] = args[param.name];
986
- }
987
- var headers = this.resource.api.headers;
988
- var name;
989
- for (name in headers) {
990
- var value = headers[name];
991
- matchingParams[name] = value;
992
- }
993
- return matchingParams;
994
- };
995
-
996
- SwaggerOperation.prototype.help = function() {
997
- var msg = "";
998
- var params = this.parameters;
999
- for (var i = 0; i < params.length; i++) {
1000
- var param = params[i];
1001
- if (msg !== "")
1002
- msg += "\n";
1003
- msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
1004
- }
1005
- return msg;
1006
- };
1007
-
1008
-
1009
- SwaggerOperation.prototype.formatXml = function(xml) {
1010
- var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
1011
- reg = /(>)(<)(\/*)/g;
1012
- wsexp = /[ ]*(.*)[ ]+\n/g;
1013
- contexp = /(<.+>)(.+\n)/g;
1014
- xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
1015
- pad = 0;
1016
- formatted = '';
1017
- lines = xml.split('\n');
1018
- indent = 0;
1019
- lastType = 'other';
1020
- transitions = {
1021
- 'single->single': 0,
1022
- 'single->closing': -1,
1023
- 'single->opening': 0,
1024
- 'single->other': 0,
1025
- 'closing->single': 0,
1026
- 'closing->closing': -1,
1027
- 'closing->opening': 0,
1028
- 'closing->other': 0,
1029
- 'opening->single': 1,
1030
- 'opening->closing': 0,
1031
- 'opening->opening': 1,
1032
- 'opening->other': 1,
1033
- 'other->single': 0,
1034
- 'other->closing': -1,
1035
- 'other->opening': 0,
1036
- 'other->other': 0
1037
- };
1038
- _fn = function(ln) {
1039
- var fromTo, j, key, padding, type, types, value;
1040
- types = {
1041
- single: Boolean(ln.match(/<.+\/>/)),
1042
- closing: Boolean(ln.match(/<\/.+>/)),
1043
- opening: Boolean(ln.match(/<[^!?].*>/))
1044
- };
1045
- type = ((function() {
1046
- var _results;
1047
- _results = [];
1048
- for (key in types) {
1049
- value = types[key];
1050
- if (value) {
1051
- _results.push(key);
1052
- }
1053
- }
1054
- return _results;
1055
- })())[0];
1056
- type = type === void 0 ? 'other' : type;
1057
- fromTo = lastType + '->' + type;
1058
- lastType = type;
1059
- padding = '';
1060
- indent += transitions[fromTo];
1061
- padding = ((function() {
1062
- var _j, _ref5, _results;
1063
- _results = [];
1064
- for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
1065
- _results.push(' ');
1066
- }
1067
- return _results;
1068
- })()).join('');
1069
- if (fromTo === 'opening->closing') {
1070
- return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
1071
- } else {
1072
- return formatted += padding + ln + '\n';
1073
- }
1074
- };
1075
- for (_i = 0, _len = lines.length; _i < _len; _i++) {
1076
- ln = lines[_i];
1077
- _fn(ln);
1078
- }
1079
- return formatted;
1080
- };
1081
-
1082
- var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) {
1083
- var _this = this;
1084
- var errors = [];
1085
- this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
1086
- this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
1087
- this.url = (url||errors.push("SwaggerRequest url is required."));
1088
- this.params = params;
1089
- this.opts = opts;
1090
- this.successCallback = (successCallback||errors.push("SwaggerRequest successCallback is required."));
1091
- this.errorCallback = (errorCallback||errors.push("SwaggerRequest error callback is required."));
1092
- this.operation = (operation||errors.push("SwaggerRequest operation is required."));
1093
- this.execution = execution;
1094
- this.headers = (params.headers||{});
1095
-
1096
- if(errors.length > 0) {
1097
- throw errors;
1098
- }
1099
-
1100
- this.type = this.type.toUpperCase();
1101
-
1102
- // set request, response content type headers
1103
- var headers = this.setHeaders(params, this.operation);
1104
- var body = params.body;
1105
-
1106
- // encode the body for form submits
1107
- if (headers["Content-Type"]) {
1108
- var values = {};
1109
- var i;
1110
- var operationParams = this.operation.parameters;
1111
- for(i = 0; i < operationParams.length; i++) {
1112
- var param = operationParams[i];
1113
- if(param.paramType === "form")
1114
- values[param.name] = param;
1115
- }
1116
-
1117
- if(headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) {
1118
- var encoded = "";
1119
- var key;
1120
- for(key in values) {
1121
- value = this.params[key];
1122
- if(typeof value !== 'undefined'){
1123
- if(encoded !== "")
1124
- encoded += "&";
1125
- encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
1126
- }
1127
- }
1128
- body = encoded;
1129
- }
1130
- else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) {
1131
- // encode the body for form submits
1132
- var data = "";
1133
- var boundary = "----SwaggerFormBoundary" + Date.now();
1134
- var key;
1135
- for(key in values) {
1136
- value = this.params[key];
1137
- if(typeof value !== 'undefined') {
1138
- data += '--' + boundary + '\n';
1139
- data += 'Content-Disposition: form-data; name="' + key + '"';
1140
- data += '\n\n';
1141
- data += value + "\n";
1142
- }
1143
- }
1144
- data += "--" + boundary + "--\n";
1145
- headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
1146
- body = data;
1147
- }
1148
- }
1149
-
1150
- if (!((this.headers != null) && (this.headers.mock != null))) {
1151
- obj = {
1152
- url: this.url,
1153
- method: this.type,
1154
- headers: headers,
1155
- body: body,
1156
- useJQuery: this.useJQuery,
1157
- on: {
1158
- error: function(response) {
1159
- return _this.errorCallback(response, _this.opts.parent);
1160
- },
1161
- redirect: function(response) {
1162
- return _this.successCallback(response, _this.opts.parent);
1163
- },
1164
- 307: function(response) {
1165
- return _this.successCallback(response, _this.opts.parent);
1166
- },
1167
- response: function(response) {
1168
- return _this.successCallback(response, _this.opts.parent);
1169
- }
1170
- }
1171
- };
1172
- var e;
1173
- if (typeof window !== 'undefined') {
1174
- e = window;
1175
- } else {
1176
- e = exports;
1177
- }
1178
- status = e.authorizations.apply(obj, this.operation.authorizations);
1179
- if (opts.mock == null) {
1180
- if (status !== false) {
1181
- new SwaggerHttp().execute(obj);
1182
- } else {
1183
- obj.canceled = true;
1184
- }
1185
- } else {
1186
- return obj;
1187
- }
1188
- }
1189
- };
1190
-
1191
- SwaggerRequest.prototype.setHeaders = function(params, operation) {
1192
- // default type
1193
- var accepts = "application/json";
1194
- var consumes = "application/json";
1195
-
1196
- var allDefinedParams = this.operation.parameters;
1197
- var definedFormParams = [];
1198
- var definedFileParams = [];
1199
- var body = params.body;
1200
- var headers = {};
1201
-
1202
- // get params from the operation and set them in definedFileParams, definedFormParams, headers
1203
- var i;
1204
- for(i = 0; i < allDefinedParams.length; i++) {
1205
- var param = allDefinedParams[i];
1206
- if(param.paramType === "form")
1207
- definedFormParams.push(param);
1208
- else if(param.paramType === "file")
1209
- definedFileParams.push(param);
1210
- else if(param.paramType === "header" && this.params.headers) {
1211
- var key = param.name;
1212
- var headerValue = this.params.headers[param.name];
1213
- if(typeof this.params.headers[param.name] !== 'undefined')
1214
- headers[key] = headerValue;
1215
- }
1216
- }
1217
-
1218
- // if there's a body, need to set the accepts header via requestContentType
1219
- if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) {
1220
- if (this.opts.requestContentType)
1221
- accepts = this.opts.requestContentType;
1222
- } else {
1223
- // if any form params, content type must be set
1224
- if(definedFormParams.length > 0) {
1225
- if(definedFileParams.length > 0)
1226
- consumes = "multipart/form-data";
1227
- else
1228
- consumes = "application/x-www-form-urlencoded";
1229
- }
1230
- else if (this.type == "DELETE")
1231
- body = "{}";
1232
- else if (this.type != "DELETE")
1233
- accepts = null;
1234
- }
1235
-
1236
- if (consumes && this.operation.consumes) {
1237
- if (this.operation.consumes.indexOf(consumes) === -1) {
1238
- log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes));
1239
- consumes = this.operation.consumes[0];
1240
- }
1241
- }
1242
-
1243
- if (this.opts.responseContentType) {
1244
- accepts = this.opts.responseContentType;
1245
- } else {
1246
- accepts = "application/json";
1247
- }
1248
- if (accepts && this.operation.produces) {
1249
- if (this.operation.produces.indexOf(accepts) === -1) {
1250
- log("server can't produce " + accepts);
1251
- accepts = this.operation.produces[0];
1252
- }
1253
- }
1254
-
1255
- if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded"))
1256
- headers["Content-Type"] = consumes;
1257
- if (accepts)
1258
- headers["Accept"] = accepts;
1259
- return headers;
1260
- }
1261
-
1262
- SwaggerRequest.prototype.asCurl = function() {
1263
- var results = [];
1264
- if(this.headers) {
1265
- var key;
1266
- for(key in this.headers) {
1267
- results.push("--header \"" + key + ": " + this.headers[v] + "\"");
1268
- }
1269
- }
1270
- return "curl " + (results.join(" ")) + " " + this.url;
1271
- };
1272
-
1273
- /**
1274
- * SwaggerHttp is a wrapper for executing requests
1275
- */
1276
- var SwaggerHttp = function() {};
1277
-
1278
- SwaggerHttp.prototype.execute = function(obj) {
1279
- if(obj && (typeof obj.useJQuery === 'boolean'))
1280
- this.useJQuery = obj.useJQuery;
1281
- else
1282
- this.useJQuery = this.isIE8();
1283
-
1284
- if(this.useJQuery)
1285
- return new JQueryHttpClient().execute(obj);
1286
- else
1287
- return new ShredHttpClient().execute(obj);
1288
- }
1289
-
1290
- SwaggerHttp.prototype.isIE8 = function() {
1291
- var detectedIE = false;
1292
- if (typeof navigator !== 'undefined' && navigator.userAgent) {
1293
- nav = navigator.userAgent.toLowerCase();
1294
- if (nav.indexOf('msie') !== -1) {
1295
- var version = parseInt(nav.split('msie')[1]);
1296
- if (version <= 8) {
1297
- detectedIE = true;
1298
- }
1299
- }
1300
- }
1301
- return detectedIE;
1302
- };
1303
-
1304
- /*
1305
- * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
1306
- * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
1307
- * Since we are using closures here we need to alias it for internal use.
1308
- */
1309
- var JQueryHttpClient = function(options) {
1310
- "use strict";
1311
- if(!jQuery){
1312
- var jQuery = window.jQuery;
1313
- }
1314
- }
1315
-
1316
- JQueryHttpClient.prototype.execute = function(obj) {
1317
- var cb = obj.on;
1318
- var request = obj;
1319
-
1320
- obj.type = obj.method;
1321
- obj.cache = false;
1322
-
1323
- obj.beforeSend = function(xhr) {
1324
- var key, results;
1325
- if (obj.headers) {
1326
- results = [];
1327
- var key;
1328
- for (key in obj.headers) {
1329
- if (key.toLowerCase() === "content-type") {
1330
- results.push(obj.contentType = obj.headers[key]);
1331
- } else if (key.toLowerCase() === "accept") {
1332
- results.push(obj.accepts = obj.headers[key]);
1333
- } else {
1334
- results.push(xhr.setRequestHeader(key, obj.headers[key]));
1335
- }
1336
- }
1337
- return results;
1338
- }
1339
- };
1340
-
1341
- obj.data = obj.body;
1342
- obj.complete = function(response, textStatus, opts) {
1343
- var headers = {},
1344
- headerArray = response.getAllResponseHeaders().split("\n");
1345
-
1346
- for(var i = 0; i < headerArray.length; i++) {
1347
- var toSplit = headerArray[i].trim();
1348
- if(toSplit.length === 0)
1349
- continue;
1350
- var separator = toSplit.indexOf(":");
1351
- if(separator === -1) {
1352
- // Name but no value in the header
1353
- headers[toSplit] = null;
1354
- continue;
1355
- }
1356
- var name = toSplit.substring(0, separator).trim(),
1357
- value = toSplit.substring(separator + 1).trim();
1358
- headers[name] = value;
1359
- }
1360
-
1361
- var out = {
1362
- url: request.url,
1363
- method: request.method,
1364
- status: response.status,
1365
- data: response.responseText,
1366
- headers: headers
1367
- };
1368
-
1369
- var contentType = (headers["content-type"]||headers["Content-Type"]||null)
1370
-
1371
- if(contentType != null) {
1372
- if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1373
- if(response.responseText && response.responseText !== "")
1374
- out.obj = JSON.parse(response.responseText);
1375
- else
1376
- out.obj = {}
1377
- }
1378
- }
1379
-
1380
- if(response.status >= 200 && response.status < 300)
1381
- cb.response(out);
1382
- else if(response.status === 0 || (response.status >= 400 && response.status < 599))
1383
- cb.error(out);
1384
- else
1385
- return cb.response(out);
1386
- };
1387
-
1388
- jQuery.support.cors = true;
1389
- return jQuery.ajax(obj);
1390
- }
1391
-
1392
- /*
1393
- * ShredHttpClient is a light-weight, node or browser HTTP client
1394
- */
1395
- var ShredHttpClient = function(options) {
1396
- this.options = (options||{});
1397
- this.isInitialized = false;
1398
-
1399
- var identity, toString;
1400
-
1401
- if (typeof window !== 'undefined') {
1402
- this.Shred = require("./shred");
1403
- this.content = require("./shred/content");
1404
- }
1405
- else
1406
- this.Shred = require("shred");
1407
- this.shred = new this.Shred();
1408
- }
1409
-
1410
- ShredHttpClient.prototype.initShred = function () {
1411
- this.isInitialized = true;
1412
- this.registerProcessors(this.shred);
1413
- }
1414
-
1415
- ShredHttpClient.prototype.registerProcessors = function(shred) {
1416
- var identity = function(x) {
1417
- return x;
1418
- };
1419
- var toString = function(x) {
1420
- return x.toString();
1421
- };
1422
-
1423
- if (typeof window !== 'undefined') {
1424
- this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1425
- parser: identity,
1426
- stringify: toString
1427
- });
1428
- } else {
1429
- this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1430
- parser: identity,
1431
- stringify: toString
1432
- });
1433
- }
1434
- }
1435
-
1436
- ShredHttpClient.prototype.execute = function(obj) {
1437
- if(!this.isInitialized)
1438
- this.initShred();
1439
-
1440
- var cb = obj.on, res;
1441
-
1442
- var transform = function(response) {
1443
- var out = {
1444
- headers: response._headers,
1445
- url: response.request.url,
1446
- method: response.request.method,
1447
- status: response.status,
1448
- data: response.content.data
1449
- };
1450
-
1451
- var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
1452
-
1453
- if(contentType != null) {
1454
- if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1455
- if(response.content.data && response.content.data !== "")
1456
- out.obj = JSON.parse(response.content.data);
1457
- else
1458
- out.obj = {}
1459
- }
1460
- }
1461
- return out;
1462
- };
1463
-
1464
- res = {
1465
- error: function(response) {
1466
- if (obj)
1467
- return cb.error(transform(response));
1468
- },
1469
- redirect: function(response) {
1470
- if (obj)
1471
- return cb.redirect(transform(response));
1472
- },
1473
- 307: function(response) {
1474
- if (obj)
1475
- return cb.redirect(transform(response));
1476
- },
1477
- response: function(response) {
1478
- if (obj)
1479
- return cb.response(transform(response));
1480
- }
1481
- };
1482
- if (obj) {
1483
- obj.on = res;
1484
- }
1485
- return this.shred.request(obj);
1486
- };
1487
-
1488
- /**
1489
- * SwaggerAuthorizations applys the correct authorization to an operation being executed
1490
- */
1491
- var SwaggerAuthorizations = function() {
1492
- this.authz = {};
1493
- };
1494
-
1495
- SwaggerAuthorizations.prototype.add = function(name, auth) {
1496
- this.authz[name] = auth;
1497
- return auth;
1498
- };
1499
-
1500
- SwaggerAuthorizations.prototype.remove = function(name) {
1501
- return delete this.authz[name];
1502
- };
1503
-
1504
- SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
1505
- var status = null;
1506
- var key;
1507
-
1508
- // if the "authorizations" key is undefined, or has an empty array, add all keys
1509
- if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
1510
- for (key in this.authz) {
1511
- value = this.authz[key];
1512
- result = value.apply(obj, authorizations);
1513
- if (result === true)
1514
- status = true;
1515
- }
1516
- }
1517
- else {
1518
- for(name in authorizations) {
1519
- for (key in this.authz) {
1520
- if(key == name) {
1521
- value = this.authz[key];
1522
- result = value.apply(obj, authorizations);
1523
- if (result === true)
1524
- status = true;
1525
- }
1526
- }
1527
- }
1528
- }
1529
-
1530
- return status;
1531
- };
1532
-
1533
- /**
1534
- * ApiKeyAuthorization allows a query param or header to be injected
1535
- */
1536
- var ApiKeyAuthorization = function(name, value, type) {
1537
- this.name = name;
1538
- this.value = value;
1539
- this.type = type;
1540
- };
1541
-
1542
- ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
1543
- if (this.type === "query") {
1544
- if (obj.url.indexOf('?') > 0)
1545
- obj.url = obj.url + "&" + this.name + "=" + this.value;
1546
- else
1547
- obj.url = obj.url + "?" + this.name + "=" + this.value;
1548
- return true;
1549
- } else if (this.type === "header") {
1550
- obj.headers[this.name] = this.value;
1551
- return true;
1552
- }
1553
- };
1554
-
1555
- var CookieAuthorization = function(cookie) {
1556
- this.cookie = cookie;
1557
- }
1558
-
1559
- CookieAuthorization.prototype.apply = function(obj, authorizations) {
1560
- obj.cookieJar = obj.cookieJar || CookieJar();
1561
- obj.cookieJar.setCookie(this.cookie);
1562
- return true;
1563
- }
1564
-
1565
- /**
1566
- * Password Authorization is a basic auth implementation
1567
- */
1568
- var PasswordAuthorization = function(name, username, password) {
1569
- this.name = name;
1570
- this.username = username;
1571
- this.password = password;
1572
- this._btoa = null;
1573
- if (typeof window !== 'undefined')
1574
- this._btoa = btoa;
1575
- else
1576
- this._btoa = require("btoa");
1577
- };
1578
-
1579
- PasswordAuthorization.prototype.apply = function(obj, authorizations) {
1580
- var base64encoder = this._btoa;
1581
- obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
1582
- return true;
1583
- };
1584
-
1585
- var e = (typeof window !== 'undefined' ? window : exports);
1586
-
1587
- var sampleModels = {};
1588
- var cookies = {};
1589
-
1590
- e.SampleModels = sampleModels;
1591
- e.SwaggerHttp = SwaggerHttp;
1592
- e.SwaggerRequest = SwaggerRequest;
1593
- e.authorizations = new SwaggerAuthorizations();
1594
- e.ApiKeyAuthorization = ApiKeyAuthorization;
1595
- e.PasswordAuthorization = PasswordAuthorization;
1596
- e.CookieAuthorization = CookieAuthorization;
1597
- e.JQueryHttpClient = JQueryHttpClient;
1598
- e.ShredHttpClient = ShredHttpClient;
1599
- e.SwaggerOperation = SwaggerOperation;
1600
- e.SwaggerModel = SwaggerModel;
1601
- e.SwaggerModelProperty = SwaggerModelProperty;
1602
- e.SwaggerResource = SwaggerResource;
1603
- e.SwaggerApi = SwaggerApi;