Skip to content

Instantly share code, notes, and snippets.

@miketromba
Created September 29, 2021 21:36
Show Gist options
  • Save miketromba/a53f2e822e39c79680951d284d21a266 to your computer and use it in GitHub Desktop.
Save miketromba/a53f2e822e39c79680951d284d21a266 to your computer and use it in GitHub Desktop.
ApiClient.js
import axios from 'axios'
// Extend me!
export default class ApiClient {
constructor(endpoint, token){
this.endpoint = endpoint
this.token = token
}
async post(path, data){
return axios.post(`${this.endpoint}${path}`, data, {
headers: {
Authorization: `Bearer ${this.token}`
}
})
}
async get(path, query){
return axios.get(`${this.endpoint}${path}${buildQueryString(query)}`, {
headers: {
Authorization: `Bearer ${this.token}`
}
})
}
}
// It's forgiving. Includes the '?' char if needed
function buildQueryString(params = {}){
const qs = Object.keys(params)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
.join('&')
if(qs) return `?${qs}`
return ''
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment