now can load local detail news

This commit is contained in:
Yifei Hu 2024-07-11 12:33:19 +08:00
parent 14294f8a14
commit deb82d38b8
3 changed files with 23 additions and 6 deletions

View file

@ -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);
}

View file

@ -5,7 +5,7 @@ export default async function NewsPage({ params }: { params: { id: string } }) {
const newsData = await fetchNewsData(params.id);
if (!newsData) {
return <div>News not found</div>;
return <div className="text-center text-red-500">News not found or failed to load</div>;
}
return <NewsDetail news={newsData} />;

View file

@ -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();
}