Built motion from commit (unavailable).|2.5.2
[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 = new FormData();
57         var bodyJson = '';
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;
68                     }
69                 });
70             }else {
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;
78                     }
79                     if (contentType == "body-form-data"){
80                         header['Content-Type'] = 'multipart/form-data'
81                         if (element.type == "file") {
82                         value = element.files[0];
83                       }
84                       bodyFormData.append(key,value);
85                     }else {
86                         param[key] = value;
87                         paramType[key] = $(element).next().text();
88                     }
89                 });
90             }
91         });
92
93         // grab user-inputted URL
94         var url = $root.find(".sample-request-url").val();
95
96         //Convert {param} form to :param
97         url = utils.convertPathParams(url);
98
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);
104             var optional = false
105             if (key[key.length - 1] === '?') {
106                 optional = true;
107                 key = key.substr(0, key.length - 1);
108             }
109             if (param[key] !== undefined) {
110                 url = url.replace(matches[i], encodeURIComponent(param[key]));
111
112                 // remove URL parameters from list
113                 delete param[key];
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], '');
118                 delete param[key];
119             }
120         } // for
121
122         //handle nested objects and parsing fields
123         param = utils.handleNestedAndParsingFields(param, paramType);
124
125         //add url search parameter
126         if (header['Content-Type'] == 'application/json') {
127             if (bodyJson) {
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);
131                 param = bodyJson;
132             } else {
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);
138             }
139         }else if (header['Content-Type'] == 'multipart/form-data'){
140             url = url + encodeSearchParams(param);
141             param = bodyFormData;
142         }
143
144         $root.find(".sample-request-response").fadeTo(250, 1);
145         $root.find(".sample-request-response-json").html("Loading...");
146         refreshScrollSpy();
147
148         // send AJAX request, catch success or error callback
149         var ajaxRequest = {
150             url        : url,
151             headers    : header,
152             data       : param,
153             type       : type.toUpperCase(),
154             success    : displaySuccess,
155             error      : displayError
156         };
157
158         if(header['Content-Type'] == 'multipart/form-data'){
159             delete ajaxRequest.headers['Content-Type'];
160             ajaxRequest.contentType=false;
161             ajaxRequest.processData=false;
162         }
163         $.ajax(ajaxRequest);
164
165
166         function displaySuccess(data, status, jqXHR) {
167             var jsonResponse;
168             try {
169                 jsonResponse = JSON.parse(jqXHR.responseText);
170                 jsonResponse = JSON.stringify(jsonResponse, null, 4);
171             } catch (e) {
172                 jsonResponse = jqXHR.responseText;
173             }
174             $root.find(".sample-request-response-json").text(jsonResponse);
175             refreshScrollSpy();
176         };
177
178         function displayError(jqXHR, textStatus, error) {
179             var message = "Error " + jqXHR.status + ": " + error;
180             var jsonResponse;
181             try {
182                 jsonResponse = JSON.parse(jqXHR.responseText);
183                 jsonResponse = JSON.stringify(jsonResponse, null, 4);
184             } catch (e) {
185                 jsonResponse = jqXHR.responseText;
186             }
187
188             if (jsonResponse)
189                 message += "\n" + jsonResponse;
190
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);
194
195             $root.find(".sample-request-response").fadeTo(250, 1);
196             $root.find(".sample-request-response-json").text(message);
197             refreshScrollSpy();
198         };
199     }
200
201     function clearSampleRequest(group, name, version)
202     {
203         var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
204
205         // hide sample response
206         $root.find(".sample-request-response-json").html("");
207         $root.find(".sample-request-response").hide();
208
209         // reset value of parameters
210         $root.find(".sample-request-param").each(function(i, element) {
211             element.value = "";
212         });
213
214         // restore default URL
215         var $urlElement = $root.find(".sample-request-url");
216         $urlElement.val($urlElement.prop("defaultValue"));
217
218         refreshScrollSpy();
219     }
220
221     function refreshScrollSpy()
222     {
223         $('[data-spy="scroll"]').each(function () {
224             $(this).scrollspy("refresh");
225         });
226     }
227
228     function escapeHtml(str) {
229         var div = document.createElement("div");
230         div.appendChild(document.createTextNode(str));
231         return div.innerHTML;
232     }
233
234
235     /**
236      * is Json
237      */
238     function isJson(str) {
239         if (typeof str == 'string') {
240             try {
241                 var obj=JSON.parse(str);
242                 if(typeof obj == 'object' && obj ){
243                     return true;
244                 }else{
245                     return false;
246                 }
247             } catch(e) {
248                 return false;
249             }
250         }
251     }
252
253     /**
254      * encode Search Params
255      */
256     function encodeSearchParams(obj) {
257         const params = [];
258         Object.keys(obj).forEach((key) => {
259             let value = obj[key];
260             params.push([key, encodeURIComponent(value)].join('='));
261         })
262         return params.length === 0 ? '' : '?' + params.join('&');
263     }
264
265     /**
266      * Exports.
267      */
268     return {
269         initDynamic: initDynamic
270     };
271
272 });