Skip to content

Instantly share code, notes, and snippets.

@eralston
Last active November 11, 2023 19:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eralston/5c67c59f4e2b34177b3943ef69d71f9a to your computer and use it in GitHub Desktop.
Save eralston/5c67c59f4e2b34177b3943ef69d71f9a to your computer and use it in GitHub Desktop.
Example class wrapping an Axios instance to provide a basic REST-based repository pattern
// https://www.npmjs.com/package/axios Version 0.19.2
import Axios, { AxiosInstance } from 'axios'
export interface IEntity {
example: string
}
export interface ISdk {
getAllAsync: () => Promise<IEntity[]>
getAsync: (id: number) => Promise<IEntity>
postAsync: (values: IEntity) => Promise<IEntity>
putAsync: (id: number, values: IEntity) => Promise<IEntity>
deleteAsync: (id: number) => Promise<void>
}
export default class Sdk implements ISdk {
protected axiosInstance: AxiosInstance
constructor () {
this.axiosInstance = Axios.create({
baseURL: '', // TODO: Define base URL
timeout: undefined // TODO: Consider making this configurable
})
this.addAuthInterceptor(this.axiosInstance)
}
protected addAuthInterceptor (instance: AxiosInstance): void {
instance.interceptors.request.use(async (config) => {
const accessToken = await this.getAccessTokenAsync()
config.headers.Authorization = accessToken
return config
}, async (error) => {
return await Promise.reject(error)
})
}
protected async getAccessTokenAsync (): Promise<string> {
return '123' // TODO: Real implementation
}
// Example CRUD calls
public async getAllAsync (): Promise<IEntity[]> {
const response = await this.axiosInstance.get('Entity')
return response.data
}
public async getAsync (id: number): Promise<IEntity> {
const response = await this.axiosInstance.get(`Entity/${id}`)
return response.data
}
public async postAsync (values: IEntity): Promise<IEntity> {
const response = await this.axiosInstance.post('Entity', values)
return response.data
}
public async putAsync (id: number, values: IEntity): Promise<IEntity> {
const response = await this.axiosInstance.put(`Entity/${id}`, values)
return response.data
}
public async deleteAsync (id: number): Promise<void> {
const response = await this.axiosInstance.delete(`Entity/${id}`)
return response.data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment