Last active
July 22, 2020 07:38
-
-
Save jpulec/b982b0c52f1a04669366b96353498c5e to your computer and use it in GitHub Desktop.
Request Replaced
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
import fetch from 'cross-fetch'; | |
import _ from 'lodash'; | |
const myRequests = { | |
get: (...args) => { | |
const urlOrOptions = args[0]; | |
const cb = args[1]; | |
let url; | |
let options; | |
let isJSON; | |
if (_.isString(urlOrOptions)) { | |
url = urlOrString; | |
options = {}; | |
isJSON = false; | |
} else { | |
isJSON = urlOrOptions.json; | |
url = urlOrOptions.uri || urlOrOptions.url; | |
const headers = { | |
...urlOrOptions.headers, | |
...(isJSON ? { | |
'content-type': 'application/json', | |
}: {}) | |
}; | |
const body = isJSON ? JSON.stringify(urlOrOptions.body) : urlOrOptions.body; | |
options = { | |
headers, | |
body, | |
}; | |
} | |
fetch(url, options) | |
.then((response) => { | |
if (isJSON) { | |
response.json() | |
.then((data) => { | |
cb(null, response, data); | |
}); | |
} else { | |
cb(null, response); | |
} | |
}, (err) => { | |
cb(err); | |
}); | |
}, | |
// Other methods ommited for brevity | |
}; | |
export default myRequests; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment