e43e9094ecb60547abbc67c58ddb14a9693c1742
[vchess.git] / client / src / utils / ajax.js
1 import params from "../parameters"; //for server URL
2 import { store } from "../store"; //for translations
3
4 // From JSON (encoded string values!) to "arg1=...&arg2=..."
5 function toQueryString(data) {
6 let data_str = "";
7 Object.keys(data).forEach(k => {
8 data_str += k + "=" + encodeURIComponent(data[k]) + "&";
9 });
10 return data_str.slice(0, -1); //remove last "&"
11 }
12
13 // TODO: use this syntax https://stackoverflow.com/a/29823632 ?
14 // data, success, error: optional
15 export function ajax(url, method, options) {
16 const data = options.data || {};
17 // By default, do nothing on success and print errors:
18 if (!options.success)
19 options.success = () => {};
20 if (!options.error) {
21 options.error = (errmsg) => {
22 alert(store.state.tr[errmsg] || errmsg);
23 };
24 }
25 if (["GET", "DELETE"].includes(method) && !!data)
26 // Append query params to URL
27 url += "/?" + toQueryString(data);
28 const headers = {
29 "Content-Type": "application/json;charset=UTF-8",
30 "X-Requested-With": "XMLHttpRequest"
31 };
32 let fetchOptions = {
33 method: method,
34 headers: headers,
35 };
36 if (["POST", "PUT"].includes(method))
37 fetchOptions["body"] = JSON.stringify(data);
38 if (
39 !!options.credentials ||
40 (method != "GET" && !options.nocredentials)
41 ) {
42 fetchOptions["credentials"] = params.credentials;
43 }
44 fetch(params.serverUrl + url, fetchOptions)
45 .then(res => res.json())
46 .then(json => {
47 if (!json.errmsg && !json.errno) options.success(json);
48 else {
49 if (!!json.errmsg) options.error(json.errmsg);
50 else options.error(json.code + ". errno = " + json.errno);
51 }
52 });
53 }