Files
recipe-app/frontend/app/api/admin/product/[id]/route.ts
T
Nils-Johan Gynther 1ae9b336d8 feat(api): implement bulk categorization and suggestion endpoints with authentication
refactor(actions): remove unused imports and console logs from product actions
refactor(EditProductForm): update category suggestion logic to use new API endpoint
2026-04-19 19:04:04 +02:00

124 lines
4.1 KiB
TypeScript

import { auth } from '../../../../../auth';
const API_BASE = process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
async function getAuthHeaders(): Promise<Record<string, string>> {
const session = await auth();
if (!session?.accessToken) {
return {};
}
return { Authorization: `Bearer ${session.accessToken}` };
}
// PATCH /api/admin/product/[id]
// Body: { name, canonicalName, category, subcategory, brand, categoryId, tags }
export async function PATCH(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const { id } = await params;
const productId = Number(id);
if (!productId) return Response.json({ error: 'Invalid id' }, { status: 400 });
const body = await req.json();
const { name, canonicalName, category, subcategory, brand, categoryId, tags } = body;
if (!name || typeof name !== 'string' || !name.trim()) {
return Response.json({ error: 'Namn får inte vara tomt.' }, { status: 400 });
}
const authHeaders = await getAuthHeaders();
if (!authHeaders.Authorization) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
// 1. Update product fields
const patchRes = await fetch(`${API_BASE}/api/products/${productId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...authHeaders },
body: JSON.stringify({
name: name.trim(),
canonicalName: canonicalName?.trim() || undefined,
category: category?.trim() || null,
subcategory: subcategory?.trim() || null,
brand: brand?.trim() || null,
categoryId: categoryId ?? null,
}),
});
if (!patchRes.ok) {
const text = await patchRes.text();
console.error('[api/admin/product] PATCH failed:', patchRes.status, text);
return Response.json({ error: `Kunde inte uppdatera produkt: ${text}` }, { status: patchRes.status });
}
// 2. Update tags
const tagsRes = await fetch(`${API_BASE}/api/products/${productId}/tags`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...authHeaders },
body: JSON.stringify({ tags: tags ?? [] }),
});
if (!tagsRes.ok) {
const text = await tagsRes.text();
console.error('[api/admin/product] tags PUT failed:', tagsRes.status, text);
return Response.json({ error: `Kunde inte uppdatera taggar: ${text}` }, { status: tagsRes.status });
}
// 3. Return the complete updated product
const fullRes = await fetch(`${API_BASE}/api/products/${productId}`, {
headers: authHeaders,
});
if (!fullRes.ok) {
return Response.json({ error: 'Produkt uppdaterad men kunde inte hämtas' }, { status: 500 });
}
const product = await fullRes.json();
return Response.json(product);
} catch (err) {
console.error('[api/admin/product] PATCH error:', err);
return Response.json(
{ error: err instanceof Error ? err.message : 'Unknown error' },
{ status: 500 },
);
}
}
// DELETE /api/admin/product/[id]
export async function DELETE(
_req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const { id } = await params;
const productId = Number(id);
if (!productId) return Response.json({ error: 'Invalid id' }, { status: 400 });
const authHeaders = await getAuthHeaders();
if (!authHeaders.Authorization) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const res = await fetch(`${API_BASE}/api/products/${productId}`, {
method: 'DELETE',
headers: authHeaders,
});
if (!res.ok) {
const text = await res.text();
console.error('[api/admin/product] DELETE failed:', res.status, text);
return Response.json({ error: `Kunde inte ta bort produkt: ${text}` }, { status: res.status });
}
return new Response(null, { status: 204 });
} catch (err) {
console.error('[api/admin/product] DELETE error:', err);
return Response.json(
{ error: err instanceof Error ? err.message : 'Unknown error' },
{ status: 500 },
);
}
}