diff -r 3c9d3c8f41d1 -r 3b20e2b584fe client/src/APIClient.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/client/src/APIClient.js Fri Jun 16 18:36:39 2017 +0200 @@ -0,0 +1,66 @@ +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); + } + + createAuthorizedRequest = (method, uri, data) => { + + var headers = new Headers(), + token = this.storage.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.model ? 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