parsley/app/javascript/lib/Api.js
2018-04-01 21:43:23 -05:00

175 lines
4.2 KiB
JavaScript

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 if (response.status === 422) {
return response.json().then(json => { throw new Errors.ApiValidationError(null, response, json) }, jsonErr => { throw new Errors.ApiValidationError(null, response, null) });
} 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);
}
objectToUrlParams(obj, queryParams = [], prefixes = []) {
for (let key in obj) {
const val = obj[key];
const paramName = prefixes.join("[") + "[".repeat(Math.min(prefixes.length, 1)) + encodeURIComponent(key) + "]".repeat(prefixes.length);
if (Array.isArray(val)) {
for (let x of val) {
queryParams.push(paramName + "[]=" + (x === null ? '' : encodeURIComponent(x)));
}
} else if (typeof(val) === "object") {
this.objectToUrlParams(val, queryParams, prefixes.concat([key]));
} else {
queryParams.push(paramName + "=" + (val === null ? '' : encodeURIComponent(val)));
}
}
return queryParams;
}
get(url, params = {}) {
const queryParams = this.objectToUrlParams(params);
if (queryParams.length) {
url = url + "?" + queryParams.join("&");
}
return this.performRequest(url, "GET");
}
post(url, params = {}) {
return this.performRequest(url, "POST", params);
}
patch(url, params = {}) {
return this.performRequest(url, "PATCH", params);
}
getRecipeList(page, per, sortColumn, sortDirection, name, tags) {
const params = {
criteria: {
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);
}
getRecipe(id) {
return this.get("/recipes/" + id);
}
patchRecipe(recipe) {
const params = {
recipe: {
name: recipe.name,
description: recipe.description,
source: recipe.source,
yields: recipe.yields,
total_time: recipe.total_time,
active_time: recipe.active_time,
step_text: recipe.step_text,
tag_names: recipe.tag_names,
recipe_ingredients_attributes: recipe.ingredients.map(i => {
if (i._destroy) {
return {
id: i.id,
_destroy: true
};
} else {
return {
id: i.id,
name: i.name,
ingredient_id: null,
quantity: i.quantity,
units: i.units,
preparation: i.preparation,
sort_order: i.sort_order
};
}
})
}
};
return this.patch("/recipes/" + recipe.id, params);
}
postPreviewSteps(step_text) {
const params = {
step_text: step_text
};
return this.post("/recipes/preview_steps", params);
}
getSearchIngredients(query) {
const params = { query: query };
return this.get("/ingredients/search", params);
}
postLogin(username, password) {
const params = {
username: username,
password: password
};
return this.post("/login", params);
}
getLogout() {
return this.get("/logout");
}
getCurrentUser() {
return this.get("/user")
}
}
const api = new Api();
export default api;