feat: implement automated Whiskybase ID discovery

This commit is contained in:
2025-12-18 12:40:57 +01:00
parent 35c2443473
commit fef1c4a275
3 changed files with 211 additions and 3 deletions

View File

@@ -0,0 +1,69 @@
'use server';
/**
* Service to discover a Whiskybase ID for a given bottle.
* Uses SerpApi to search Google and extracts the ID from the first result.
*/
export async function discoverWhiskybaseId(bottle: {
name: string;
distillery?: string;
abv?: number;
age?: number;
}) {
const apiKey = process.env.SERPAPI_API_KEY;
if (!apiKey) {
return {
success: false,
error: 'SERPAPI_API_KEY ist nicht konfiguriert.'
};
}
try {
// Construct targeted search query
// site:whiskybase.com/whiskies/whisky ensures we only get product pages
const queryParts = [
'site:whiskybase.com/whiskies/whisky',
`"${bottle.distillery || ''}"`,
`"${bottle.name}"`,
bottle.abv ? `${bottle.abv}%` : '',
bottle.age ? `${bottle.age} year old` : ''
].filter(Boolean);
const q = queryParts.join(' ');
const url = `https://serpapi.com/search.json?q=${encodeURIComponent(q)}&api_key=${apiKey}&engine=google&num=5`;
const response = await fetch(url);
const data = await response.json();
if (!data.organic_results || data.organic_results.length === 0) {
return { success: false, error: 'Keine Treffer auf Whiskybase gefunden.' };
}
// Try to find the first result that looks like a valid product page
// Pattern matches: https://www.whiskybase.com/whiskies/whisky/12345/name
const wbRegex = /\/whisky\/(\d+)\//;
for (const result of data.organic_results) {
const link = result.link;
const match = link.match(wbRegex);
if (match && match[1]) {
return {
success: true,
id: match[1],
url: link,
title: result.title
};
}
}
return { success: false, error: 'Konnte keine gültige Whiskybase-ID im Suchergebnis finden.' };
} catch (error) {
console.error('Whiskybase Discovery Error:', error);
return {
success: false,
error: 'Fehler bei der Suche auf Whiskybase.'
};
}
}