← back to Wine Finder Next
app/api/ingest/winecom/route.ts
82 lines
// app/api/ingest/winecom/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { wines } = body;
if (!Array.isArray(wines)) {
return NextResponse.json({ error: 'wines array required' }, { status: 400 });
}
const db = getDb();
const insertWine = db.prepare(`
INSERT OR REPLACE INTO wines (
name, varietal, vintage, region, country,
alc_percent, tasting_notes, winecom_id,
image_url, critic_scores
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const insertPrice = db.prepare(`
INSERT INTO wine_prices (wine_id, vendor, price, collected_at, product_id)
VALUES (?, 'winecom', ?, datetime('now'), ?)
`);
let processed = 0;
let errors = 0;
for (const wine of wines) {
try {
// Insert or update wine
const wineResult = insertWine.run(
wine.name || '',
wine.varietal || null,
wine.vintage || null,
wine.region || null,
wine.country || null,
wine.alc_percent || null,
wine.tasting_notes || null,
wine.winecom_id || null,
wine.image_url || null,
wine.critic_scores ? JSON.stringify(wine.critic_scores) : null
);
// Insert price if provided
if (wine.price && wine.winecom_id) {
insertPrice.run(
wineResult.lastInsertRowid,
wine.price,
wine.winecom_id
);
}
processed++;
} catch (error) {
console.error('Error processing wine:', error);
errors++;
}
}
return NextResponse.json({
success: true,
processed,
errors,
message: `Processed ${processed} wines from Wine.com`
});
} catch (error) {
console.error('Wine.com ingest error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function GET() {
// Health check endpoint
return NextResponse.json({
status: 'Wine.com ingest endpoint ready',
timestamp: new Date().toISOString()
});
}