Skip to content

Instantly share code, notes, and snippets.

@zurez
Created May 19, 2020 21:08
Show Gist options
  • Save zurez/3edd133aa3461f53469cee16e8b0bd0a to your computer and use it in GitHub Desktop.
Save zurez/3edd133aa3461f53469cee16e8b0bd0a to your computer and use it in GitHub Desktop.
Code I wrote for talking with server
import axios from 'axios';
import { AwsAuth } from './aws';
const baseUrl = process.env.API_URL;
interface AjaxRequest {
url: string;
queryParams?: object;
body?: object;
headers?: object;
auth?: boolean;
authState?: string;
tokenType?: string;
fullUrl?: string;
}
interface AjaxResponse {
status: string;
data?: any;
error?: string;
}
async function ajax(params: AjaxRequest, method): Promise<AjaxResponse> {
const {
queryParams,
url,
body,
auth,
authState,
tokenType,
fullUrl,
} = params;
let token = null;
try {
const currentSession: any = await AwsAuth.currentSession();
if (tokenType && tokenType === 'accessToken') {
token = currentSession.accessToken.jwtToken;
} else {
token = currentSession.idToken.jwtToken;
}
} catch (error) {
// Do refreshing
console.log(error);
// throw new Error('AUTHFAIL');
}
const headers = {
'content-type': 'application/json',
};
if (!token && auth && authState === 'compulsory') {
// throw new Error('Only authenticated users allowed.');
return { status: 'failed' };
}
if (token && auth) {
headers['Authorization'] = `Bearer ${token}`;
}
const config = {
method,
url: fullUrl ? fullUrl : baseUrl + url,
params: queryParams,
headers,
};
if ((method === 'post' || method === 'put') && body) {
config['data'] = body;
}
try {
const { data, status } = await axios(config);
return { status: data.status, data: data.data };
} catch (error) {
const errorRes = error.response.data;
throw new Error(
errorRes.errorMessage ||
'An error happened with ajax service for ' + fullUrl,
);
}
}
export async function post(params: AjaxRequest): Promise<AjaxResponse> {
return ajax(params, 'post');
}
export async function put(params: AjaxRequest): Promise<AjaxResponse> {
return ajax(params, 'put');
}
export async function get(params: AjaxRequest): Promise<AjaxResponse> {
return ajax(params, 'get');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment