import config from '../config'; import * as Errors from './Errors'; class Api { constructor() { } baseUrl() { return config.baseApiUrl; } url(path) { return this.baseUrl() + path; } checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } else if (response.status === 404) { throw new Errors.ApiNotFoundError(response.statusText, response); } else { throw new Errors.ApiServerError(response.statusText || "Unknown Server Error", response); } } parseJSON(response) { return response.json(); } performRequest(url, method, params = {}) { const hasBody = Object.keys(params || {}).length !== 0; const headers = new Headers(); headers.append('Accept', 'application/json'); const opts = { headers, method: method, credentials: "same-origin" }; if (hasBody) { headers.append('Content-Type', 'application/json'); opts.body = JSON.stringify(params); } return fetch(url, opts).then(this.checkStatus).then(this.parseJSON); } get(url, params = {}) { const queryParams = []; for (let key in params) { const val = params[key]; if (Array.isArray(val)) { for (let x of val) { queryParams.push(encodeURIComponent(key) + "[]=" + (x === null ? '' : encodeURIComponent(x))); } } else { queryParams.push(encodeURIComponent(key) + "=" + (val === null ? '' : encodeURIComponent(val))); } } if (queryParams.length) { url = url + "?" + queryParams.join("&"); } return this.performRequest(url, "GET"); } post(url, params = {}) { return this.performRequest(url, "POST", params); } getRecipeList(page, per, sortColumn, sortDirection, name, tags) { const params = { page: page || null, per: per || null, sort_column: sortColumn || null, sort_direction: sortDirection || null, name: name || null, tags: tags || null }; return this.get("/recipes", params); } postLogin(username, password) { const params = { username: username, password: password }; return this.post("/login", params); } getCurrentUser() { return this.get("/user") } } const api = new Api(); export default api;