PromucFlow_constructor/app/client/src/api/Api.tsx

88 lines
2.3 KiB
TypeScript
Raw Normal View History

2019-09-09 09:08:54 +00:00
import _ from "lodash";
// import axios from "axios";
import {
BASE_URL,
REQUEST_TIMEOUT_MS,
2019-09-09 09:08:54 +00:00
REQUEST_HEADERS,
2019-09-24 12:36:03 +00:00
AUTH_CREDENTIALS,
2019-09-09 09:08:54 +00:00
} from "../constants/ApiConstants";
const axios = require("axios"); //eslint-disable-line @typescript-eslint/no-var-requires
const axiosInstance = axios.create({
baseURL: BASE_URL,
timeout: REQUEST_TIMEOUT_MS,
2019-09-09 09:08:54 +00:00
headers: REQUEST_HEADERS,
withCredentials: true,
2019-09-24 12:36:03 +00:00
auth: AUTH_CREDENTIALS,
2019-09-09 09:08:54 +00:00
});
axiosInstance.interceptors.response.use(
function(response: any) {
// Do something with response data
2019-09-09 09:08:54 +00:00
return response.data;
},
function(error: any) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
2019-09-09 09:08:54 +00:00
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
2019-09-09 09:08:54 +00:00
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
2019-09-09 09:08:54 +00:00
console.log("Error", error.message);
}
2019-09-09 09:08:54 +00:00
console.log(error.config);
return Promise.reject(error);
},
);
class Api {
2019-09-12 13:44:25 +00:00
static get(url: string, queryParams?: any) {
2019-09-09 09:08:54 +00:00
return axiosInstance.get(
url + this.convertObjectToQueryParams(queryParams),
);
}
static post(url: string, body?: any, queryParams?: any) {
return axiosInstance.post(
url + this.convertObjectToQueryParams(queryParams),
2019-09-09 09:08:54 +00:00
body,
);
}
static put(url: string, queryParams?: any, body?: any) {
return axiosInstance.put(
url + this.convertObjectToQueryParams(queryParams),
body,
);
}
2019-10-21 15:12:45 +00:00
static delete(url: string, queryParams?: any) {
return axiosInstance.delete(
url + this.convertObjectToQueryParams(queryParams),
);
}
static convertObjectToQueryParams(object: any): string {
if (!_.isNil(object)) {
const paramArray: string[] = _.map(_.keys(object), key => {
2019-09-09 09:08:54 +00:00
return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]);
});
return "?" + _.join(paramArray, "&");
} else {
2019-09-09 09:08:54 +00:00
return "";
}
}
}
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
2019-09-09 09:08:54 +00:00
export default Api;