From deb82d38b882062a7c7f575d4b869d219fc10f34 Mon Sep 17 00:00:00 2001 From: Yifei Hu Date: Thu, 11 Jul 2024 12:33:19 +0800 Subject: [PATCH] now can load local detail news --- ui/app/api/news/[id]/router.ts | 12 ++++++++++++ ui/app/news/[id]/page.tsx | 2 +- ui/lib/fetchNewsData.ts | 15 ++++++++++----- 3 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 ui/app/api/news/[id]/router.ts diff --git a/ui/app/api/news/[id]/router.ts b/ui/app/api/news/[id]/router.ts new file mode 100644 index 0000000..02d52a2 --- /dev/null +++ b/ui/app/api/news/[id]/router.ts @@ -0,0 +1,12 @@ +import { NextResponse } from "next/server"; +import { fetchNewsData } from "../../../../lib/fetchNewsData"; + +export async function GET(request: Request, { params }: { params: { id: string } }) { + const newsData = await fetchNewsData(params.id); + + if (!newsData) { + return NextResponse.json({ error: "News not found" }, { status: 404 }); + } + + return NextResponse.json(newsData); +} diff --git a/ui/app/news/[id]/page.tsx b/ui/app/news/[id]/page.tsx index b9b0a3c..a98b18f 100644 --- a/ui/app/news/[id]/page.tsx +++ b/ui/app/news/[id]/page.tsx @@ -5,7 +5,7 @@ export default async function NewsPage({ params }: { params: { id: string } }) { const newsData = await fetchNewsData(params.id); if (!newsData) { - return
News not found
; + return
News not found or failed to load
; } return ; diff --git a/ui/lib/fetchNewsData.ts b/ui/lib/fetchNewsData.ts index b5568f8..9fd902a 100644 --- a/ui/lib/fetchNewsData.ts +++ b/ui/lib/fetchNewsData.ts @@ -1,9 +1,14 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + export async function fetchNewsData(id: string) { - const response = await fetch( - `https://raw.githubusercontent.com/newspedia-crew/newspedia-web/intern-change/public/data/${id}.json`, - ); - if (!response.ok) { + try { + const dataDirectory = path.join(process.cwd(), "public", "data"); + const filePath = path.join(dataDirectory, `${id}.json`); + const fileContents = await fs.readFile(filePath, "utf8"); + return JSON.parse(fileContents); + } catch (error) { + console.error("Error reading news data:", error); return null; } - return response.json(); }