feat(api): implement GET and POST endpoints for managing items associated with a specific URL

This commit is contained in:
ryan 2025-06-19 14:48:08 +03:00
parent 4366678935
commit b90590f9a5

View file

@ -0,0 +1,95 @@
//Handles GET (fetch items) and POST (create/update item) for a specific URL
import { NextRequest, NextResponse } from 'next/server';
import { getItemsByUrl, insertItemByUrl, insertUrl } from '@/lib/database';
import { Item } from '@/types/database';
// GET /api/urls/[encodedUrl]/items - Fetch items for a URL
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ encodedUrl: string }> }
) {
// Await params before accessing properties
const resolvedParams = await params;
const url = decodeURIComponent(resolvedParams.encodedUrl);
console.log('[SERVER] Received request for URL:', url);
try {
const items = await getItemsByUrl(url);
console.log('[SERVER] Returning', items.length, 'items for URL:', url);
return NextResponse.json(items, {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error('[SERVER ERROR] Failed to fetch items for', url, ':', error);
return NextResponse.json(
{
error: 'Failed to fetch items',
details: error instanceof Error ? error.message : 'Unknown error',
url: url
},
{ status: 500 }
);
}
}
// POST /api/urls/[encodedUrl]/items - Create/update an item
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ encodedUrl: string }> }
) {
// Await params before accessing properties
const resolvedParams = await params;
const url = decodeURIComponent(resolvedParams.encodedUrl);
try {
const item: Item = await request.json();
const itemId = item.id;
// Request logging
console.log('[API] Received item request - URL:', url, 'Item ID:', itemId);
// Raw JSON logging
const rawJson = JSON.stringify(item);
console.log('[API] Raw request JSON:', rawJson);
// Validate item data
if (!item.id || typeof item.name !== 'string' || typeof item.description !== 'string') {
console.log('[API] Validation error: Invalid item data');
return NextResponse.json(
{ error: 'Invalid item data', item: item },
{ status: 400 }
);
}
// Ensure URL exists in database
await insertUrl(url);
// Insert/update the item
await insertItemByUrl(url, item);
console.log('[API] Successfully saved item ID:', itemId);
return NextResponse.json(item, {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.log('[API] Database error:', error);
return NextResponse.json(
{
error: 'Database error',
details: error instanceof Error ? error.message : 'Unknown error',
url: url
},
{ status: 400 }
);
}
}