Files
gatehouse-ui/src/lib/api.ts
T

130 lines
2.6 KiB
TypeScript
Raw Normal View History

2026-01-06 15:33:03 +00:00
// API Client for Gatehouse Backend
// Uses session-based authentication with cookies
2026-01-06 15:42:41 +00:00
import { config } from '@/config';
2026-01-06 15:33:03 +00:00
interface ApiResponse<T = unknown> {
version: string;
success: boolean;
code: number;
message: string;
data?: T;
error?: {
type: string;
details: Record<string, unknown>;
};
}
export interface User {
id: string;
email: string;
2026-01-06 16:06:53 +00:00
email_verified: boolean;
2026-01-06 15:33:03 +00:00
full_name: string | null;
avatar_url: string | null;
2026-01-06 16:06:53 +00:00
status: string;
last_login_at: string | null;
created_at: string;
updated_at: string;
}
export interface Organization {
id: string;
name: string;
slug: string;
description: string | null;
logo_url: string | null;
2026-01-06 15:33:03 +00:00
is_active: boolean;
2026-01-06 16:06:53 +00:00
role: string;
2026-01-06 15:33:03 +00:00
created_at: string;
updated_at: string;
}
2026-01-06 16:06:53 +00:00
export interface OrganizationsResponse {
organizations: Organization[];
count: number;
}
2026-01-06 15:33:03 +00:00
export interface Session {
id: string;
expires_at: string;
}
export interface LoginResponse {
user: User;
session: Session;
}
export interface ProfileResponse {
user: User;
}
class ApiError extends Error {
code: number;
type: string;
details: Record<string, unknown>;
constructor(message: string, code: number, type: string, details: Record<string, unknown> = {}) {
super(message);
this.name = 'ApiError';
this.code = code;
this.type = type;
this.details = details;
}
}
async function request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
2026-01-06 15:42:41 +00:00
const response = await fetch(`${config.api.baseUrl}${endpoint}`, {
2026-01-06 15:33:03 +00:00
...options,
credentials: 'include', // Important: include session cookies
headers: {
'Content-Type': 'application/json',
...options.headers,
},
});
const json: ApiResponse<T> = await response.json();
if (!json.success) {
throw new ApiError(
json.message || 'An error occurred',
json.code,
json.error?.type || 'UNKNOWN_ERROR',
json.error?.details || {}
);
}
return json.data as T;
}
export const api = {
auth: {
login: (email: string, password: string, remember_me = false) =>
request<LoginResponse>('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password, remember_me }),
}),
logout: () =>
request<void>('/auth/logout', {
method: 'POST',
}),
},
users: {
me: () => request<ProfileResponse>('/users/me'),
updateMe: (data: { full_name?: string; avatar_url?: string }) =>
request<ProfileResponse>('/users/me', {
method: 'PATCH',
body: JSON.stringify(data),
}),
2026-01-06 16:06:53 +00:00
organizations: () => request<OrganizationsResponse>('/users/me/organizations'),
2026-01-06 15:33:03 +00:00
},
};
export { ApiError };