refactor(sitemap): streamline sitemap generation by consolidating static and dynamic routes, improve error handling, and update XML response format
This commit is contained in:
@@ -9,52 +9,78 @@ interface ProjectsData {
|
|||||||
posts: Project[];
|
posts: Project[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SitemapRoute {
|
export const runtime = "nodejs"; // Force Node runtime
|
||||||
url: string;
|
|
||||||
lastModified: string;
|
const GHOST_API_URL = "http://big-bear-ghost:2368";
|
||||||
|
const GHOST_API_KEY = process.env.GHOST_API_KEY;
|
||||||
|
|
||||||
|
// Funktion, um die XML für die Sitemap zu generieren
|
||||||
|
function generateXml(sitemapRoutes: { url: string; lastModified: string }[]) {
|
||||||
|
const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||||
|
const urlsetOpen = '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';
|
||||||
|
const urlsetClose = '</urlset>';
|
||||||
|
|
||||||
|
const urlEntries = sitemapRoutes
|
||||||
|
.map(
|
||||||
|
(route) => `
|
||||||
|
<url>
|
||||||
|
<loc>${route.url}</loc>
|
||||||
|
<lastmod>${route.lastModified}</lastmod>
|
||||||
|
<changefreq>monthly</changefreq>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
</url>`
|
||||||
|
)
|
||||||
|
.join("");
|
||||||
|
|
||||||
|
return `${xmlHeader}${urlsetOpen}${urlEntries}${urlsetClose}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://dki.one";
|
|
||||||
|
|
||||||
const generateSitemap = async (): Promise<SitemapRoute[]> => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${baseUrl}/api/fetchAllProjects`, {
|
|
||||||
headers: {"Cache-Control": "no-cache"},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
console.error(`Failed to fetch projects: ${response.statusText}`);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectsData = (await response.json()) as ProjectsData;
|
|
||||||
|
|
||||||
// Dynamische Projekt-Routen generieren
|
|
||||||
const projectRoutes: SitemapRoute[] = projectsData.posts.map((project) => ({
|
|
||||||
url: `${baseUrl}/projects/${project.slug}`,
|
|
||||||
lastModified: project.updated_at
|
|
||||||
? new Date(project.updated_at).toISOString()
|
|
||||||
: new Date().toISOString(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
return [...projectRoutes];
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to generate sitemap:", error);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000";
|
||||||
|
|
||||||
|
// Statische Routen
|
||||||
|
const staticRoutes = [
|
||||||
|
{url: `${baseUrl}/`, lastModified: new Date().toISOString(), priority: 1, changeFreq: "weekly"},
|
||||||
|
{url: `${baseUrl}/legal-notice`, lastModified: new Date().toISOString(), priority: 0.5, changeFreq: "yearly"},
|
||||||
|
{url: `${baseUrl}/privacy-policy`, lastModified: new Date().toISOString(), priority: 0.5, changeFreq: "yearly"},
|
||||||
|
];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const sitemap = await generateSitemap();
|
const response = await fetch(
|
||||||
return NextResponse.json(sitemap, {
|
`${GHOST_API_URL}/ghost/api/content/posts/?key=${GHOST_API_KEY}&limit=all`
|
||||||
headers: {"Cache-Control": "no-cache"},
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to generate sitemap:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{error: "Failed to generate sitemap"},
|
|
||||||
{status: 500},
|
|
||||||
);
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error(`Failed to fetch posts: ${response.statusText}`);
|
||||||
|
return new NextResponse(generateXml(staticRoutes), {
|
||||||
|
headers: {"Content-Type": "application/xml"},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const projectsData = await response.json() as ProjectsData;
|
||||||
|
const projects = projectsData.posts;
|
||||||
|
|
||||||
|
// Dynamische Projekt-Routen generieren
|
||||||
|
const sitemapRoutes = projects.map((project) => {
|
||||||
|
const lastModified = project.updated_at || new Date().toISOString();
|
||||||
|
return {
|
||||||
|
url: `${baseUrl}/projects/${project.slug}`,
|
||||||
|
lastModified,
|
||||||
|
priority: 0.8,
|
||||||
|
changeFreq: "monthly",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const allRoutes = [...staticRoutes, ...sitemapRoutes];
|
||||||
|
|
||||||
|
// Rückgabe der Sitemap im XML-Format
|
||||||
|
return new NextResponse(generateXml(allRoutes), {
|
||||||
|
headers: {"Content-Type": "application/xml"},
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch posts from Ghost:", error);
|
||||||
|
// Rückgabe der statischen Routen, falls Fehler auftritt
|
||||||
|
return new NextResponse(generateXml(staticRoutes), {
|
||||||
|
headers: {"Content-Type": "application/xml"},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +1,26 @@
|
|||||||
import {NextResponse} from "next/server";
|
import {NextResponse} from "next/server";
|
||||||
|
|
||||||
interface SitemapRoute {
|
|
||||||
url: string;
|
|
||||||
lastModified: string;
|
|
||||||
changeFrequency?:
|
|
||||||
| "always"
|
|
||||||
| "hourly"
|
|
||||||
| "daily"
|
|
||||||
| "weekly"
|
|
||||||
| "monthly"
|
|
||||||
| "yearly"
|
|
||||||
| "never";
|
|
||||||
priority?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseUrl = "https://dki.one";
|
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000"; // Stelle sicher, dass die Base-URL korrekt ist
|
||||||
|
const apiUrl = `${baseUrl}/api/sitemap`; // Verwende die vollständige URL zur API
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${baseUrl}/api/sitemap`);
|
// Holt die Sitemap-Daten von der API
|
||||||
if (!response.ok) {
|
const res = await fetch(apiUrl);
|
||||||
console.error(`Failed to fetch dynamic routes: ${response.statusText}`);
|
|
||||||
|
if (!res.ok) {
|
||||||
|
console.error(`Failed to fetch sitemap: ${res.statusText}`);
|
||||||
|
return new NextResponse("Failed to fetch sitemap", {status: 500});
|
||||||
}
|
}
|
||||||
|
|
||||||
const dynamicRoutes = (await response.json()) as SitemapRoute[];
|
const xml = await res.text();
|
||||||
const sitemap = [...dynamicRoutes];
|
|
||||||
|
|
||||||
return new NextResponse(generateXml(sitemap), {
|
// Gibt die XML mit dem richtigen Content-Type zurück
|
||||||
|
return new NextResponse(xml, {
|
||||||
headers: {"Content-Type": "application/xml"},
|
headers: {"Content-Type": "application/xml"},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching dynamic routes, using fallback:", error);
|
console.error("Error fetching sitemap:", error);
|
||||||
return new NextResponse(generateXml([]), {
|
return new NextResponse("Error fetching sitemap", {status: 500});
|
||||||
headers: {"Content-Type": "application/xml"},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateXml(routes: SitemapRoute[]): string {
|
|
||||||
const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
|
|
||||||
const urlsetOpen = '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';
|
|
||||||
const urlsetClose = '</urlset>';
|
|
||||||
|
|
||||||
const urlEntries = routes
|
|
||||||
.map(
|
|
||||||
(route) => `
|
|
||||||
<url>
|
|
||||||
<loc>${route.url}</loc>
|
|
||||||
<lastmod>${route.lastModified}</lastmod>
|
|
||||||
${route.changeFrequency ? `<changefreq>${route.changeFrequency}</changefreq>` : ""}
|
|
||||||
${route.priority ? `<priority>${route.priority}</priority>` : ""}
|
|
||||||
</url>`
|
|
||||||
)
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
return `${xmlHeader}${urlsetOpen}${urlEntries}${urlsetClose}`;
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user