From d75fe0b1214f64f63236eb6a6747d6412d288a1e Mon Sep 17 00:00:00 2001 From: Thomas Aunvik Date: Mon, 22 Apr 2024 23:06:31 +0200 Subject: [PATCH] Server API Url Function --- Web/Client/lib/api/fetch.ts | 61 +++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/Web/Client/lib/api/fetch.ts b/Web/Client/lib/api/fetch.ts index 533c30a..764f39d 100644 --- a/Web/Client/lib/api/fetch.ts +++ b/Web/Client/lib/api/fetch.ts @@ -1,48 +1,51 @@ import { cookies } from "next/headers"; import "server-only"; -const SERVER_API_URL = process.env.SERVER_API_URL; -if (!SERVER_API_URL || SERVER_API_URL === "") { - throw new Error("SERVER_API_URL env is not set"); -} +const getServerApiUrl = () => { + const env = process.env.SERVER_API_URL; + if (!env || env === "") { + throw new Error("SERVER_API_URL env is not set"); + } + return env; +}; const LOGIN_COOKIE_NAME = ".AspNetCore.Cookies"; export const apiFetch = ( - path: string, - method: "GET" | "POST" | "PUT", - body?: T, + path: string, + method: "GET" | "POST" | "PUT", + body?: T, ) => { - const cook = cookies(); - const cookieValue = cook.get(LOGIN_COOKIE_NAME); - const loginValue = cookieValue?.value; + const cook = cookies(); + const cookieValue = cook.get(LOGIN_COOKIE_NAME); + const loginValue = cookieValue?.value; - return fetch(`${SERVER_API_URL}${path}`, { - method: method, - headers: { - ...(loginValue ? { Cookie: `${LOGIN_COOKIE_NAME}=${cookieValue}` } : {}), - "Content-Type": "application/json", - }, - body: JSON.stringify(body), - }); + return fetch(`${getServerApiUrl()}${path}`, { + method: method, + headers: { + ...(loginValue ? { Cookie: `${LOGIN_COOKIE_NAME}=${cookieValue}` } : {}), + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }); }; export const apiGET = async (path: string) => { - const res = await apiFetch(path, "GET"); - const text = await res.text(); - console.log(text); - const data = JSON.parse(text); - return data as T; + const res = await apiFetch(path, "GET"); + const text = await res.text(); + console.log(text); + const data = JSON.parse(text); + return data as T; }; export const apiPOST = async (path: string, body: B) => { - const res = await apiFetch(path, "POST", body); - const data = await res.json(); - return data as T; + const res = await apiFetch(path, "POST", body); + const data = await res.json(); + return data as T; }; export const apiPUT = async (path: string, body: B) => { - const res = await apiFetch(path, "PUT", body); - const data = await res.json(); - return data as T; + const res = await apiFetch(path, "PUT", body); + const data = await res.json(); + return data as T; };