Skip to content

Commit

Permalink
Server API Url Function
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasAunvik committed Apr 22, 2024
1 parent 4405dda commit d75fe0b
Showing 1 changed file with 32 additions and 29 deletions.
61 changes: 32 additions & 29 deletions Web/Client/lib/api/fetch.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(
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 <T>(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 <T, B>(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 <T, B>(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;
};

0 comments on commit d75fe0b

Please sign in to comment.