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 ` ${pages.map(page => ` ${baseURL}/${page} 0.75 `).join('\n')} ${locations.map(loc => ` ${baseURL}/location/${loc.country.slug}/${loc.slug} 1 ${formatDate(loc.updated, 'DATETIME')} weekly `).join('\n') } ` } // 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) }