-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchJSON.js
More file actions
149 lines (130 loc) · 5.2 KB
/
fetchJSON.js
File metadata and controls
149 lines (130 loc) · 5.2 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**@function fetchJSON
*use the Fetch API to retrieve data from a JSON file
*@param {string} path - the complete path to the file
*@param {object|undefined} data - an object of data to be converted into a query string
*@param {object|undefined} options - the options for fetch
*
*@return the Promise object of the fetch request
*/
(function UniversalModuleDefinition(root, factory){
if(typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("fetchJSON", [], factory);
else if(typeof exports === 'object')
exports["fetchJSON"] = factory();
else
root["fetchJSON"] = factory();
})(window || this, function(){
// cf. https://stackoverflow.com/a/34749873/7316365
/**
* Simple object check.
* @param item
* @returns {boolean}
*/
function isObject(item) {
return (item && typeof item === 'object' && !(item instanceof Array));
}
/**
* Deep merge two objects.
* @param target
* @param ...sources
*/
function mergeDeep(target/*, ...sources*/) {
// if (!sources.length) return target;
if (arguments.length <=1)
return target;
var sources = [].slice.apply(arguments);
sources.shift(); //remove "target"
var source = sources.shift();
if (isObject(target) && isObject(source)) {
for (var key in source) {
if (isObject(source[key])) {
if (!target[key]){
var obj = {};
obj[key] = {};
Object.assign(target, obj);
}
mergeDeep(target[key], source[key]);
} else {
var obj = {};
obj[key] = source[key];
Object.assign(target, obj);
}
}
}
// return mergeDeep(target, ...sources);
return mergeDeep.apply(null, [target].concat(sources));
}
//cf. https://stackoverflow.com/a/34749873/7316365
var fetchJSON = function(path, data, options){
// data = Object.assign({}, fetchJSON.defaults.qs, data || {});
data = mergeDeep({}, fetchJSON.defaults.qs, data || {});
options = options || {};
if(typeof data != "object" || data === null)
throw new TypeError("'data' must be an Object");
var check = function(elem){
var innerCheck = function(elem){
if(!(typeof elem == "string" || typeof elem == "number"))
throw new TypeError("Invalid data object (elements are not all arrays of strings/numbers or strings or numbers)");
}
if(elem instanceof Array){
elem.forEach(innerCheck);
return;
}
innerCheck(elem);
};
Object.values(data).forEach(check);
var primitiveToQstring = function(e){
return encodeURIComponent(e.key) + "=" + encodeURIComponent(e.value);
}
var qstring = Object.entries(data)
.map(function(e){ return {key: e[0], value: e[1]}; })
.map(function(e){
if(e.value instanceof Array){
return e.value.map(function(val){
return {key: e.key, value: val};
}).map(primitiveToQstring).join("&");
}
return primitiveToQstring(e);
}).join("&");
if(qstring !== ""){
if(!/\?/.test(path))//has a '?'
qstring = "?"+qstring;
else if(!/\?$/.test(path))//doesn't end by '?'
qstring = /&$/.test(path) ? qstring : "&"+qstring;
}
return new Promise(function(resolve, reject){
if(typeof path == "string"){
// var fetchOptions = Object.assign({}, fetchJSON.defaults.options, options, {method: "GET"});
// fetchOptions.headers = Object.assign({}, fetchJSON.defaults.headers, fetchOptions.headers || {});
var fetchOptions = mergeDeep({}, fetchJSON.defaults.options, options, {method: "GET"});
fetchOptions.headers = mergeDeep({}, fetchJSON.defaults.headers, fetchOptions.headers || {});
var f = fetch(path + qstring, fetchOptions);
f.then(function(response){
return response.json()
.then(resolve)
.catch(function(){
var error = "Something went wrong during data inspection (data is not JSON or couldn't reach file)";
reject(error);
return Promise.reject(error);
});
});
return f;
}
else{
if(typeof path != "string")
reject("The 1st argument must be a string");
return null;
}
});
};
fetchJSON.defaults = {
qs: {},
options: {},
headers: {
"Content-Type": "application/json"
}
};
return fetchJSON;
});