Skip to content

Instantly share code, notes, and snippets.

@DotCoyote
Created February 20, 2019 07:41
Show Gist options
  • Save DotCoyote/7ac2f62962f78a11382642102461d823 to your computer and use it in GitHub Desktop.
Save DotCoyote/7ac2f62962f78a11382642102461d823 to your computer and use it in GitHub Desktop.
Example Axios API Class
import axios, { AxiosPromise, AxiosRequestConfig } from 'axios'
import { URL } from 'consts'
import { ApiResponse } from '__src/types/api'
const cancelTokens = {}
// ====================================
// Interceptors
// ====================================
axios.interceptors.request.use((requestConfig: AxiosRequestConfig) => {
if (!requestConfig.url) {
throw new Error('invalid requestConfig.url')
}
const url: string | undefined = requestConfig.url
if (url && cancelTokens[url]) {
cancelTokens[url].cancelToken.cancel('USER_INTERACTION')
cancelTokens[url] = null
}
const cancelToken = axios.CancelToken.source()
cancelTokens[url] = { cancelToken, time: Date.now() }
return requestConfig
}, (error) => Promise.reject(error))
// ====================================
// AXIOS init
// ====================================
export const HTTP = axios.create()
// ====================================
// API Class
// ====================================
/**
* API Class
* @class
* @classdesc Provides REST-Functions (GET, POST, PATCH, DELETE), implements axios calls
*/
class Api {
public constructor() { }
/**
* @method _post
*
* Sends POST-Requested with given params
*
* @private
* @param {string} route Actual api-endpoint
* @param {object} params Post-Params, optional
*
* @returns {AxiosPromise}
*/
private async _post(route: string, params?: object): Promise<ApiResponse> {
const res = await HTTP.post(route, params)
return (res as ApiResponse)
}
/**
* @method _get
*
* Sends GET-Requested with given Query-params
*
* @private
* @param {string} route Actual api-endpoint
* @param {object} params Post-Params, optional
*
* @returns {AxiosPromise}
*/
private async _get(route: string, params?: object): Promise<ApiResponse> {
const res = await HTTP.get(route, params)
return (res as ApiResponse)
}
// private _patch(route: string, params: object) { }
// private _delete(route: string, params: object) { }
/**
* @function call
*
* Switches through given `route` and calls matching api-method
* or returns rejected promise if no route matches
*
* @public
* @param {string} route - speaking route-name, doesn't have to match actual api-route
* @param {object} params - params to pass to api, optional
*
* @returns {AxiosPromise|null}
*/
public call(route: string, params?: any): AxiosPromise<void> | null {
let response: AxiosPromise<void> | null = null
const errorPromise = () => new Promise((resolve, reject) => {
reject(`Route '${route}' not found!`)
resolve() // only for linter
})
switch (route) {
// ====================================
// Product routes
// ====================================
case 'exampleRoute':
response = this._post(URL, params) as any
break
// ====================================
// DEFAULT: Rejected Promise
// ====================================
default:
response = errorPromise() as any
break
}
return response
}
}
export default new Api()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment