platform-codebase/@packages/@providers/profile-client/src/profile-api.ts

90 lines
2 KiB
TypeScript

/**
* Profile API Client
*
* Functions for fetching and updating profiles from the profile backend.
*/
import type { ProfileData, ProfileType, ProfileUpdateData } from './types';
/**
* Fetch all profiles for the current user.
*/
export async function fetchAllProfiles(
baseUrl: string,
authHeaders?: Record<string, string>
): Promise<ProfileData[]> {
const response = await fetch(`${baseUrl}/api/profile/all`, {
headers: authHeaders,
});
if (response.status === 404) {
return [];
}
if (!response.ok) {
throw new Error(`Failed to fetch profiles: ${response.statusText}`);
}
return response.json();
}
/**
* Fetch a specific profile by type.
*/
export async function fetchProfileByType(
baseUrl: string,
type: ProfileType,
authHeaders?: Record<string, string>
): Promise<ProfileData | null> {
const response = await fetch(`${baseUrl}/api/profile/${type}`, {
headers: authHeaders,
});
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(`Failed to fetch profile: ${response.statusText}`);
}
return response.json();
}
/**
* Create or update a profile.
*/
export async function saveProfile(
baseUrl: string,
type: ProfileType,
data: ProfileUpdateData,
authHeaders?: Record<string, string>
): Promise<ProfileData> {
const response = await fetch(`${baseUrl}/api/profile/${type}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...authHeaders,
},
body: JSON.stringify(data),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(error.message || 'Failed to save profile');
}
return response.json();
}
/**
* Get auth headers for API requests.
* Uses Bearer token if available.
*/
export function getAuthHeaders(accessToken?: string | null): Record<string, string> {
const headers: Record<string, string> = {};
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
}
return headers;
}