-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate-sitemap.js
120 lines (103 loc) · 2.57 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
require('dotenv').config()
const { SitemapStream, streamToPromise } = require('sitemap')
const { createWriteStream } = require('fs')
const { request, gql } = require('graphql-request')
const { pipeline } = require('stream')
const { promisify } = require('util')
const GRAPHQL_ENDPOINT = process.env.NEXT_PUBLIC_GRAPHQL_HOST
const token = process.env.NEXT_PUBLIC_GRAPHQL_TOKEN || ''
const GET_ALL_PAGES = gql`
query getAllPages {
genres(pagination: { limit: 10000 }) {
data {
attributes {
slug
updatedAt
}
}
}
countries(pagination: { limit: 10000 }) {
data {
attributes {
slug
updatedAt
}
}
}
albums(pagination: { limit: 10000 }) {
data {
attributes {
slug
updatedAt
released
}
}
}
}
`
async function fetchPages() {
try {
const data = await request(
GRAPHQL_ENDPOINT,
GET_ALL_PAGES,
{},
{
authorization: token ? `Bearer ${token}` : ''
}
)
return data
} catch (error) {
console.error('Erro ao buscar as páginas:', error)
return []
}
}
async function generateSitemap() {
const { albums, countries, genres } = await fetchPages()
const years = []
const sitemap = new SitemapStream({ hostname: 'https://bandas1album.com.br' })
const writeStream = createWriteStream('public/sitemap.xml')
const pipelineAsync = promisify(pipeline)
albums?.data.map((album) => {
sitemap.write({
url: `/album/${album.attributes?.slug}`,
changefreq: 'weekly',
lastmod: new Date(album.attributes?.updatedAt)
})
})
albums?.data.map((album) => {
const year = album.attributes.released.split('-')[0]
if (!years.includes(year)) {
years.push(year)
}
})
countries?.data.map((country) => {
sitemap.write({
url: `/pais/${country.attributes?.slug}`,
changefreq: 'weekly',
lastmod: new Date(country.attributes?.updatedAt)
})
})
genres?.data.map((genre) => {
sitemap.write({
url: `/genero/${genre.attributes?.slug}`,
changefreq: 'weekly',
lastmod: new Date(genre.attributes?.updatedAt)
})
})
years?.map((year) => {
sitemap.write({
url: `/ano/${year}`,
changefreq: 'weekly',
lastmod: new Date()
})
})
sitemap.end()
try {
await pipelineAsync(sitemap, writeStream)
console.log('Sitemap gerado com sucesso!')
} catch (err) {
console.error('Erro ao gerar sitemap:', err)
}
}
generateSitemap()
module.exports.generateSitemap = generateSitemap