import { getAllPosts } from "../external/cms"
import fs from "fs"
import prettier from "prettier"
import config from './config'
export const generateSitemap = async () => {
const getDate = new Date().toISOString()
const staticPaths = fs.readdirSync("pages", {withFileTypes: true})
.filter((staticPage) => {
if(staticPage.isFile()) {
return ![
"api",
"_app.js",
"_document.js",
"404.js",
"sitemap.xml.js",
"index.js"
].includes(staticPage.name);
}
})
.map((staticPagePath) => {
console.log(staticPagePath)
return `${config.siteURL}/${staticPagePath.name}`;
}
);
const postData = await getAllPosts()
const postList = []
postData.data.forEach(post => postList.push({slug: post.attributes.Slug, updatedAt: post.attributes.updatedAt}))
console.log(postList)
const formatted = sitemap => prettier.format(sitemap, { parser: "html" });
const pageListMap = staticPaths.map(page => {
return `
${page}
${getDate}
1
`
}).join("")
const postListSiteMap = postList.map(post => {
return `
${`${config.siteURL}/news/${post.slug}`}
${post.updatedAt}
0.5
`
})
.join("")
const generatedSitemap = `
${pageListMap}
${postListSiteMap}
`
console.log(generatedSitemap)
const formattedSitemap = [formatted(generatedSitemap)];
fs.writeFileSync("public/sitemap-posts.xml", generatedSitemap, "utf8")
}