Created
September 29, 2021 21:36
-
-
Save miketromba/a53f2e822e39c79680951d284d21a266 to your computer and use it in GitHub Desktop.
ApiClient.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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