From 1bb6447141551967dfde785df2fca79048ba62a5 Mon Sep 17 00:00:00 2001 From: Vasily Zubarev Date: Fri, 4 Apr 2025 13:49:51 +0200 Subject: [PATCH] feat: move currency converter to server --- app/api/currency/route.ts | 66 +++++++++++++++++++++++++++ components/forms/convert-currency.tsx | 22 ++++++++- lib/currency-scraper.ts | 57 ----------------------- 3 files changed, 87 insertions(+), 58 deletions(-) create mode 100644 app/api/currency/route.ts delete mode 100644 lib/currency-scraper.ts diff --git a/app/api/currency/route.ts b/app/api/currency/route.ts new file mode 100644 index 0000000..a1af942 --- /dev/null +++ b/app/api/currency/route.ts @@ -0,0 +1,66 @@ +import { format } from "date-fns" +import { NextRequest, NextResponse } from "next/server" + +type HistoricRate = { + currency: string + rate: number + inverse: number +} + +export async function GET(request: NextRequest) { + try { + const searchParams = request.nextUrl.searchParams + const fromCurrency = searchParams.get("from") + const toCurrency = searchParams.get("to") + const dateParam = searchParams.get("date") + + if (!fromCurrency || !toCurrency || !dateParam) { + return NextResponse.json({ error: "Missing required parameters: from, to, date" }, { status: 400 }) + } + + const date = new Date(dateParam) + if (isNaN(date.getTime())) { + return NextResponse.json({ error: "Invalid date format" }, { status: 400 }) + } + + const formattedDate = format(date, "yyyy-MM-dd") + const url = `https://www.xe.com/currencytables/?from=${fromCurrency}&date=${formattedDate}` + + const response = await fetch(url) + + if (!response.ok) { + return NextResponse.json( + { error: `Failed to fetch currency data: ${response.status}` }, + { status: response.status } + ) + } + + const html = await response.text() + + // Extract the JSON data from the __NEXT_DATA__ script tag + const scriptTagRegex = /