Skip to content

Instantly share code, notes, and snippets.

@leMaur
Created December 17, 2020 15:00
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 leMaur/36b784d92754d290c58bc14e79649871 to your computer and use it in GitHub Desktop.
Save leMaur/36b784d92754d290c58bc14e79649871 to your computer and use it in GitHub Desktop.
export default class RestJson {
constructor(endpoint, options = {}) {
if (!window.fetch) {
console.error("Sorry you cannot use RestJson Class, your browser doesn't support Fetch API.");
console.error("Please try with another browser or update it to a new version.");
}
const defaultOptions = {
headers: {'Content-Type': 'application/json'}
};
this.endpoint = endpoint;
this.options = Object.assign(defaultOptions, options);
this.queryString = '';
this.id = '';
}
withParams(params) {
if (Object.keys(params).length) {
const query = new URLSearchParams();
Object.entries(params).forEach(param => query.set(param[0], param[1]));
this.queryString = `?${query.toString()}`;
}
return this;
}
withId(id) {
if (typeof id === 'number') {
this.id = `/${id}`;
}
return this;
}
async baseFetch(method, payload = null) {
if (payload) {
this.options.body = JSON.stringify(payload);
}
this.options.method = method;
let response = await fetch(
this.endpoint + this.id + this.queryString,
this.options
);
if (!response.ok) {
throw new Error(response.status);
}
this.options.body = null;
this.queryString = '';
this.id = '';
if (response.status === 204) {
return response;
}
return response.json();
}
get() {
return this.baseFetch('GET');
}
post(data) {
return this.baseFetch('POST', data);
}
put(data) {
return this.baseFetch('PUT', data);
}
patch(data) {
return this.baseFetch('PATCH', data);
}
delete() {
return this.baseFetch('DELETE');
}
}
@leMaur
Copy link
Author

leMaur commented Dec 17, 2020

How to use it

let restJson = new RestJson('https://rest.api.com/endpoint');

// GET
restJson
  .get()
  .then(response => {
    // do something...
  });

// POST
restJson
  .post('id') // <== fill in with item id
  .then(transaction => {
    // do something...
    }
  });

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