Skip to content

Instantly share code, notes, and snippets.

@meftunca
Created August 6, 2019 21:55
Show Gist options
  • Save meftunca/12f2b2e61d8dd0d3425b804f73cc1002 to your computer and use it in GitHub Desktop.
Save meftunca/12f2b2e61d8dd0d3425b804f73cc1002 to your computer and use it in GitHub Desktop.
Fetch Api With Es6 Class
class fetchApi {
// method = "GET";
defaultConfig = {
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "*same-origin", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "*same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer" // no-referrer, *client
};
setConfig(defaultConfig) {
this.defaultConfig = Object.assign({}, this.defaultConfig, defaultConfig);
return this;
}
post(url, data = {}, config = {}) {
this.defaultConfig.method = "POST";
let headers = new Headers({
...this.defaultConfig,
...config,
body: objectToFormData(data)
});
return fetch(new Request(url, headers)).then(async res => {
let returnObj = {
statusText: res.statusText,
status: res.status,
ok: res.ok,
type: res.type,
trailer: res.trailer,
url: res.url,
data: await res.json()
};
return returnObj;
});
}
put(url, data = {}, config = {}) {
this.defaultConfig.method = "PUT";
let headers = new Headers({
...this.defaultConfig,
...config,
body: objectToFormData(data)
});
return fetch(new Request(url, headers)).then(async res => {
let returnObj = {
statusText: res.statusText,
status: res.status,
ok: res.ok,
type: res.type,
trailer: res.trailer,
url: res.url,
data: await res.json()
};
return returnObj;
});
}
delete(url, data = {}, config = {}) {
this.defaultConfig.method = "DELETE";
let headers = new Headers({
...this.defaultConfig,
...config,
body: objectToFormData(data)
});
return fetch(new Request(url, headers)).then(async res => {
let returnObj = {
statusText: res.statusText,
status: res.status,
ok: res.ok,
type: res.type,
trailer: res.trailer,
url: res.url,
data: await res.json()
};
return returnObj;
});
}
get(url, data = {}, config = {}) {
this.defaultConfig.method = "GET";
let headers = new Headers({
...this.defaultConfig,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
...config,
body: new URLSearchParams(data)
});
return fetch(new Request(url, headers)).then(async res => {
let returnObj = {
statusText: res.statusText,
status: res.status,
ok: res.ok,
type: res.type,
trailer: res.trailer,
url: res.url,
data: await res.json()
};
return returnObj;
});
}
}
const iFetch = new fetchApi();
//examples
iFetch.get("https://api.ipify.org?format=json").then(a => {
console.log("a", a, a.data);
});
iFetch
.post("https://api.github.com/repos/vmg/redcarpet/issues?state=closed")
.then(a => {
console.log("a", a, a.data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment