@amxchange/grid-view-web-client
Version:
amxchange grid view framework web client in react ( a module extracted from existing jax )
98 lines (87 loc) • 3.28 kB
JavaScript
import axios from "axios";
import { commonUtils } from "../utils";
export default class ApiService {
constructor({ prefix = "", responseBuilder = res => res } = {}) {
this.prefix = prefix;
this.responseBuilder = responseBuilder;
}
get = (url, data, options) => this.request({ url, method: "get", data, options });
post = (url, data, options) => this.request({ url, method: "post", data, options });
put = (url, data, options) => this.request({ url, method: "put", data, options });
delete = (url, data, options) => this.request({ url, method: "delete", data, options });
postFormData = (url, data, options) => {
data = commonUtils.serializeParams(data);
return this.post(url, data, {
...options,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
...options.headers
}
});
};
request = async ({ url, method, data, options = {} }) => {
url = this.getUrl({ url, options });
let axiosArgs = this.getAxiosArgs({ url, method, data, options });
// console.log("ApiService request: " + JSON.stringify(axiosArgs));
try {
let response = await axios.request(axiosArgs);
// console.log(`ApiService request: ${url} (${method}) status success: ${response.status}`);
return this.responseBuilder(response);
} catch (thrown) {
if (axios.isCancel(thrown)) {
console.log("Request canceled", thrown.message);
} else {
console.log(`ApiService request: ${url} (${method}) catch: ${thrown.message}`);
}
throw thrown;
}
};
getUrl = ({ url, options = {} }) => {
let result = "";
let urlType =
options && options.urlType && typeof options.urlType === "string" ? options.urlType.toLowerCase() : "";
switch (urlType) {
case "absolute":
result = url;
break;
case "relative":
result = this.prefix + url;
break;
default:
result = this.prefix + url;
}
return result;
};
getAxiosArgs = ({ url, method, data, options = {} }) => {
let _options = {
...options,
headers: {
Accept: "application/json",
...options.headers
}
};
let axiosArgs = {
url,
method,
...(_options.responseType ? { responseType: _options.responseType } : {}),
headers: _options.headers,
cancelToken: _options.cancelToken
};
switch (method) {
case "get":
axiosArgs = { ...axiosArgs, params: data };
break;
case "post":
case "put":
case "delete":
axiosArgs = { ...axiosArgs, data, params: _options.params };
break;
default:
break;
}
return axiosArgs;
};
}
export const Api = {
root: new ApiService()
};