add api utils

This commit is contained in:
Anika Raemer 2025-10-05 14:54:45 +02:00
parent ee3ac34e4b
commit bdd90b50d9
6 changed files with 99 additions and 93 deletions

View file

@ -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();
}

View file

@ -0,0 +1,19 @@
export function setContentTypeHeaderJson(headers: Headers){
return headers.set("Content-Type", "application/json");
}
export function setAuthHeader(headers: Headers){
// retrieve session data from browser storage
const sessionStr = localStorage.getItem("session");
let loginResponse = null;
if(sessionStr){
loginResponse = JSON.parse(sessionStr);
}
// add token if possible
if(loginResponse && loginResponse.token){
headers.set("Authorization", "Bearer " + loginResponse.token)
} else {
console.log("No access token!")
}
return headers;
}

View file

@ -0,0 +1,42 @@
import { setAuthHeader, setContentTypeHeaderJson } from "./headers";
export async function get(url: string) : Promise<Response>{
const requestHeaders = new Headers();
setAuthHeader(requestHeaders);
console.log("GET to " + url);
const response = await fetch(url, {
method: "GET",
headers: requestHeaders
})
if(!response.ok){
throw new Error("GET to " + url + "failed!")
}
return response;
}
export async function postJson(url: string, requestBody: string, logBody = true) : Promise<Response>{
console.log("POST to " + url + (logBody) ? "with body " + requestBody : "");
return persistJson(url, requestBody, "POST");
}
export async function putJson(url: string, requestBody: string, logBody = true) : Promise<Response>{
console.log("PUT to " + url + (logBody) ? "with body " + requestBody : "");
return persistJson(url, requestBody, "PUT");
}
async function persistJson(url: string, requestBody: string, requestMethod: string) : Promise<Response>{
const requestHeaders = new Headers();
setContentTypeHeaderJson(requestHeaders);
setAuthHeader(requestHeaders);
const response = await fetch(url, {
method: requestMethod,
headers: requestHeaders,
body: requestBody,
});
if(!response.ok){
throw new Error(requestMethod + " to " + url + "failed!")
}
return response;
}