optimize fetch routine

This commit is contained in:
pypy
2020-01-11 19:52:48 +09:00
parent c72a120fae
commit ba2a47480c

View File

@@ -251,7 +251,7 @@ if (window.CefSharp) {
} }
}; };
API.$fetch = {}; API.$pendingGetRequests = new Map();
API.call = function (endpoint, options) { API.call = function (endpoint, options) {
var input = `https://api.vrchat.cloud/api/1/${endpoint}`; var input = `https://api.vrchat.cloud/api/1/${endpoint}`;
@@ -263,28 +263,33 @@ if (window.CefSharp) {
referrerPolicy: 'no-referrer', referrerPolicy: 'no-referrer',
...options ...options
}; };
if (init.method === 'GET') { var isGetRequest = init.method === 'GET';
if (init.body) {
if (isGetRequest) {
// transform body to url
if (isObject(init.body)) {
var url = new URL(input); var url = new URL(input);
for (var key in init.body) { for (var key in init.body) {
url.searchParams.set(key, init.body[key]); url.searchParams.set(key, init.body[key]);
} }
input = url.toString(); input = url.toString();
init.body = null;
} }
delete init.body;
// merge requests // merge requests
if (this.$fetch[input]) { var request = this.$pendingGetRequests.get(input);
return this.$fetch[input]; if (request) {
return request;
} }
} else { } else {
init.headers = { init.headers = {
'Content-Type': 'application/json;charset=utf-8', 'Content-Type': 'application/json;charset=utf-8',
...init.headers ...init.headers
}; };
init.body = init.body init.body = isObject(init.body)
? JSON.stringify(init.body) ? JSON.stringify(init.body)
: '{}'; : '{}';
} }
var req = fetch(input, init).catch((err) => { var req = fetch(input, init).catch((err) => {
this.$throw(0, err); this.$throw(0, err);
}).then((res) => res.json().catch(() => { }).then((res) => res.json().catch(() => {
@@ -316,11 +321,14 @@ if (window.CefSharp) {
} }
return json; return json;
})); }));
if (init.method === 'GET') {
this.$fetch[input] = req.finally(() => { if (isGetRequest) {
delete this.$fetch[input]; req.finally(() => {
this.$pendingGetRequests.delete(input);
}); });
this.$pendingGetRequests.set(input, req);
} }
return req; return req;
}; };