-
Notifications
You must be signed in to change notification settings - Fork 4
/
database.ts
65 lines (54 loc) · 1.48 KB
/
database.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { defineStore } from 'pinia';
import { api } from 'src/boot/axios';
import { Ingredient, Recipe } from 'src/components/models';
import { ref } from 'vue';
export const useDatabaseStore = defineStore('database', () => {
const recipes = ref<Recipe[]>([]);
const isLoading = ref<boolean>(false);
async function fetchAllRecipes() {
isLoading.value = false;
const { data } = await api.get('/recipes');
const allRecipes = data.recipes.map(
(data: Recipe & { ingredients: string }) => {
const { ingredients, ...recipe } = data;
return {
...recipe,
ingredients: ingredients !== undefined ? JSON.parse(ingredients) : [],
} as unknown as Recipe;
}
) as Recipe[];
recipes.value = allRecipes;
isLoading.value = false;
}
async function addRecipe({
recipe,
ingredients,
}: {
recipe: Recipe;
ingredients: Ingredient[];
}) {
isLoading.value = true;
await api.post<Recipe[]>('/recipe', {
recipe: recipe,
ingredients,
});
fetchAllRecipes();
}
function getRecipeById(id: string): Recipe | undefined {
return recipes.value.filter((recipe) => recipe.id === id)[0];
}
async function deleteRecipe(recipe: Recipe) {
isLoading.value = true;
await api.delete(`/recipe/${recipe.id}`);
fetchAllRecipes();
isLoading.value = false;
}
return {
recipes,
isLoading,
fetchAllRecipes,
getRecipeById,
addRecipe,
deleteRecipe,
};
});