Built motion from commit (unavailable).|2.5.1
[motion2.git] / apidoc / utils / send_sample_request.js
1 define([
2     'jquery',
3     'lodash',
4     './utils/send_sample_request_utils'
5 ], function($, _, utils) {
6
7     var initDynamic = function() {
8         // Button send
9         $(".sample-request-send").off("click");
10         $(".sample-request-send").on("click", function(e) {
11             e.preventDefault();
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"));
17         });
18
19         // Button clear
20         $(".sample-request-clear").off("click");
21         $(".sample-request-clear").on("click", function(e) {
22             e.preventDefault();
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);
28         });
29     }; // initDynamic
30
31     function sendSampleRequest(group, name, version, type)
32     {
33         var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
34
35         // Optional header
36         var header = {};
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;
44                 }
45                 if ( ! element.optional && element.defaultValue !== '') {
46                     value = element.defaultValue;
47                 }
48                 header[key] = value;
49             });
50         });
51
52
53         // create JSON dictionary of parameters
54         var param = {};
55         var paramType = {};
56         var bodyFormData = {};
57         var bodyFormDataType = {};
58         var bodyJson = '';
59         $root.find(".sample-request-param:checked").each(function(i, element) {
60             var group = $(element).data("sample-request-param-group-id");
61             var contentType = $(element).nextAll('.sample-header-content-type-switch').first().val();
62             if (contentType == "body-json"){
63                 $root.find("[data-sample-request-body-group=\"" + group + "\"]").not(function(){
64                     return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
65                 }).each(function(i, element) {
66                     if (isJson(element.value)){
67                         header['Content-Type'] = 'application/json';
68                         bodyJson = element.value;
69                     }
70                 });
71             }else {
72                 $root.find("[data-sample-request-param-group=\"" + group + "\"]").not(function(){
73                     return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
74                 }).each(function(i, element) {
75                     var key = $(element).data("sample-request-param-name");
76                     var value = element.value;
77                     if ( ! element.optional && element.defaultValue !== '') {
78                         value = element.defaultValue;
79                     }
80                     if (contentType == "body-form-data"){
81                         header['Content-Type'] = 'multipart/form-data'
82                         bodyFormData[key] = value;
83                         bodyFormDataType[key] = $(element).next().text();
84                     }else {
85                         param[key] = value;
86                         paramType[key] = $(element).next().text();
87                     }
88                 });
89             }
90         });
91
92         // grab user-inputted URL
93         var url = $root.find(".sample-request-url").val();
94
95         //Convert {param} form to :param
96         url = url.replace(/{/,':').replace(/}/,'');
97
98         // Insert url parameter
99         var pattern = pathToRegexp(url, null);
100         var matches = pattern.exec(url);
101         for (var i = 1; i < matches.length; i++) {
102             var key = matches[i].substr(1);
103             if (param[key] !== undefined) {
104                 url = url.replace(matches[i], encodeURIComponent(param[key]));
105
106                 // remove URL parameters from list
107                 delete param[key];
108             }
109         } // for
110
111         //handle nested objects and parsing fields
112         param = utils.handleNestedAndParsingFields(param, paramType);
113
114         //add url search parameter
115         if (header['Content-Type'] == 'application/json' ){
116             url = url + encodeSearchParams(param);
117             param = bodyJson;
118         }else if (header['Content-Type'] == 'multipart/form-data'){
119             url = url + encodeSearchParams(param);
120             param = bodyFormData;
121         }
122
123         $root.find(".sample-request-response").fadeTo(250, 1);
124         $root.find(".sample-request-response-json").html("Loading...");
125         refreshScrollSpy();
126
127         // send AJAX request, catch success or error callback
128         var ajaxRequest = {
129             url        : url,
130             headers    : header,
131             data       : param,
132             type       : type.toUpperCase(),
133             success    : displaySuccess,
134             error      : displayError
135         };
136
137         $.ajax(ajaxRequest);
138
139
140         function displaySuccess(data, status, jqXHR) {
141             var jsonResponse;
142             try {
143                 jsonResponse = JSON.parse(jqXHR.responseText);
144                 jsonResponse = JSON.stringify(jsonResponse, null, 4);
145             } catch (e) {
146                 jsonResponse = jqXHR.responseText;
147             }
148             $root.find(".sample-request-response-json").text(jsonResponse);
149             refreshScrollSpy();
150         };
151
152         function displayError(jqXHR, textStatus, error) {
153             var message = "Error " + jqXHR.status + ": " + error;
154             var jsonResponse;
155             try {
156                 jsonResponse = JSON.parse(jqXHR.responseText);
157                 jsonResponse = JSON.stringify(jsonResponse, null, 4);
158             } catch (e) {
159                 jsonResponse = jqXHR.responseText;
160             }
161
162             if (jsonResponse)
163                 message += "\n" + jsonResponse;
164
165             // flicker on previous error to make clear that there is a new response
166             if($root.find(".sample-request-response").is(":visible"))
167                 $root.find(".sample-request-response").fadeTo(1, 0.1);
168
169             $root.find(".sample-request-response").fadeTo(250, 1);
170             $root.find(".sample-request-response-json").text(message);
171             refreshScrollSpy();
172         };
173     }
174
175     function clearSampleRequest(group, name, version)
176     {
177         var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
178
179         // hide sample response
180         $root.find(".sample-request-response-json").html("");
181         $root.find(".sample-request-response").hide();
182
183         // reset value of parameters
184         $root.find(".sample-request-param").each(function(i, element) {
185             element.value = "";
186         });
187
188         // restore default URL
189         var $urlElement = $root.find(".sample-request-url");
190         $urlElement.val($urlElement.prop("defaultValue"));
191
192         refreshScrollSpy();
193     }
194
195     function refreshScrollSpy()
196     {
197         $('[data-spy="scroll"]').each(function () {
198             $(this).scrollspy("refresh");
199         });
200     }
201
202     function escapeHtml(str) {
203         var div = document.createElement("div");
204         div.appendChild(document.createTextNode(str));
205         return div.innerHTML;
206     }
207
208
209     /**
210      * is Json
211      */
212     function isJson(str) {
213         if (typeof str == 'string') {
214             try {
215                 var obj=JSON.parse(str);
216                 if(typeof obj == 'object' && obj ){
217                     return true;
218                 }else{
219                     return false;
220                 }
221             } catch(e) {
222                 return false;
223             }
224         }
225     }
226
227     /**
228      * encode Search Params
229      */
230     function encodeSearchParams(obj) {
231         const params = [];
232         Object.keys(obj).forEach((key) => {
233             let value = obj[key];
234             params.push([key, encodeURIComponent(value)].join('='));
235         })
236         return params.length === 0 ? '' : '?' + params.join('&');
237     }
238
239     /**
240      * Exports.
241      */
242     return {
243         initDynamic: initDynamic
244     };
245
246 });