Skip to content

Instantly share code, notes, and snippets.

@joaofnds
Last active November 21, 2018 21:11
Show Gist options
  • Select an option

  • Save joaofnds/805d41c14f31411c13586149a4419f77 to your computer and use it in GitHub Desktop.

Select an option

Save joaofnds/805d41c14f31411c13586149a4419f77 to your computer and use it in GitHub Desktop.
Example of an API class that helps with server communication
const SERVER_URL = "https://donamaid.herokuapp.com";
class API {
constructor() {
this.token = null;
this.currentUser = null;
this.defaultParams = this.defaultParams.bind(this);
this.fetchJSON = this.fetchJSON.bind(this);
this.authenticate = this.authenticate.bind(this);
this.get = this.get.bind(this);
this.post = this.post.bind(this);
}
defaultParams() {
return {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`
}
};
}
async authenticate(email, password) {
const {
data: { token, account }
} = await this.post("authentication", {
email,
password
});
this.token = token;
this.currentUser = account;
}
async fetchJSON(path, options = {}) {
return (await fetch(`${SERVER_URL}/${path}`, {
...this.defaultParams(),
...options
})).json();
}
get(path, options = {}) {
return this.fetchJSON(path, {
method: "GET",
...options
});
}
post(path, body, options = {}) {
return this.fetchJSON(path, {
method: "POST",
body: JSON.stringify(body),
...options
});
}
}
(async () => {
const api = new API();
try {
await api.authenticate("USER_EMAIL", "USER_PASSWORD");
const {
data: {
attributes: { language, time_zone: timeZone }
}
} = await api.get(`accounts/${api.currentUser.id}`);
console.log(new Date().toLocaleString(language, { timeZone }));
} catch (e) {
console.log(e);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment