Antalya-Restaurant/scripts/generate-sitemap.cjs

67 lines
2.3 KiB
JavaScript

const fs = require("fs");
const path = require("path");
const { SitemapStream, streamToPromise } = require("sitemap");
const { pathToFileURL } = require("url");
const hostname = "http://localhost:3000"; // localhost for development
const addTrailingSlash = true; // ✅ Set this true if your Next.js uses trailingSlash: true
// Utility to format URLs based on config
const shouldAddSlash = (url) => {
if (url === "/") return false;
if (/\.[a-z0-9]{2,6}(\?.*)?$/i.test(url)) return false;
return true;
};
const formatUrl = (url) => {
if (!url.startsWith("/")) url = "/" + url;
if (addTrailingSlash && shouldAddSlash(url) && !url.endsWith("/")) {
return url + "/";
}
if (!addTrailingSlash && url.endsWith("/") && url !== "/") {
return url.slice(0, -1);
}
return url;
};
// ✅ Static pages
const staticLinks = [
{ url: '/', changefreq: 'daily', priority: 1.0 },
{ url: '/about/', changefreq: 'monthly', priority: 0.5 },
{ url: '/menu/', changefreq: 'weekly', priority: 0.6 },
{ url: '/gallery/', changefreq: 'weekly', priority: 0.6 },
{ url: '/contact/', changefreq: 'weekly', priority: 0.6 },
{ url: '/blog/', changefreq: 'weekly', priority: 0.6 },
];
// ✅ Dynamic blog posts (only URLs, no extra metadata needed beyond static format)
const blogPosts = [
{ slug: '/blog/the-art-of-turkish-tea' },
{ slug: '/blog/secrets-of-charcoal-grilling/' },
{ slug: '/blog/a-taste-of-sweet-legacy/' },
];
const blogLinks = blogPosts.map(p => ({ url: p.slug, changefreq: 'weekly', priority: 0.6 }));
const allLinks = [...staticLinks, ...blogLinks].map(l => ({ ...l, url: formatUrl(l.url) }));
async function generateSitemap() {
try {
const sitemap = new SitemapStream({ hostname });
const writeStream = fs.createWriteStream(path.resolve(__dirname, "../public/sitemap.xml"));
sitemap.pipe(writeStream);
console.log('📦 Writing URLs to sitemap:');
allLinks.forEach(link => {
console.log(' -', hostname + link.url);
sitemap.write(link);
});
sitemap.end();
await streamToPromise(sitemap);
console.log('✅ sitemap.xml created successfully!');
} catch (error) {
console.error('❌ Error creating sitemap.xml:', error);
}
}
generateSitemap();