add api utils
This commit is contained in:
parent
ee3ac34e4b
commit
bdd90b50d9
6 changed files with 99 additions and 93 deletions
|
|
@ -1,10 +1,11 @@
|
|||
import type { Recipe } from "../types/recipe"
|
||||
import { get, postJson, putJson } from "./utils/requests";
|
||||
|
||||
|
||||
/**
|
||||
* Util for handling the recipe api
|
||||
*/
|
||||
// reate base url from .env file
|
||||
// read base url from .env file
|
||||
const BASE_URL = import.meta.env.VITE_API_BASE;
|
||||
|
||||
/**
|
||||
|
|
@ -18,10 +19,7 @@ const RECIPE_URL = `${BASE_URL}/recipe`
|
|||
* @returns A single recipe
|
||||
*/
|
||||
export async function fetchRecipe(id: string): Promise<Recipe> {
|
||||
const res = await fetch(`${RECIPE_URL}/${id}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch recipe with id ${id}`)
|
||||
}
|
||||
const res = await get(`${RECIPE_URL}/${id}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
|
|
@ -36,12 +34,8 @@ export async function fetchRecipeList(searchString : string): Promise<Recipe[]>
|
|||
if(searchString && searchString !== ""){
|
||||
url +="?search=" + searchString;
|
||||
}
|
||||
console.log("calling url", url)
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch recipe list`)
|
||||
}
|
||||
return res.json()
|
||||
const res = await get(url);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -50,15 +44,8 @@ export async function fetchRecipeList(searchString : string): Promise<Recipe[]>
|
|||
* @returns Saved recipe
|
||||
*/
|
||||
export async function createRecipe(recipe: Recipe): Promise<Recipe> {
|
||||
const res = await fetch(RECIPE_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(recipe),
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to create recipe")
|
||||
}
|
||||
return res.json()
|
||||
const res = await postJson(RECIPE_URL, JSON.stringify(recipe));
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -67,13 +54,6 @@ export async function createRecipe(recipe: Recipe): Promise<Recipe> {
|
|||
* @returns Saved recipe
|
||||
*/
|
||||
export async function updateRecipe(recipe: Recipe): Promise<Recipe> {
|
||||
const res = await fetch(`${RECIPE_URL}/${recipe.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(recipe),
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to update recipe with id ${recipe.id}`)
|
||||
}
|
||||
return res.json()
|
||||
const res = await putJson(`${RECIPE_URL}/${recipe.id}`, JSON.stringify(recipe));
|
||||
return res.json();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue