Created
April 20, 2021 15:03
-
-
Save BolajiOlajide/c85aae2c49523c1c0d5522aff3d094df to your computer and use it in GitHub Desktop.
a wrapper around fetch for Asincole
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 fetch = require('node-fetch'); | |
const http = require('http'); | |
const https = require('https'); | |
const httpAgent = new http.Agent({ keepAlive: true }); | |
const httpsAgent = new https.Agent({ keepAlive: true }); | |
const agent = (parsedUrl) => parsedUrl.protocol == 'http:' ? httpAgent : httpsAgent; | |
const client = { | |
async _createClient(method, url, payload = null, headers = {}) { | |
const config = { | |
method, | |
agent, | |
headers: { | |
'Content-Type': 'application/json', | |
...headers | |
} | |
}; | |
if (payload) { | |
config.body = payload; | |
} | |
const response = await fetch(url, config); | |
const data = await response.json(); | |
if (response.ok) { | |
return data; | |
} | |
return Promise.reject(data); | |
}, | |
async get(url, payload = null, headers = {}) { | |
const method = 'GET'; | |
return client._createClient(method, url, payload, headers); | |
}, | |
async post(url, payload, headers = {}) { | |
const method = 'POST'; | |
return client._createClient(method, url, payload, headers); | |
}, | |
}; | |
module.exports = client; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment