Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Last active May 30, 2021 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rw3iss/08636dd6cc136b5284aa350db5da83c1 to your computer and use it in GitHub Desktop.
Save rw3iss/08636dd6cc136b5284aa350db5da83c1 to your computer and use it in GitHub Desktop.
HttpClient base class - a fetch wrapper for service classes to extend, with Basic authentication token using cookies, no dependencies
import Request from './Request';
//import ErrorService from 'lib/services/ErrorService';
// Todo: change body + headers arguments to opts: {} object.
export default class HttpClient {
// shortcuts
public get<T>(url) {
return this.request(url, 'GET');
}
public post<T>(url, body) {
return this.request(url, 'POST', body);
}
public put<T>(url, body) {
return this.request(url, 'PUT', body);
}
public delete<T>(url) {
return this.request(url, 'DELETE');
}
// underlying Request wrapper. Can manage responses.
private async request(url: string, method: string = 'GET', body: any = undefined, headers = undefined): Promise<any> {
return new Promise((resolve, reject) => {
let request;
switch (method.toLowerCase()) {
case 'get':
request = Request.get(url, headers);
break;
case 'post':
request = Request.post(url, body, headers);
break;
case 'put':
request = Request.put(url, body, headers);
break;
case 'delete':
request = Request.delete(url, headers);
break;
default:
request = Request.get(url, headers);
break;
}
request
.then(r => {
// first see if an error was thrown
console.log('response', r)
if (!r.ok) {
console.log('bad response')
let handled = false;// ErrorService.handleError(r);
if (!handled) {
return reject(r);
} else {
return resolve(false);
}
}
return r.text()
})
.then(text => {
return text ? JSON.parse(text) : {};
})
.then(r => {
return resolve(r);
})
.catch(e => {
console.log('REQUEST ERROR', e)
return reject("Failed to make request.");
});
});
}
}
const fetch = require('node-fetch').default;
// adds Authorization header with JWT token, etc...
function _makeRequestOptions(opts) {
opts = opts || {}
// let token = _getAccessToken();
// if (token) {
// opts.headers = opts.headers || {};
// opts.headers["Authorization"] = opts.headers["Authorization"] || `Bearer ${token}`;
// }
return opts
}
class Request {
static async get(url, headers) {
let opts = {
mode: 'cors',
method: 'GET',
// credentials: 'include',
headers: headers,
redirect: 'follow'
}
opts = _makeRequestOptions(opts)
return fetch(url, opts)
}
static async post(url, data, headers) {
let opts = {
mode: 'cors',
body: data ? JSON.stringify(data) : undefined,
method: 'POST',
// credentials: 'include',
headers: {
'Content-Type': 'application/json',
...headers
},
redirect: 'follow'
}
opts = _makeRequestOptions(opts)
return fetch(url, opts).catch(e => {
console.log('caught request', e)
})
}
static async put(url, data, headers) {
let opts = {
mode: 'cors',
body: data ? JSON.stringify(data) : undefined,
method: 'PUT',
// credentials: 'include',
headers: {
'Content-Type': 'application/json',
...headers
}
}
opts = _makeRequestOptions(opts)
return fetch(url, opts)
}
static async delete(url, headers) {
let opts = {
method: 'DELETE',
headers: headers
}
opts = _makeRequestOptions(opts)
return fetch(url, opts)
}
// Helper to extract error messaging from responses
static findError(res) {
return res
? res.error
? res.error
: res.message
? res.message
: 'An unknown error occurred.'
: 'An unknown error occurred.'
}
}
export default Request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment