DEV Community

iron_man
iron_man

Posted on

Api

export async function refreshCsrf(): Promise {
// Spring Security ignores CSRF for /api/** in this application.
}

export async function api(
path: string,
method = "GET",
body?: unknown
): Promise {
const headers: Record = {
Accept: "application/json"
};

const request: RequestInit = {
method,
headers,
credentials: "include"
};

if (body !== undefined) {
headers["Content-Type"] = "application/json";
request.body = JSON.stringify(body);
}

const response = await fetch(path, request);

if (!response.ok) {
const data = (await response.json().catch(() => null)) as {
message?: string;
} | null;

throw new Error(
  data?.message ?? `Request failed (${response.status}).`
);
Enter fullscreen mode Exit fullscreen mode

}

return response.status === 204
? (undefined as T)
: ((await response.json()) as T);
}

export async function login(
username: string,
password: string
): Promise {
// UI says “Administrator”; Spring Security user is named “admin”.
const normalized = username.trim().toLowerCase();
const backendUsername =
normalized === "administrator" ? "admin" : normalized;

const form = new URLSearchParams({
username: backendUsername,
password
});

const response = await fetch("/api/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: form.toString(),
credentials: "include"
});

if (!response.ok) {
throw new Error("Sign-in failed. Check the configured application account.");
}
}

Top comments (0)