-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-sitemap.js
56 lines (47 loc) · 1.75 KB
/
generate-sitemap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const { SitemapStream, streamToPromise } = require('sitemap');
const { createWriteStream } = require('fs');
const { resolve } = require('path');
const fetchBlogSlugs = async () => {
try {
const fetch = (await import('node-fetch')).default; // Dynamically import node-fetch
const response = await fetch('https://os5ae1ct.api.sanity.io/v2023-03-06/data/query/production', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `*[_type == "post"] {
slug
}`
}),
});
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error fetching blog slugs:', error);
return [];
}
};
const generateSitemap = async () => {
const sitemap = new SitemapStream({ hostname: 'https://www.developerhuzaifa.site' });
const staticPages = [
{ url: '/', changefreq: 'daily', priority: 1.0 },
{ url: '/blog', changefreq: 'monthly', priority: 0.9 },
{ url: '/connect', changefreq: 'monthly', priority: 0.7 },
{ url: '/projects', changefreq: 'monthly', priority: 0.6 },
// Add more static pages here
];
staticPages.forEach(page => sitemap.write(page));
const blogSlugs = await fetchBlogSlugs();
blogSlugs.forEach(blog => {
sitemap.write({ url: `/blog/${blog.slug.current}`, changefreq: 'weekly', priority: 0.8 });
});
sitemap.end();
const data = await streamToPromise(sitemap);
const sitemapPath = resolve(__dirname, 'public', 'sitemap.xml');
createWriteStream(sitemapPath).write(data);
};
generateSitemap().catch(console.error);