project/lib/api-client.ts

78 lines
1.9 KiB
TypeScript

import { WorkItem, WorkItemFormData } from './types';
const API_BASE_URL = '';
export class WorkItemApiClient {
private baseUrl: string;
constructor(baseUrl: string = API_BASE_URL) {
this.baseUrl = baseUrl.replace(/\/$/, '');
}
private async fetchApi<T>(
endpoint: string,
options?: RequestInit
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`;
try {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
...options,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return await response.json();
}
return (await response.text()) as T;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
async getWorkItems(): Promise<WorkItem[]> {
return this.fetchApi<WorkItem[]>('/api/work-items');
}
async getWorkItem(id: number): Promise<WorkItem> {
return this.fetchApi<WorkItem>(`/api/work-items/${id}`);
}
async createWorkItem(workItem: WorkItemFormData): Promise<WorkItem> {
const newWorkItem = {
title: workItem.title,
description: workItem.description,
status: 0, // Default to Pending
};
return this.fetchApi<WorkItem>('/api/work-items', {
method: 'POST',
body: JSON.stringify(newWorkItem),
});
}
async updateWorkItem(id: number, workItem: WorkItem): Promise<void> {
await this.fetchApi(`/api/work-items/${id}`, {
method: 'PUT',
body: JSON.stringify(workItem),
});
}
async deleteWorkItem(id: number): Promise<void> {
await this.fetchApi(`/api/work-items/${id}`, {
method: 'DELETE',
});
}
}
export const workItemApi = new WorkItemApiClient();