Login sequence and inventory/protocol storage groundwork
This commit is contained in:
63
lib/api.ts
Normal file
63
lib/api.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import type { ChemicalInventory, SafetyIssue } from '../shared/types';
|
||||
|
||||
async function apiFetch(path: string, options: RequestInit = {}): Promise<Response> {
|
||||
const res = await fetch(path, {
|
||||
...options,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: res.statusText }));
|
||||
throw new Error(err.error || 'API error');
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export const chemicalsApi = {
|
||||
list: (): Promise<ChemicalInventory[]> =>
|
||||
apiFetch('/api/chemicals').then(r => r.json()),
|
||||
|
||||
create: (data: Partial<ChemicalInventory>): Promise<ChemicalInventory> =>
|
||||
apiFetch('/api/chemicals', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}).then(r => r.json()),
|
||||
|
||||
update: (id: string, data: Partial<ChemicalInventory>): Promise<ChemicalInventory> =>
|
||||
apiFetch(`/api/chemicals/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}).then(r => r.json()),
|
||||
|
||||
remove: (id: string): Promise<void> =>
|
||||
apiFetch(`/api/chemicals/${id}`, { method: 'DELETE' }).then(() => undefined),
|
||||
};
|
||||
|
||||
export const protocolsApi = {
|
||||
list: () => apiFetch('/api/protocols').then(r => r.json()),
|
||||
|
||||
create: (formData: FormData) =>
|
||||
fetch('/api/protocols', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: formData, // Don't set Content-Type — browser sets multipart boundary
|
||||
}).then(r => r.json()),
|
||||
|
||||
createFromText: (title: string, content: string) =>
|
||||
apiFetch('/api/protocols', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, content }),
|
||||
}).then(r => r.json()),
|
||||
|
||||
saveAnalysis: (id: string, results: SafetyIssue[]) =>
|
||||
apiFetch(`/api/protocols/${id}/analysis`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ analysis_results: results }),
|
||||
}).then(r => r.json()),
|
||||
|
||||
remove: (id: string): Promise<void> =>
|
||||
apiFetch(`/api/protocols/${id}`, { method: 'DELETE' }).then(() => undefined),
|
||||
};
|
||||
Reference in New Issue
Block a user