Creating site map in sapper

OptionsOptionsOptions

Creating a sitemap.xml.js file in svelte / sapper

Code
// sitemap.xml.js
import fetch from 'node-fetch';

function getPath(title, id) {
    if (!id) return '/';

    const formatted_title = title
        .replace(/(\s|\?|\,|\&|\/)+/g, '-')
        .toLowerCase();
    return '/' + formatted_title + '-' + id;
}

const render = (notes) => `<?xml version="1.0" encoding="UTF-8" ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    ${notes
        .map(function(note) {
            return `<url>
                 <loc>${'https://app.codernotes.io/notes' + getPath(note.title, note.id)}</loc>
            </url>`;
        })
        .join('')}
    </urlset>
`;

export async function get(req, res) {
		// The important thing for you to know about this is that
		// this get request returns a list of stringified json objects.
    let algolia_notes = await fetch(
        process.env.NODE_ENV === 'development'
            ? `http://localhost:3000/algolia.json`
            : 'https://app.codernotes.io/algolia.json',
        {
            method: 'get',
            headers: {
                'Content-Type': 'application/json',
            },
        }
    );
    const result = await algolia_notes.json();
    res.setHeader('Content-Type', 'application/xml');
    const xml = render(result);
    res.end(xml);
}
Tags
None
Last updated by Kevcon80 on March 27 2020, at 8:47:40 PM