Projeto bot pontos
This commit is contained in:
34
web/lib/server-api.ts
Normal file
34
web/lib/server-api.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// Chamadas à API Go feitas pelos Server Components, pela rede interna do Docker.
|
||||
// O cookie de sessão do navegador é repassado; quem autoriza é sempre o Go.
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import type { Problem } from "./types";
|
||||
|
||||
const API = process.env.API_INTERNAL_URL ?? "http://api:8080";
|
||||
|
||||
export class ForbiddenError extends Error {}
|
||||
|
||||
export async function apiGet<T>(path: string): Promise<T> {
|
||||
const store = await cookies();
|
||||
const cookie = store
|
||||
.getAll()
|
||||
.map((c) => `${c.name}=${c.value}`)
|
||||
.join("; ");
|
||||
|
||||
const res = await fetch(`${API}/api/v1${path}`, {
|
||||
headers: { cookie, accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
redirect("/login");
|
||||
}
|
||||
if (res.status === 403) {
|
||||
throw new ForbiddenError("Seu papel não permite acessar esta página.");
|
||||
}
|
||||
if (!res.ok) {
|
||||
const problem = (await res.json().catch(() => null)) as Problem | null;
|
||||
throw new Error(problem?.title ?? `Erro ${res.status} ao consultar a API`);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
Reference in New Issue
Block a user