Attempt to clarify installation instructions a little
[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 options = options || {};
17 const data = options.data || {};
18 // By default, do nothing on success and print errors:
19 if (!options.success)
20 options.success = () => {};
21 if (!options.error) {
22 options.error = (errmsg) => {
23 alert(store.state.tr[errmsg] || errmsg);
24 };
25 }
26 if (["GET", "DELETE"].includes(method) && !!data)
27 // Append query params to URL
28 url += "/?" + toQueryString(data);
29 const headers = {
30 "Content-Type": "application/json;charset=UTF-8",
31 "X-Requested-With": "XMLHttpRequest"
32 };
33 let fetchOptions = {
34 method: method,
35 headers: headers,
36 };
37 if (["POST", "PUT"].includes(method))
38 fetchOptions["body"] = JSON.stringify(data);
39 if (
40 !!options.credentials ||
41 (method != "GET" && !options.nocredentials)
42 ) {
43 fetchOptions["credentials"] = params.credentials;
44 }
45 fetch(params.serverUrl + url, fetchOptions)
46 .then(res => res.json())
47 .then(json => {
48 if (!json.errmsg && !json.errno) options.success(json);
49 else {
50 if (!!json.errmsg) options.error(json.errmsg);
51 else options.error(json.code + ". errno = " + json.errno);
52 }
53 });
54 }