Skip to content

Instantly share code, notes, and snippets.

@trentmurray
Created May 1, 2020 06:22
Show Gist options
  • Save trentmurray/632ce62aff2b2e732dfeb78a0e912776 to your computer and use it in GitHub Desktop.
Save trentmurray/632ce62aff2b2e732dfeb78a0e912776 to your computer and use it in GitHub Desktop.
API calls in typescript
import {AxiosError} from "axios";
export interface Request<DataType = {}> {
endpoint: string;
params?: object;
data?: DataType;
headers?: object;
withCredentials?: boolean;
ownAPI?: boolean;
}
export interface Config {
params?: object;
headers?: object;
withCredentials?: boolean;
}
export interface ApiResponse<T> {
status: number | null;
statusText: string | null;
resultData: T | null;
errorData: AxiosError | null;
}
const processResponse = <T>(resp: AxiosResponse) => {
const resultData = resp.data
const status = resp.status
const statusText = resp.statusText
const response: ApiResponse<T> = {
status: status,
statusText: statusText,
resultData: resultData as T,
errorData: null
}
return response;
}
const processError = (error: AxiosError) => {
const status = error.response ? error.response.status : null;
const statusText = error.response ? error.response.statusText : null;
// @ts-ignore
const response: ApiResponse<any> = {
status: status,
statusText: statusText,
resultData: null,
errorData: error as AxiosError
}
return response;
}
export const $get = async <T>(request: Request) => {
const config: Config = {
params: request.params,
headers: request.headers,
withCredentials: request.withCredentials || false
}
const http = setDefaults(axios)
return http
.get(request.endpoint, config)
.then( (resp: AxiosResponse) => {
return processResponse<T>(resp)
} )
.catch( (error: AxiosError) => {
return processError(error)
})
}
export interface Login {
email: string;
password: string;
}
// Where we call it
const request: Request<Login> = {
endpoint: "/api/users/login/",
data: {
email: this.email,
password: this.password
} as Login
};
const response: ApiResponse<Login> = await $post<Login>(request);
if (response.errorData) {
console.log(response.errorData);
} else {
// do something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment