Skip to content

Instantly share code, notes, and snippets.

@iksose
Created December 4, 2015 22:16
Show Gist options
  • Save iksose/43ec69e0b02135dae50c to your computer and use it in GitHub Desktop.
Save iksose/43ec69e0b02135dae50c to your computer and use it in GitHub Desktop.
import queryString from "query-string";
let _route = "api/v2.0/";
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
const verbs = {
get: async function(id, params, cache = false){
const response = await fetch(`${this.route}/${id}`, { method: 'GET', headers });
let data = await response.json();
return Reflect.construct(this[_constructor], [data])
},
query: async function(params = {}, cached = false){
params = queryString.stringify(params);
const response = await fetch(`${this.route}?${params}`, { method: 'GET', headers });
let data = await response.json();
return data.results
},
update: async function(resource = this){
const response = await fetch(`${resource.route}/${resource.id}`, { method: 'PATCH', headers, body: JSON.stringify(resource) })
return await response.json();
},
save: async function(resource = this){
const response = await fetch(`${resource.route}`, { method: 'POST', headers, body: JSON.stringify(resource) })
return await response.json();
},
get route(){
return _route;
},
}
const _constructor = Symbol("_class")
class AbstractResource {
constructor(route, constructor) {
this[_constructor] = constructor;
_route += route;
Object.assign(this, verbs);
}
instance(...args){
return Reflect.construct(this[_constructor], args)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment