combine the lib/fetnewsdata.tsx to app/api/news/[id]/page.tsx

This commit is contained in:
Yifei Hu 2024-07-12 12:48:33 +08:00
parent e8e90d84cc
commit 07a66489d1
2 changed files with 19 additions and 7 deletions

View file

@ -1,12 +1,17 @@
import { NextResponse } from "next/server";
import { fetchNewsData } from "../../../../lib/fetchNewsData";
import fs from "node:fs/promises";
import path from "node:path";
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 });
}
try {
const dataDirectory = path.join(process.cwd(), "public", "data");
const filePath = path.join(dataDirectory, `${params.id}.json`);
const fileContents = await fs.readFile(filePath, "utf8");
const newsData = JSON.parse(fileContents);
return NextResponse.json(newsData);
} catch (error) {
console.error("Error reading news data:", error);
return NextResponse.json({ error: "News not found" }, { status: 404 });
}
}

View file

@ -1,8 +1,15 @@
import { fetchNewsData } from "../../../lib/fetchNewsData";
import NewsDetail from "../../../components/NewsDetail";
async function getNewsData(id: string) {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/news/${id}`, { next: { revalidate: 60 } });
if (!res.ok) {
throw new Error("Failed to fetch news");
}
return res.json();
}
export default async function NewsPage({ params }: { params: { id: string } }) {
const newsData = await fetchNewsData(params.id);
const newsData = await getNewsData(params.id);
if (!newsData) {
return <div className="text-center text-red-500">News not found or failed to load</div>;