37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import type { ZitadelAuth } from "@kuns/zitadel-auth";
|
|
|
|
/** API call failure carrying the HTTP status (401 = authenticated but not authorized). */
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public status: number,
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
// Access the bootstrap-provided Zitadel auth instance + a small JSON helper for /api calls.
|
|
// By the time any component mounts, the plugin has gated auth, so `auth` is authenticated.
|
|
// `auth.fetch` auto-attaches the Bearer access token.
|
|
export function useAuth() {
|
|
const { $auth } = useNuxtApp() as unknown as { $auth: ZitadelAuth };
|
|
|
|
async function api<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
|
const res = await $auth.fetch(`/api${path}`, init);
|
|
if (!res.ok) {
|
|
let message = `${res.status}`;
|
|
try {
|
|
const body = await res.json();
|
|
message = body?.statusMessage || body?.message || message;
|
|
} catch {
|
|
// non-JSON error body
|
|
}
|
|
throw new ApiError(message, res.status);
|
|
}
|
|
if (res.status === 204) return undefined as T;
|
|
return (await res.json()) as T;
|
|
}
|
|
|
|
return { auth: $auth, api };
|
|
}
|