client/src/APIClient.js
author Alexandre Segura <mex.zktk@gmail.com>
Mon, 19 Jun 2017 14:35:48 +0200
changeset 49 39f69dc1c2d2
parent 44 3b20e2b584fe
child 51 08d46c730397
permissions -rw-r--r--
Use token to identify requests.

class APIClient {
  constructor(baseURL) {
    this.baseURL = baseURL;
  }

  createRequest = (method, uri, data, headers) => {

    headers = headers || new Headers();
    headers.append("Content-Type", "application/json");

    var options = {
      method: method,
      headers: headers,
    };

    if (data) {
      options.body = JSON.stringify(data);
    }

    // TODO : use URL-module to build URL
    return new Request(this.baseURL + uri, options);
  }

  hasToken = () => {
    const token = this.localStorage.get('token');

    return token !== null;
  }

  createAuthorizedRequest = (method, uri, data) => {

    var headers = new Headers(),
        token = this.localStorage.get('token') || '';
    headers.append("Authorization", "Bearer " + token);
    headers.append("Content-Type", "application/json");

    return this.createRequest(method, uri, data, headers);
  }

  request = (method, uri, data) => {
    console.log(method + ' ' + uri);
    var req = this.hasToken() ? this.createAuthorizedRequest(method, uri, data) : this.createRequest(method, uri, data);
    return this.fetch(req, { credentials: 'include' });
  }

  get = (uri, data) => {
    return this.request('GET', uri, data);
  }

  post = (uri, data) => {
    return this.request('POST', uri, data);
  }

  put = (uri, data) => {
    return this.request('PUT', uri, data);
  }

  fetch = (req) => {
    return new Promise((resolve, reject) => {
      fetch(req)
        .then((response) => {
          if (response.ok) {
            return response.json().then((data) => resolve(data));
          } else {
            return response.json().then((data) => reject(data));
          }
        });
    });
  }
}

export default APIClient