Skip to content

Instantly share code, notes, and snippets.

@BolajiOlajide
Created April 20, 2021 15:03
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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