feat(api): add GET and POST endpoints for managing properties associated with a URL

This commit is contained in:
ryan 2025-06-19 14:49:19 +03:00
parent c03d01d9c8
commit ff0f252389

View file

@ -0,0 +1,86 @@
//property management API Route Handles GET (fetch properties) and POST (add property) for a URL
import { NextRequest, NextResponse } from 'next/server';
import { getSelectedProperties, addSelectedProperty, insertUrl } from '@/lib/database';
// GET /api/urls/[encodedUrl]/properties - Get selected properties 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('[API] Getting selected properties for URL:', url);
try {
const properties = await getSelectedProperties(url);
console.log('[API] Returning', properties.length, 'properties for URL:', url);
return NextResponse.json(properties, {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error('[API] Failed to fetch properties for URL:', url, error);
return NextResponse.json(
{
error: 'Failed to fetch properties',
details: error instanceof Error ? error.message : 'Unknown error',
url: url
},
{ status: 500 }
);
}
}
// POST /api/urls/[encodedUrl]/properties - Add a selected property to a URL
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 property: string = await request.json();
console.log('[API] Adding property', property, 'to URL', url);
// Validate property data
if (!property || typeof property !== 'string') {
console.log('[API] Validation error: Invalid property data');
return NextResponse.json(
{ error: 'Invalid property data', property: property },
{ status: 400 }
);
}
// Ensure URL exists in database
await insertUrl(url);
// Add the selected property
await addSelectedProperty(url, property);
console.log('[API] Successfully added property:', property);
return NextResponse.json(
{ message: 'Property added', property: property },
{ status: 200 }
);
} catch (error) {
console.log('[API] Error adding property:', error);
return NextResponse.json(
{
error: 'Failed to add property',
details: error instanceof Error ? error.message : 'Unknown error',
url: url
},
{ status: 500 }
);
}
}