Created
April 12, 2019 10:36
-
-
Save AnjaneyuluBatta505/69d85c1db8d4cbf05b3b04cd04a08e17 to your computer and use it in GitHub Desktop.
requests lib using fetch
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
const getQueryString = params => { | |
return Object.keys(params) | |
.map(k => { | |
if (Array.isArray(params[k])) { | |
return params[k] | |
.map(val => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`) | |
.join("&"); | |
} | |
return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`; | |
}) | |
.join("&"); | |
}; | |
const request = params => { | |
var method = params.method || "GET"; | |
var qs = ""; | |
var body; | |
var headers = params.headers || { | |
Accept: "application/json", | |
"Content-Type": "application/json" | |
}; | |
if (["GET", "DELETE"].indexOf(method) > -1) | |
qs = "?" + getQueryString(params.data); | |
// POST or PUT | |
else body = JSON.stringify(params.data); | |
var url = params.url + qs; | |
return fetch(url, { method, headers, body }).then(response => | |
response.json() | |
// .then(data => ({ status: response.status, data: data })) | |
); | |
}; | |
export default { | |
get: params => request(Object.assign({ method: "GET" }, params)), | |
post: params => request(Object.assign({ method: "POST" }, params)), | |
put: params => request(Object.assign({ method: "PUT" }, params)), | |
patch: params => request(Object.assign({ method: "PATCH" }, params)), | |
delete: params => request(Object.assign({ method: "DELETE" }, params)) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment