combine the lib/fetnewsdata.tsx to app/api/news/[id]/page.tsx
This commit is contained in:
parent
e8e90d84cc
commit
07a66489d1
2 changed files with 19 additions and 7 deletions
|
@ -1,12 +1,17 @@
|
||||||
import { NextResponse } from "next/server";
|
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 } }) {
|
export async function GET(request: Request, { params }: { params: { id: string } }) {
|
||||||
const newsData = await fetchNewsData(params.id);
|
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);
|
||||||
|
|
||||||
if (!newsData) {
|
return NextResponse.json(newsData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error reading news data:", error);
|
||||||
return NextResponse.json({ error: "News not found" }, { status: 404 });
|
return NextResponse.json({ error: "News not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(newsData);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,15 @@
|
||||||
import { fetchNewsData } from "../../../lib/fetchNewsData";
|
|
||||||
import NewsDetail from "../../../components/NewsDetail";
|
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 } }) {
|
export default async function NewsPage({ params }: { params: { id: string } }) {
|
||||||
const newsData = await fetchNewsData(params.id);
|
const newsData = await getNewsData(params.id);
|
||||||
|
|
||||||
if (!newsData) {
|
if (!newsData) {
|
||||||
return <div className="text-center text-red-500">News not found or failed to load</div>;
|
return <div className="text-center text-red-500">News not found or failed to load</div>;
|
||||||
|
|
Loading…
Add table
Reference in a new issue