UNPKG

2.38 kBJavaScriptView Raw
1(function() {
2 var AjaxRequest, AjaxUtils, superagent;
3
4 superagent = require("superagent");
5
6 AjaxUtils = require("./ajax_utils");
7
8 AjaxRequest = (function() {
9 function AjaxRequest() {}
10
11 AjaxRequest.promise = {
12 end: function() {}
13 };
14
15 AjaxRequest.enabled = true;
16
17 AjaxRequest.disable = function(callback) {
18 var e;
19 if (this.enabled) {
20 this.enabled = false;
21 try {
22 return callback();
23 } catch (_error) {
24 e = _error;
25 throw e;
26 } finally {
27 this.enabled = true;
28 }
29 } else {
30 return callback();
31 }
32 };
33
34 AjaxRequest.queueRequest = {
35 get: function(params, options) {
36 return AjaxRequest.executeRequest("get", params, options);
37 },
38 post: function(params, options) {
39 return AjaxRequest.executeRequest("post", params, options);
40 },
41 put: function(params, options) {
42 return AjaxRequest.executeRequest("put", params, options);
43 },
44 del: function(params, options) {
45 return AjaxRequest.executeRequest("del", params, options);
46 }
47 };
48
49 AjaxRequest.executeRequest = function(type, params, options) {
50 var header, request, _i, _len, _ref;
51 if (this.enabled === false) {
52 return this.promise;
53 }
54 request = superagent[type](options.url).set('X-Requested-With', 'XMLHttpRequest');
55 _ref = _3Model.Model.headers;
56 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
57 header = _ref[_i];
58 if (!header.name || !header.value) {
59 throw "header should be an object with name and value";
60 }
61 request = request.set(header.name, header.value);
62 }
63 if (typeof request.withCredentials === "function") {
64 request.withCredentials();
65 }
66 if (type === "put" || type === "post") {
67 request = request.type('json');
68 }
69 if (options.error) {
70 request.on("error", options.error);
71 }
72 if (params.query) {
73 request = request.query(params.query);
74 }
75 if (params.data) {
76 if (typeof params.data !== 'string') {
77 params.data = JSON.stringify(params.data);
78 }
79 request = request.send(params.data);
80 }
81 return request;
82 };
83
84 return AjaxRequest;
85
86 })();
87
88 module.exports = AjaxRequest;
89
90}).call(this);