Skip to content

Instantly share code, notes, and snippets.

@thedgbrt
Created January 11, 2016 23:14
Show Gist options
  • Save thedgbrt/26ac3a4ad4a2aace384a to your computer and use it in GitHub Desktop.
Save thedgbrt/26ac3a4ad4a2aace384a to your computer and use it in GitHub Desktop.

Revisions

  1. thedgbrt created this gist Jan 11, 2016.
    52 changes: 52 additions & 0 deletions ApiClient.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    import superagentCache from 'superagent-cache';
    import config from '../config';

    const methods = ['get', 'post', 'put', 'patch', 'del'];
    const superagent = superagentCache(null, {backgroundRefreshInterval: 500});

    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 + 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 (__SERVER__ && req.get('cookie')) {
    request.set('cookie', req.get('cookie'));
    }

    if (data) {
    request.send(data);
    }

    request.responseProp('body').backgroundRefresh();

    request.end((err, { body } = {}) => body ? reject(err || body) : resolve(err));

    }));
    }
    }

    const ApiClient = _ApiClient;

    export default ApiClient;