planning-fight/lib/api.ts

54 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-11-04 14:18:19 +00:00
const API_URL = typeof window !== 'undefined'
? (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001')
: (process.env.API_URL || 'http://localhost:3001');
export interface Worker {
id: string;
name: string;
presenceDays: number;
}
export const workersAPI = {
async getAll(): Promise<Worker[]> {
const response = await fetch(`${API_URL}/workers`);
if (!response.ok) throw new Error('Failed to fetch workers');
return response.json();
},
async create(worker: Omit<Worker, 'id'>): Promise<Worker> {
const response = await fetch(`${API_URL}/workers`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(worker),
});
if (!response.ok) throw new Error('Failed to create worker');
return response.json();
},
async update(id: string, worker: Partial<Worker>): Promise<Worker> {
const response = await fetch(`${API_URL}/workers/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(worker),
});
if (!response.ok) throw new Error('Failed to update worker');
return response.json();
},
async delete(id: string): Promise<void> {
const response = await fetch(`${API_URL}/workers/${id}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete worker');
},
async resetAllPresences(): Promise<void> {
const workers = await this.getAll();
await Promise.all(
workers.map(worker =>
this.update(worker.id, { presenceDays: 0 })
)
);
},
};