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