Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active April 12, 2023 00:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save coryhouse/09fb49dd0c13ca20cca6cc0fe2438f3e to your computer and use it in GitHub Desktop.
Save coryhouse/09fb49dd0c13ca20cca6cc0fe2438f3e to your computer and use it in GitHub Desktop.
API Wrapper example
/* This API wrapper is useful because it:
1. Centralizes our Axios default configuration.
2. Abstracts away the logic for determining the baseURL.
3. Provides a clear, easily consumable list of JavaScript functions
for interacting with the API. This keeps API calls short and consistent.
*/
import axios from 'axios';
let api = null;
function getInitializedApi() {
if (api) return api; // return initialized api if already initialized.
return (api = axios.create({
baseURL: getBaseUrl(),
responseType: 'json',
withCredentials: true
}));
}
// Helper functions
function getBaseUrl() {
// Insert logic here to get the baseURL by either:
// 1. Sniffing the URL to determine the environment we're running in.
// 2. Looking for an environment variable as part of the build process.
}
function get(url) {
return getInitializedApi().get(url);
}
function post(url, data) {
return getInitializedApi().post(url, data);
}
// Public functions
// Note how short these are due to the centralized config and helpers above. 😎
export function getUserById(id) {
return get(`user/${id}`);
}
export function saveUser(user) {
return post(`user/${user.id}`, {user: user});
}
@dahlbyk
Copy link

dahlbyk commented Dec 31, 2017

post(`user/{id}`, {user: user})

Is this Axios magic to parse user/{id}?

@coryhouse
Copy link
Author

Oops, fixed. Thanks Keith!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment