Created
December 26, 2021 16:48
-
-
Save alejandropaciotti/7492a4c4d6d043ec986c5c498da8d03f to your computer and use it in GitHub Desktop.
This file contains 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
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