Skip to content

Instantly share code, notes, and snippets.

@anomaly44
Created December 15, 2015 14:09
Show Gist options
  • Save anomaly44/c4f8fd7b7276ab9aa622 to your computer and use it in GitHub Desktop.
Save anomaly44/c4f8fd7b7276ab9aa622 to your computer and use it in GitHub Desktop.
import superagent from 'superagent';
import config from '../config';
import cookie from 'react-cookie';
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__) {
// Prepend host and port of the API server to the path.
return 'http://' + config.apiHost + ':' + config.apiPort + adjustedPath;
}
// Prepend `/api` to relative URL, to proxy to API server.
return '/api' + adjustedPath;
}
/*
* This silly underscore is here to avoid a mysterious "ReferenceError: ApiClient is not defined" error.
* See Issue #14. https://github.com/erikras/react-redux-universal-hot-example/issues/14
*
* Remove it at your own risk.
*/
class _ApiClient {
constructor(req) {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
if (cookie && cookie.load('RES')) {
request.set('authorization', 'Bearer ' + cookie.load('RES'));
console.log(JSON.stringify(request.header) + ' apiclient: ' + cookie.load('RES'));
}
if (__SERVER__ && req.get('cookie')) {
request.set('cookie', req.get('cookie'));
}
if (data) {
request.send(data);
}
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
}
const ApiClient = _ApiClient;
export default ApiClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment