Add sitemap route
Adds routes and locations to sitemap.xml file
This commit is contained in:
55
src/routes/sitemap.xml.js
Normal file
55
src/routes/sitemap.xml.js
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
const fs = require('fs')
|
||||||
|
const fetch = require('node-fetch')
|
||||||
|
import { apiEndpoints } from '../utils/store'
|
||||||
|
|
||||||
|
|
||||||
|
// Variables
|
||||||
|
let BASE_URL
|
||||||
|
const pages = ['']
|
||||||
|
|
||||||
|
// Get each route
|
||||||
|
fs.readdirSync('./src/routes').forEach(file => {
|
||||||
|
const filename = file.split('.')[0]
|
||||||
|
if (!file.startsWith('.') && !filename.startsWith('_') && ['sitemap', 'index', 'location', 'viewer'].indexOf(filename) === -1) {
|
||||||
|
pages.push(filename)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Render function
|
||||||
|
const render = (pages, locations) => {
|
||||||
|
console.log(locations)
|
||||||
|
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8" ?>
|
||||||
|
<urlset
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||||
|
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
|
||||||
|
>
|
||||||
|
${pages.map(page => `
|
||||||
|
<url>
|
||||||
|
<loc>${BASE_URL}/${page}</loc>
|
||||||
|
<priority>0.75</priority>
|
||||||
|
</url>`).join('\n')}
|
||||||
|
|
||||||
|
${locations.map(loc => `
|
||||||
|
<url>
|
||||||
|
<loc>${BASE_URL}/location/${loc.country.slug}/${loc.slug}</loc>
|
||||||
|
<priority>1</priority>
|
||||||
|
</url>`).join('\n')}
|
||||||
|
</urlset>`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get function
|
||||||
|
export async function get (req, res, next) {
|
||||||
|
BASE_URL = `http${(req.httpVersion >= 2) ? 's' : ''}://${req.headers.host}`
|
||||||
|
|
||||||
|
// Get locations
|
||||||
|
const locationsReq = await fetch(`${apiEndpoints.rest}/items/locations?fields=slug,country.slug`)
|
||||||
|
const locations = await locationsReq.json()
|
||||||
|
|
||||||
|
res.setHeader('Cache-Control', `max-age=0, s-max-age=${600}`) // 10 minutes
|
||||||
|
res.setHeader('Content-Type', 'application/rss+xml')
|
||||||
|
|
||||||
|
const sitemap = render(pages, locations.data)
|
||||||
|
res.end(sitemap)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user