-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamd-base-api-es6.js
82 lines (62 loc) · 2.48 KB
/
amd-base-api-es6.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* BASE API FOR AMD(Asyncronous Module Definition) loaders like RequireJS
*
* Created by rahulp on 13-07-2015.
*/
'use strict';
((factory) => {
if(!requirejs && !requirejs.config) throw new Error("RequireJS is not loaded correctly...");; // Exit from here
/* RequireJS Configuartion settings */
requirejs.config({
paths: {
jquery: 'https://code.jquery.com/jquery-2.1.4.min.js'
}
});
if (typeof define === 'function' && define.amd) {
factory();
} else {
throw new Error("RequireJS is not loaded correctly...");
}
})(()=>{
define(['jquery'], ($) => {
let api = {},
_httpAjax = (httpMethod, webApiMethod, id, query, postData, enableCache) => {
let deferred = $.Deferred(),
url,
requestPayload;
if (!!query && !query.startsWith('?')) {
query = '?' + query;
}
url = webApiUrl + "api/" + webApiMethod + (!!id ? "/" + id : "") + (query || "");
$.ajaxSetup({ cache: !!enableCache });
var requestData = {
cache: !!enableCache,
url: url,
type: httpMethod,
data: !!postData ? JSON.stringify(postData) : null,
contentType: "application/json"
};
$.ajax(requestData).done(function (data) {
api.methods[webApiMethod] = api.methods[webApiMethod] || {};
api.methods[webApiMethod][(id || "") + (!!query ? "?" + query : "")] = data;
deferred.resolve(data);
}).fail(function (err) {
deferred.reject(err);
});
return deferred.promise();
};
api.get = (method, id, query, enableCache = false) => {
return _httpAjax('GET', method, id, query, null, enableCache);
};
api.post = (method, id, query, postData, enableCache = false) => {
return _httpAjax('POST', method, id, query, postData, enableCache);
};
api.put = (method, id, query, postData, enableCache = false) => {
return _httpAjax('PUT', method, id, query, postData, enableCache);
};
api.delete = (method, id, query, enableCache = false)=> {
return _httpAjax('DELETE', method, id, query, null, enableCache);
};
return api;
});
});