import 'es6-promise/auto'; import axios, { AxiosResponse, AxiosError } from 'axios'; import { CrudReqOpts, CrudParams } from './crud.typings.d'; import { ReqPrefix } from '../constants/env'; export function paramsSerializer(params: { [key: string]: any }) { return Object.keys(params || {}) .map(paramKey => { const paramValue = params[paramKey]; let value = ''; if (BI.isObject(paramValue)) { value = BI.encodeURIComponent(JSON.stringify(paramValue)); } else { value = paramValue; } return BI.isNull(value) ? '' : `${paramKey}=${value}`; }) .filter(v => v !== '') .join('&'); } function getCookieByName(name: string):string { let value = null; const regExpName = new RegExp(name); document.cookie.split(';').forEach((item: string) => { if (item.match(regExpName)) { value = item.split(`${name}=`)[1]; return false; } }); return value; } export async function request(reqOptions: CrudReqOpts = {}) { const { url, type, headers, data, params } = reqOptions; return axios .request({ url, baseURL: ReqPrefix, method: type, headers: { ...headers, Authorization: `Bearer ${getCookieByName('fine_auth_token')}`, }, params, paramsSerializer, data, }) .then((response: AxiosResponse) => { const status = response.status; return status === 200 ? typeof response.data === 'string' ? BI.jsonDecode(response.data) : response.data : {}; }) .catch((error: AxiosError) => { console.log(error); }); } export function requestGet(url: string, data?: any, params: CrudParams = {}) { return request({ url, type: 'GET', data, params, headers: { 'Content-Type': 'application/json', }, }); } export function requestPost(url: string, data = {}, params: CrudParams = {}) { return request({ url, type: 'POST', data, params, headers: { 'Content-Type': 'application/json', }, }); } export function requestDelete(url: string, data = {}) { return request({ url, type: 'DELETE', data, headers: { 'Content-Type': 'application/json', }, }); } export function requestPut(url: string, data = {}, params: CrudParams = {}) { return request({ url, type: 'PUT', data, params, headers: { 'Content-Type': 'application/json', }, }); }