Skip to content

Instantly share code, notes, and snippets.

@BolajiOlajide
Created April 20, 2021 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BolajiOlajide/c85aae2c49523c1c0d5522aff3d094df to your computer and use it in GitHub Desktop.
Save BolajiOlajide/c85aae2c49523c1c0d5522aff3d094df to your computer and use it in GitHub Desktop.
a wrapper around fetch for Asincole
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