-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgw2-api-wrapper.js
185 lines (163 loc) · 4.57 KB
/
gw2-api-wrapper.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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
'use strict';
var getJson;
if (typeof fetch === 'undefined') {
getJson = url => new Promise((accept, reject) => window.$.getJSON(url).then(accept, reject)).catch(response => {
throw response.responseJSON || response.responseText || response;
});
} else {
getJson = url => Promise.resolve(fetch(url)).then(response => {
if (response.ok) {
return response.json();
}
return response.json().then(json => {
throw json;
});
});
}
function urlify(object) {
var queryParams = [];
for (var key in object) {
queryParams.push(key + '=' + object[key]);
}
return '?' + queryParams.join('&');
}
function split(array, max) {
const chunkCount = Math.ceil(array.length / max);
const chunkSize = Math.ceil(array.length / chunkCount);
const result = [];
for (var start = 0, end; start < array.length; start = end) {
end = Math.round(start + chunkSize);
result.push(array.slice(start, end));
}
return result;
}
function Api(options) {
if (!options) {
options = {};
}
this.options = {
key: options.key,
keyPrefix: 'gw2-api-' || options.keyPrefix,
rootUrl: 'https://api.guildwars2.com/v2/' || options.rootUrl,
saveDelay: 1000 || options.saveDelay,
cacheTimes: {
default: 60 * 60 * 1000,
global: 7 * 24 * 60 * 60 * 1000
}
};
if (options.cacheTimes) {
for (var key in options.cacheTimes) {
this.options.cacheTimes[key] = options.cacheTimes[key];
}
}
this.pending = {};
this.cache = JSON.parse(localStorage.getItem(this.options.keyPrefix + this.options.key) || '{}');
setInterval(() => {
this.expireOthers();
this.expireAll();
}, 60 * 60 * 1000);
}
Api.prototype = {
save: function () {
if (this.timeoutId) {
this.timeoutId = clearTimeout(this.timeoutId);
}
this.timeoutId = setTimeout(() => {
delete this.timeoutId;
this.cache.deleteAfter = Date.now() + this.options.cacheTimes.global;
localStorage.setItem(this.options.keyPrefix + this.options.key, JSON.stringify(this.cache));
}, this.options.saveDelay);
},
getCacheTime: function (endpoint) {
var endpointPiece;
var pos;
while (pos !== -1) {
endpointPiece = endpoint.slice(0, pos);
if (this.options.cacheTimes[endpointPiece]) {
return this.options.cacheTimes[endpointPiece];
}
pos = endpoint.lastIndexOf('/', pos - 1);
}
return this.options.cacheTimes.default;
},
expire: function (endpoint, querystring) {
var request = endpoint + querystring;
if (this.cache[request]) {
var expireDate = this.cache[request][0] + this.getCacheTime(endpoint);
if (!this.cache[request][1] || expireDate < Date.now()) {
delete this.cache[request];
this.save();
}
}
},
expireAll: function () {
for (var request in this.cache) {
if (request === '') {
continue;
}
this.expire(request);
}
},
expireOthers: function () {
for (var key in localStorage) {
if (this.options.keyPrefix + this.options.key === key || key.indexOf(this.options.keyPrefix) !== 0) {
continue;
}
var data = JSON.parse(localStorage.getItem(key) || '{}');
if (data.deleteAfter < Date.now()) {
localStorage.removeItem(key);
}
}
},
getCached: function (endpoint, querystring) {
this.expire(endpoint, querystring);
return this.cache[endpoint + querystring] && this.cache[endpoint + querystring][1];
},
setCache: function (value, request) {
this.cache[request] = [Date.now(), value];
this.save();
},
getPending: function (request) {
return this.pending[request];
},
setPending: function (request, promise) {
if (promise === undefined) {
delete this.pending[request];
} else {
this.pending[request] = promise;
}
},
getFromApi: function (endpoint, params) {
var querystring = urlify(params);
var cached = this.getCached(endpoint, querystring);
if (cached) {
return Promise.resolve(cached);
}
var request = endpoint + querystring;
var pending = this.getPending(request);
if (pending) {
return pending;
}
var promise = getJson(this.options.rootUrl + request + '&access_token=' + this.options.key);
this.setPending(request, promise);
return promise.then(data => {
this.setCache(data, request);
this.setPending(request);
return data;
});
},
getMultiple: function (endpoint, params) {
var requests = split(params.ids, 100).map(ids => {
var splittedParams = Object.assign({}, params, { ids });
return this.getFromApi(endpoint, splittedParams);
});
return Promise.all(requests)
.then(dataList => Array.prototype.concat.apply([], dataList));
},
get: function (endpoint, params) {
if (params && params.ids) {
return this.getMultiple(endpoint, params);
}
return this.getFromApi(endpoint, params);
}
};