Files
factoryOps-v2/dashboard/lib/api.ts
Johngreen 66018e37c4
All checks were successful
Deploy to Production / deploy (push) Successful in 2m7s
feat: filter equipment import by tenant-company mapping
- Add digital_twin_company_id column to tenants table
- Map spifox tenant to its digital-twin companyId
- Pass companyId filter when fetching from digital-twin API
- Return 404 with clear message for unmapped tenants
- Improve API error messages in frontend (show server detail)
2026-02-12 14:30:18 +09:00

84 lines
2.3 KiB
TypeScript

import { getStoredToken } from './auth-context';
import { getTenantFromPath } from './tenant-context';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
function getHeaders(): HeadersInit {
const token = getStoredToken();
return {
'Content-Type': 'application/json',
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
};
}
async function parseErrorDetail(res: Response): Promise<string> {
try {
const body = await res.json();
return body.detail || body.message || 'API request failed';
} catch {
return 'API request failed';
}
}
export async function fetcher<T>(url: string): Promise<T> {
const res = await fetch(`${API_BASE_URL}${url}`, {
headers: getHeaders(),
});
if (!res.ok) {
const detail = await parseErrorDetail(res);
throw new Error(detail);
}
return res.json();
}
export function getTenantUrl(path: string, tenantId?: string): string {
const tenant = tenantId || getTenantFromPath();
if (!tenant) {
throw new Error('Tenant ID not found');
}
return `/api/${tenant}${path}`;
}
export const api = {
get: <T>(url: string) => fetcher<T>(url),
post: async <T>(url: string, data: unknown): Promise<T> => {
const res = await fetch(`${API_BASE_URL}${url}`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(await parseErrorDetail(res));
return res.json();
},
put: async <T>(url: string, data: unknown): Promise<T> => {
const res = await fetch(`${API_BASE_URL}${url}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(await parseErrorDetail(res));
return res.json();
},
patch: async <T>(url: string, data: unknown): Promise<T> => {
const res = await fetch(`${API_BASE_URL}${url}`, {
method: 'PATCH',
headers: getHeaders(),
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(await parseErrorDetail(res));
return res.json();
},
delete: async <T>(url: string): Promise<T> => {
const res = await fetch(`${API_BASE_URL}${url}`, {
method: 'DELETE',
headers: getHeaders(),
});
if (!res.ok) throw new Error(await parseErrorDetail(res));
return res.json();
},
};