cuizin/cuizin/js_src/api.js

89 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-03-04 23:37:10 +01:00
import * as constants from '@/constants';
2018-03-13 19:02:10 +01:00
function fetchAPI(endpoint, params = {}) {
return fetch(
`${constants.API_URL}${endpoint}`,
Object.assign({}, { credentials: 'same-origin' }, params),
);
}
2018-03-04 23:37:10 +01:00
function loadJSON(response) {
return response.json();
}
function _postProcessRecipes(response) {
return loadJSON(response)
.then((jsonResponse) => {
const parsed = jsonResponse;
if (parsed.recipes) {
// Customize instructions
parsed.recipes = parsed.recipes.map(item => Object.assign(
item,
{
instructions: item.instructions ? item.instructions.split(/[\r\n]\n/).map(
2018-03-04 23:37:10 +01:00
line => line.trim(),
) : [],
2018-03-04 23:37:10 +01:00
},
));
}
return parsed;
});
}
export function loadRecipes() {
2018-03-13 19:02:10 +01:00
return fetchAPI('api/v1/recipes')
2018-03-04 23:37:10 +01:00
.then(_postProcessRecipes);
}
export function loadRecipe(id) {
2018-03-13 19:02:10 +01:00
return fetchAPI(`api/v1/recipe/${id}`)
2018-03-04 23:37:10 +01:00
.then(_postProcessRecipes);
}
export function refetchRecipe(id) {
2018-03-13 19:02:10 +01:00
return fetchAPI(`api/v1/recipe/${id}/refetch`)
2018-03-04 23:37:10 +01:00
.then(_postProcessRecipes);
}
2018-03-10 11:43:14 +01:00
export function postRecipeByUrl(recipe) {
2018-03-13 19:02:10 +01:00
return fetchAPI('api/v1/recipes/by_url', {
2018-03-10 11:43:14 +01:00
method: 'POST',
body: JSON.stringify(recipe),
})
.then(_postProcessRecipes);
}
export function postRecipeManually(recipe) {
2018-03-13 19:02:10 +01:00
return fetchAPI('api/v1/recipes/manually', {
2018-03-04 23:37:10 +01:00
method: 'POST',
body: JSON.stringify(recipe),
})
.then(_postProcessRecipes);
}
2018-03-11 16:49:05 +01:00
export function editRecipe(id, recipe) {
2018-03-13 19:02:10 +01:00
return fetchAPI(`api/v1/recipe/${id}`, {
2018-03-11 16:49:05 +01:00
method: 'POST',
body: JSON.stringify(recipe),
})
.then(_postProcessRecipes);
}
2018-03-04 23:37:10 +01:00
export function deleteRecipe(id) {
2018-03-13 19:02:10 +01:00
return fetchAPI(`api/v1/recipe/${id}`, {
2018-03-04 23:37:10 +01:00
method: 'DELETE',
});
}