All checks were successful
continuous-integration/drone/push Build is passing
73 lines
2.5 KiB
JavaScript
73 lines
2.5 KiB
JavaScript
const fs = require('fs')
|
|
const fetch = require('node-fetch')
|
|
import { apiEndpoints } from 'utils/store'
|
|
import { formatDate } from 'utils/functions'
|
|
|
|
|
|
// Variables
|
|
let baseURL
|
|
const pages = ['']
|
|
|
|
// Get routes and push it to array
|
|
const routesExclude = ['sitemap', 'index', 'location', 'viewer']
|
|
fs.readdirSync('./src/routes').forEach(file => {
|
|
const filename = file.split('.')[0]
|
|
if (!file.startsWith('.') && !filename.startsWith('_') && routesExclude.indexOf(filename) === -1) {
|
|
pages.push(filename)
|
|
}
|
|
})
|
|
|
|
|
|
// Render function
|
|
const render = (pages, 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>${baseURL}/${page}</loc>
|
|
<priority>0.75</priority>
|
|
</url>`).join('\n')}
|
|
|
|
${locations.map(loc => `
|
|
<url>
|
|
<loc>${baseURL}/location/${loc.country.slug}/${loc.slug}</loc>
|
|
<priority>1</priority>
|
|
<lastmod>${formatDate(loc.updated, 'DATETIME')}</lastmod>
|
|
<changefreq>weekly</changefreq>
|
|
</url>`).join('\n')
|
|
}
|
|
</urlset>`
|
|
}
|
|
|
|
// Get function
|
|
export async function get (req, res, next) {
|
|
// Define base url from request
|
|
baseURL = `https://${req.headers.host}`
|
|
|
|
// Get locations
|
|
const locationsReq = await fetch(`${apiEndpoints.rest}/items/locations?fields=slug,country.slug,modified_on&status=published`)
|
|
const locationsData = await locationsReq.json()
|
|
const locations = locationsData.data
|
|
|
|
// Add last modified date to each location from its last photo
|
|
const updatedLocations = locations.map(async (location, i) => {
|
|
const latestPhotoReq = await fetch(`${apiEndpoints.rest}/items/photos?fields=created_on&limit=1&sort=created_on&status=published&filter[location.slug][rlike]=%${location.slug}`)
|
|
const latestPhotoData = await latestPhotoReq.json()
|
|
const latestPhoto = latestPhotoData.data[0]
|
|
location.updated = latestPhoto ? latestPhoto.created_on : location.modified_on
|
|
return location
|
|
})
|
|
await Promise.all(updatedLocations)
|
|
|
|
// Set headers
|
|
res.setHeader('Cache-Control', 'max-age=0, s-max-age=600') // 10 minutes
|
|
res.setHeader('Content-Type', 'application/rss+xml')
|
|
|
|
// Render sitemap
|
|
const sitemap = render(pages, locations)
|
|
res.end(sitemap)
|
|
} |