|
| 1 | +import { NextResponse } from 'next/server'; |
| 2 | +import { LingoDotDevEngine } from '@lingo.dev/_sdk'; |
| 3 | + |
| 4 | +// Fallback dictionary for demo purposes when SDK fails |
| 5 | +const FALLBACKS: Record<string, Record<string, string>> = { |
| 6 | + 'en-es': { |
| 7 | + 'Hello, I have a problem with my order.': 'Hola, tengo un problema con mi pedido.', |
| 8 | + 'How can I help you today?': '¿Cómo puedo ayudarte hoy?', |
| 9 | + }, |
| 10 | + 'es-en': { |
| 11 | + 'Hola, tengo un problema con mi pedido.': 'Hello, I have a problem with my order.', |
| 12 | + 'Gracias por la ayuda.': 'Thanks for the help.', |
| 13 | + 'Entendido.': 'Understood.', |
| 14 | + '¿Puede explicar eso de nuevo?': 'Can you explain that again?', |
| 15 | + 'Esperaré su respuesta.': 'I will wait for your response.', |
| 16 | + }, |
| 17 | + 'de-en': { |
| 18 | + 'Funktioniert dieses Produkt auf dem Mac?': 'Does this product work on Mac?', |
| 19 | + 'Danke für die Hilfe.': 'Thanks for the help.', |
| 20 | + 'Können Sie das wiederholen?': 'Can you repeat that?', |
| 21 | + 'Verstanden.': 'Understood.', |
| 22 | + 'Ich werde warten.': 'I will wait.', |
| 23 | + }, |
| 24 | + 'ja-en': { |
| 25 | + 'ありがとうございます。': 'Thank you.', |
| 26 | + 'もう一度説明していただけますか?': 'Could you explain that again?', |
| 27 | + '分かりました。': 'I understand.', |
| 28 | + 'お待ちしております。': 'I will be waiting.', |
| 29 | + }, |
| 30 | + 'fr-en': { |
| 31 | + 'Merci pour l\'aide.': 'Thanks for the help.', |
| 32 | + 'Pouvez-vous répéter ?': 'Can you repeat that?', |
| 33 | + 'Compris.': 'Understood.', |
| 34 | + 'J\'attendrai.': 'I will wait.', |
| 35 | + }, |
| 36 | +}; |
| 37 | + |
| 38 | +export async function POST(request: Request) { |
| 39 | + const { text, sourceLocale, targetLocale } = await request.json(); |
| 40 | + |
| 41 | + const apiKey = process.env.LINGO_API_KEY; |
| 42 | + |
| 43 | + // Try SDK translation first |
| 44 | + if (apiKey) { |
| 45 | + try { |
| 46 | + const engine = new LingoDotDevEngine({ apiKey }); |
| 47 | + const translatedText = await engine.localizeText(text, { |
| 48 | + sourceLocale, |
| 49 | + targetLocale, |
| 50 | + }); |
| 51 | + return NextResponse.json({ translatedText }); |
| 52 | + } catch (error) { |
| 53 | + console.error('Lingo SDK Error:', error); |
| 54 | + // Fall through to fallback |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // Fallback Logic (used if no API key OR if SDK execution failed) |
| 59 | + const key = `${sourceLocale}-${targetLocale}`; |
| 60 | + const exactMatch = FALLBACKS[key]?.[text]; |
| 61 | + |
| 62 | + if (exactMatch) { |
| 63 | + return NextResponse.json({ translatedText: exactMatch }); |
| 64 | + } |
| 65 | + |
| 66 | + // Pseudo-translation fallback if no match |
| 67 | + return NextResponse.json({ |
| 68 | + translatedText: `[${targetLocale.toUpperCase()}] ${text}` |
| 69 | + }); |
| 70 | +} |
0 commit comments