Skip to content

Instantly share code, notes, and snippets.

@alejandropaciotti
Created December 26, 2021 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alejandropaciotti/7492a4c4d6d043ec986c5c498da8d03f to your computer and use it in GitHub Desktop.
Save alejandropaciotti/7492a4c4d6d043ec986c5c498da8d03f to your computer and use it in GitHub Desktop.
class HttpClient {
constructor(options = {}) {
this._baseURL = options.baseURL || "";
}
async _fetchJSON(endpoint, options = {}) {
const res = await fetch(this._baseURL + endpoint, {
...options,
});
if (!res.ok) throw new Error(res.statusText);
if (options.parseResponse !== false && res.status !== 204)
return res.json();
return undefined;
}
get(endpoint, options = {}) {
return this._fetchJSON(endpoint, {
...options,
method: "GET",
});
}
}
class ApiClient extends HttpClient {
constructor(baseURL) {
super({
baseURL,
});
}
get users() {
return {
get: () => this.get("/users"),
};
}
}
(function () {
const client = new ApiClient("https://www.mockachino.com/a71b232c-218e-4d",);
async function app() {
try {
const users = await client.users.get();
// Aca haces lo que quieras con la variable users.
} catch (err) {
console.log(err);
}
}
app();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment