feat(api): implement PATCH and DELETE routes for product management with error handling and logging
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
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 });
|
||||
}
|
||||
|
||||
console.log('[api/admin/product] PATCH product', productId);
|
||||
|
||||
// 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 });
|
||||
}
|
||||
|
||||
console.log('[api/admin/product] PATCH OK');
|
||||
|
||||
// 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 });
|
||||
}
|
||||
|
||||
console.log('[api/admin/product] tags PUT OK');
|
||||
|
||||
// 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();
|
||||
console.log('[api/admin/product] returning full product id:', product?.id);
|
||||
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 });
|
||||
}
|
||||
|
||||
console.log('[api/admin/product] DELETE product', productId);
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
console.log('[api/admin/product] DELETE OK');
|
||||
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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user