Completed
Push — master ( 6db2b4...7d91ca )
by Dimas
41:23 queued 27:58
created

libs/js/ajaxJQuery.ts   B

Complexity

Total Complexity 49
Complexity/F 9.8

Size

Lines of Code 320
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 217
dl 0
loc 320
rs 8.48
c 0
b 0
f 0
wmc 49
mnd 44
bc 44
fnc 5
bpm 8.8
cpm 9.8
noi 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A ajaxJQuery.ts ➔ AjaxForm 0 34 2
A ajaxJQuery.ts ➔ call_user_func 0 9 2
A ajaxJQuery.ts ➔ ajx 0 30 3
A ajaxJQuery.ts ➔ async_process 0 23 1
F ajaxJQuery.ts ➔ processAjaxForm 0 34 41

How to fix   Complexity   

Complexity

Complex classes like libs/js/ajaxJQuery.ts often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
if (!isnode()) {
2
  /**
3
   * AJAX runner base
4
   */
5
  var AJAX = null;
6
  /**
7
   * Ajax dump base
8
   */
9
  var dumpAjax = false;
10
  /**
11
   * Ajax indicator base
12
   */
13
  var indicatorAjax = false;
14
  const ajaxIDLoader =
15
    "ajxLoader_" +
16
    Math.random().toString(36).substring(2) +
17
    Date.now().toString(36);
18
  if (!$("#" + ajaxIDLoader).length) {
19
    $("body").append(
20
      '<div id="' +
21
        ajaxIDLoader +
22
        '" style="position: fixed;z-index:9999;bottom:5px;left:5px;"><svg enable-background="new 0 0 40 40"height=40px id=loader-1 version=1.1 viewBox="0 0 40 40"width=40px x=0px xml:space=preserve xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink y=0px><path d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946\
23
  s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634\
24
  c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"fill=#000 opacity=0.2 /><path d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0\
25
  C22.32,8.481,24.301,9.057,26.013,10.047z"fill=#000><animateTransform attributeName=transform attributeType=xml dur=0.5s from="0 20 20"repeatCount=indefinite to="360 20 20"type=rotate /></path></svg></div>'
26
    );
27
    $("#" + ajaxIDLoader).fadeOut("fast");
28
  }
29
30
  jQuery.ajaxPrefilter(function (options: JQueryAjaxSettings) {
31
    indicatorAjax =
32
      typeof options.indicator == "boolean" && options.indicator === true;
33
    dumpAjax = typeof options.dump == "boolean" && options.dump === true;
34
    /**
35
     * Proxying begin
36
     */
37
    if (options.crossDomain && jQuery.support.cors) {
38
      var allowed = true;
39
      if (options.url.match(/\.html$/g)) {
40
        allowed = false;
41
      }
42
      if (options.url.match(/^\//)) {
43
        allowed = false;
44
      }
45
      if (options.hasOwnProperty("proxy") && !options.proxy) {
46
        allowed = false;
47
      }
48
49
      if (allowed) {
50
        var http = window.location.protocol === "http:" ? "http:" : "https:";
51
        if (typeof options.proxy == "string") {
52
          options.url =
53
            options.proxy.replace(/\/{1,99}$/s, "") + "/" + options.url;
54
        } else {
55
          options.url = http + "//cors-anywhere.herokuapp.com/" + options.url;
56
        }
57
      }
58
    }
59
  });
60
61
  /*
62
$(document).ajaxStart(function () {
63
});
64
*/
65
66
  $(document).ajaxError(function (event, jqXHR, settings, errorThrown) {
67
    var content_type = jqXHR.getResponseHeader("Content-Type");
68
    if (typeof toastr != "undefined") {
69
      if (/json|text\/plain/s.test(content_type)) {
70
        toastr.error(
71
          "Request failed. (" +
72
            jqXHR.status +
73
            " " +
74
            jqXHR.statusText +
75
            ") " +
76
            errorThrown,
77
          "Request Info"
78
        );
79
      }
80
    }
81
  });
82
83
  $(document).ajaxSend(function (event, xhr, settings) {
84
    if (settings.hasOwnProperty("indicator") && settings.indicator) {
85
      $("#" + ajaxIDLoader).fadeIn("fast");
86
    }
87
    if (dumpAjax) {
88
      toastr.info("Requesting...", "Request Info");
89
    }
90
    if (!settings.hasOwnProperty("method")) {
91
      settings.method = "POST";
92
    }
93
  });
94
95
  $(document).ajaxComplete(function (event: any, xhr, settings) {
96
    if (settings.hasOwnProperty("indicator") && settings.indicator) {
97
      $("#" + ajaxIDLoader).fadeOut("fast");
98
    }
99
    if (dumpAjax) {
100
      toastr.success("Request complete", "Request Info");
101
    }
102
    AJAX = null;
103
    $("#" + ajaxIDLoader).fadeOut("slow");
104
105
    var content_type = xhr.getResponseHeader("Content-Type"),
106
      res;
107
    if (xhr.hasOwnProperty("responseJSON")) {
108
      res = xhr.responseJSON;
109
    } else {
110
      res = xhr.responseText;
111
      if (
112
        typeof res == "string" &&
113
        !empty(res) &&
114
        /json|text\/plain/s.test(content_type)
115
      ) {
116
        //begin decode json
117
        if (isJSON(res)) {
118
          res = JSON.parse(res);
119
        }
120
      }
121
    }
122
123
    if (typeof res == "object") {
124
      if (res.hasOwnProperty("redirect")) {
125
        this.location.replace(res.redirect);
126
        throw "Disabled";
127
      }
128
      if (res.hasOwnProperty("reload")) {
129
        location.href = location.href;
130
        throw "Disabled";
131
      }
132
    }
133
  });
134
135
  $(document).ajaxSuccess(function (event, request, settings) {
136
    var res;
137
    var content_type = request.getResponseHeader("Content-Type");
138
    if (request.hasOwnProperty("responseJSON")) {
139
      res = request.responseJSON;
140
    } else {
141
      res = request.responseText;
142
    }
143
    if (
144
      typeof res == "string" &&
145
      !empty(res) &&
146
      /json|text\/plain/s.test(content_type)
147
    ) {
148
      //begin decode json
149
      if (isJSON(res)) {
150
        res = JSON.parse(res);
151
      }
152
    }
153
    if (
154
      typeof res == "object" &&
155
      !settings.hasOwnProperty("silent") &&
156
      typeof toastr != "undefined" &&
157
      /json|javascript/s.test(content_type)
158
    ) {
159
      var error = res.hasOwnProperty("error") && res.error ? true : false;
160
      var title = res.hasOwnProperty("title") ? res.title : "Unknown Title";
161
      var msg = res.hasOwnProperty("message") ? res.message : "Unknown Error";
162
      if (res.hasOwnProperty("error") && res.hasOwnProperty("message")) {
163
        if (error) {
164
          toastr.error(msg, title);
165
        } else {
166
          toastr.success(msg, title);
167
        }
168
      } else if (res.hasOwnProperty("message")) {
169
        toastr.info(msg, title);
170
      }
171
      if (res.hasOwnProperty("unauthorized")) {
172
        location.replace("/signin");
173
      }
174
    }
175
  });
176
177
  /*
178
jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
179
  if (typeof options.data != 'undefined' && !jQuery.isEmptyObject(options.data)) {
180
    jqXHR.setRequestHeader('timeStamp', new Date().getTime().toString());
181
  }
182
});
183
*/
184
185
  function processAjaxForm(xhr: JQueryXHR, callback: string | Function) {
186
    //var content_type = typeof xhr.getResponseHeader == 'function' ? xhr.getResponseHeader('Content-Type') : null, res;
187
    console.log(getFuncName(), callback);
188
    var res: string | number | boolean;
189
    if (xhr.hasOwnProperty("responseJSON")) {
190
      res = xhr.responseJSON;
191
    } else if (xhr.hasOwnProperty("responseText")) {
192
      res = xhr.responseText;
193
      if (typeof res == "string" && !empty(res)) {
194
        //begin decode json
195
        if (isJSON(res)) {
196
          res = JSON.parse(res);
197
        }
198
      }
199
    }
200
201
    if (callback) {
202
      if (typeof callback == "function") {
203
        callback(res);
204
      } else if (typeof callback == "string") {
205
        call_user_func(callback, window, res);
206
      } else {
207
        console.error(
208
          "2nd parameters must be callback function, instead of " +
209
            typeof callback
210
        );
211
      }
212
    }
213
  }
214
215
  function call_user_func(functionName, context, args) {
216
    var args = Array.prototype.slice.call(arguments, 2);
217
    var namespaces = functionName.split(".");
218
    var func = namespaces.pop();
219
    for (var i = 0; i < namespaces.length; i++) {
220
      context = context[namespaces[i]];
221
    }
222
    return context[func].apply(context, args);
223
  }
224
225
  /**
226
   * Custom ajax
227
   * @param settings ajax settings object
228
   */
229
  function ajx(
230
    settings: JQueryAjaxSettings,
231
    success: null | Function,
232
    failed: null | Function,
233
    complete: null | Function
234
  ) {
235
    settings.headers = {
236
      "unique-id": getUID(),
237
    };
238
    if (!settings.hasOwnProperty("indicator")) {
239
      settings.indicator = true;
240
    }
241
    if (!settings.hasOwnProperty("method")) {
242
      settings.method = "POST";
243
    }
244
245
    return $.ajax(settings)
246
      .done(function (data, textStatus, jqXHR) {
247
        processAjaxForm(jqXHR, success);
248
      })
249
      .fail(function (jqXHR, textStatus, errorThrown) {
250
        processAjaxForm(jqXHR, failed);
251
      })
252
      .always(function (jqXHR, textStatus, errorThrown) {
253
        processAjaxForm(jqXHR, complete);
254
      });
255
  }
256
257
  /**
258
   * Handling form with ajax
259
   * @requires data-success success function name
260
   * @requires data-error error function name
261
   * @requires data-complete complete function name
262
   */
263
  function AjaxForm() {
264
    $(document).on("submit", "form", function (e) {
265
      e.preventDefault();
266
      var t = $(this);
267
      var sukses = t.data("success");
268
      var err = t.data("error");
269
      var complete = t.data("complete");
270
      var targetURL = t.attr("action");
271
      //console.log(targetURL, sukses, err, complete);
272
      if (!targetURL) {
273
        console.error("Target url of this form not exists");
274
        return;
275
      }
276
277
      ajx(
278
        {
279
          url: targetURL,
280
          method: t.attr("method") || "POST",
281
          data: t.serialize(),
282
          headers: {
283
            Accept: "application/json",
284
            guid: guid(),
285
          },
286
        },
287
        sukses,
288
        err,
289
        complete
290
      );
291
    });
292
  }
293
294
  /**
295
   * process page asynchronously
296
   * @param source_cache url
297
   */
298
  function async_process(source_cache: string) {
299
    var xhr = new XMLHttpRequest();
300
    $.ajax({
301
      url: source_cache,
302
      method: "POST",
303
      silent: true,
304
      indicator: false,
305
      xhr: function () {
306
        return xhr;
307
      },
308
      headers: {
309
        Pragma: "no-cache",
310
        "Cache-Control": "no-cache",
311
        "Refresh-Cache": "true",
312
      },
313
      success: function (response) {
314
        $("html").html($("html", response).html());
315
        console.log(xhr.responseURL);
316
      },
317
    });
318
  }
319
}
320