4 './utils/send_sample_request_utils'
5 ], function($, _, utils) {
7 var initDynamic = function() {
9 $(".sample-request-send").off("click");
10 $(".sample-request-send").on("click", function(e) {
12 var $root = $(this).parents("article");
13 var group = $root.data("group");
14 var name = $root.data("name");
15 var version = $root.data("version");
16 sendSampleRequest(group, name, version, $(this).data("sample-request-type"));
20 $(".sample-request-clear").off("click");
21 $(".sample-request-clear").on("click", function(e) {
23 var $root = $(this).parents("article");
24 var group = $root.data("group");
25 var name = $root.data("name");
26 var version = $root.data("version");
27 clearSampleRequest(group, name, version);
31 function sendSampleRequest(group, name, version, type)
33 var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
37 $root.find(".sample-request-header:checked").each(function(i, element) {
38 var group = $(element).data("sample-request-header-group-id");
39 $root.find("[data-sample-request-header-group=\"" + group + "\"]").each(function(i, element) {
40 var key = $(element).data("sample-request-header-name");
41 var value = element.value;
42 if (typeof element.optional === 'undefined') {
43 element.optional = true;
45 if ( ! element.optional && element.defaultValue !== '') {
46 value = element.defaultValue;
53 // create JSON dictionary of parameters
56 var bodyFormData = new FormData();
58 $root.find(".sample-request-param:checked").each(function(i, element) {
59 var group = $(element).data("sample-request-param-group-id");
60 var contentType = $(element).nextAll('.sample-header-content-type-switch').first().val();
61 if (contentType == "body-json"){
62 $root.find("[data-sample-request-body-group=\"" + group + "\"]").not(function(){
63 return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
64 }).each(function(i, element) {
65 if (isJson(element.value)){
66 header['Content-Type'] = 'application/json';
67 bodyJson = element.value;
71 $root.find("[data-sample-request-param-group=\"" + group + "\"]").not(function(){
72 return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
73 }).each(function(i, element) {
74 var key = $(element).data("sample-request-param-name");
75 var value = element.value;
76 if ( ! element.optional && element.defaultValue !== '') {
77 value = element.defaultValue;
79 if (contentType == "body-form-data"){
80 header['Content-Type'] = 'multipart/form-data'
81 if (element.type == "file") {
82 value = element.files[0];
84 bodyFormData.append(key,value);
87 paramType[key] = $(element).next().text();
93 // grab user-inputted URL
94 var url = $root.find(".sample-request-url").val();
96 //Convert {param} form to :param
97 url = utils.convertPathParams(url);
99 // Insert url parameter
100 var pattern = pathToRegexp(url, null);
101 var matches = pattern.exec(url);
102 for (var i = 1; i < matches.length; i++) {
103 var key = matches[i].substr(1);
105 if (key[key.length - 1] === '?') {
107 key = key.substr(0, key.length - 1);
109 if (param[key] !== undefined) {
110 url = url.replace(matches[i], encodeURIComponent(param[key]));
112 // remove URL parameters from list
114 } else if (optional) {
115 // if parameter is optional denoted by ending '?' in param (:param?)
116 // and no parameter is given, replace parameter with empty string instead
117 url = url.replace(matches[i], '');
122 //handle nested objects and parsing fields
123 param = utils.handleNestedAndParsingFields(param, paramType);
125 //add url search parameter
126 if (header['Content-Type'] == 'application/json') {
128 // bodyJson is set to value if request body: 'body/json' was selected and manual json was input
129 // in this case, use the given bodyJson and add other params in query string
130 url = url + encodeSearchParams(param);
133 // bodyJson not set, but Content-Type: application/json header was set. In this case, send parameters
134 // as JSON body. First, try parsing fields of object with given paramType definition so that the json
135 // is valid against the parameter spec (e.g. Boolean params are boolean instead of strings in final json)
136 param = utils.tryParsingWithTypes(param, paramType);
137 param = JSON.stringify(param);
139 }else if (header['Content-Type'] == 'multipart/form-data'){
140 url = url + encodeSearchParams(param);
141 param = bodyFormData;
144 $root.find(".sample-request-response").fadeTo(250, 1);
145 $root.find(".sample-request-response-json").html("Loading...");
148 // send AJAX request, catch success or error callback
153 type : type.toUpperCase(),
154 success : displaySuccess,
158 if(header['Content-Type'] == 'multipart/form-data'){
159 delete ajaxRequest.headers['Content-Type'];
160 ajaxRequest.contentType=false;
161 ajaxRequest.processData=false;
166 function displaySuccess(data, status, jqXHR) {
169 jsonResponse = JSON.parse(jqXHR.responseText);
170 jsonResponse = JSON.stringify(jsonResponse, null, 4);
172 jsonResponse = jqXHR.responseText;
174 $root.find(".sample-request-response-json").text(jsonResponse);
178 function displayError(jqXHR, textStatus, error) {
179 var message = "Error " + jqXHR.status + ": " + error;
182 jsonResponse = JSON.parse(jqXHR.responseText);
183 jsonResponse = JSON.stringify(jsonResponse, null, 4);
185 jsonResponse = jqXHR.responseText;
189 message += "\n" + jsonResponse;
191 // flicker on previous error to make clear that there is a new response
192 if($root.find(".sample-request-response").is(":visible"))
193 $root.find(".sample-request-response").fadeTo(1, 0.1);
195 $root.find(".sample-request-response").fadeTo(250, 1);
196 $root.find(".sample-request-response-json").text(message);
201 function clearSampleRequest(group, name, version)
203 var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
205 // hide sample response
206 $root.find(".sample-request-response-json").html("");
207 $root.find(".sample-request-response").hide();
209 // reset value of parameters
210 $root.find(".sample-request-param").each(function(i, element) {
214 // restore default URL
215 var $urlElement = $root.find(".sample-request-url");
216 $urlElement.val($urlElement.prop("defaultValue"));
221 function refreshScrollSpy()
223 $('[data-spy="scroll"]').each(function () {
224 $(this).scrollspy("refresh");
228 function escapeHtml(str) {
229 var div = document.createElement("div");
230 div.appendChild(document.createTextNode(str));
231 return div.innerHTML;
238 function isJson(str) {
239 if (typeof str == 'string') {
241 var obj=JSON.parse(str);
242 if(typeof obj == 'object' && obj ){
254 * encode Search Params
256 function encodeSearchParams(obj) {
258 Object.keys(obj).forEach((key) => {
259 let value = obj[key];
260 params.push([key, encodeURIComponent(value)].join('='));
262 return params.length === 0 ? '' : '?' + params.join('&');
269 initDynamic: initDynamic