All files / owid-grapher/baker sitemap.ts

37.21% Statements 32/86
100% Branches 0/0
0% Functions 0/2
37.21% Lines 32/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                     1x 1x                                                                                         1x
import { Post } from "../db/model/Post"
import { Chart } from "../db/model/Chart"
import { BAKED_BASE_URL, BAKED_GRAPHER_URL } from "../settings/serverSettings"
import moment from "moment"
import * as db from "../db/db"
import { countries } from "../clientUtils/countries"
import urljoin from "url-join"
import { countryProfileSpecs } from "../site/countryProfileProjects"
 
interface SitemapUrl {
    loc: string
    lastmod?: string
}
 
const xmlify = (url: SitemapUrl) => {
    if (url.lastmod)
        return `    <url>
        <loc>${url.loc}</loc>
        <lastmod>${url.lastmod}</lastmod>
    </url>`

    return `    <url>
        <loc>${url.loc}</loc>
    </url>`
}
 
export const makeSitemap = async () => {
    const posts = (await db
        .knexTable(Post.table)
        .where({ status: "publish" })
        .select("slug", "updated_at")) as { slug: string; updated_at: Date }[]
    const charts = (await db
        .knexTable(Chart.table)
        .select(db.knexRaw(`updatedAt, config->>"$.slug" AS slug`))
        .whereRaw('config->"$.isPublished" = true')) as {
        updatedAt: Date
        slug: string
    }[]

    let urls = countries.map((c) => ({
        loc: urljoin(BAKED_BASE_URL, "country", c.slug),
    })) as SitemapUrl[]

    urls = urls
        .concat(
            ...countryProfileSpecs.map((spec) => {
                return countries.map((c) => ({
                    loc: urljoin(BAKED_BASE_URL, spec.rootPath, c.slug),
                }))
            })
        )
        .concat(
            posts.map((p) => ({
                loc: urljoin(BAKED_BASE_URL, p.slug),
                lastmod: moment(p.updated_at).format("YYYY-MM-DD"),
            }))
        )
        .concat(
            charts.map((c) => ({
                loc: urljoin(BAKED_GRAPHER_URL, c.slug),
                lastmod: moment(c.updatedAt).format("YYYY-MM-DD"),
            }))
        ) as SitemapUrl[]

    const sitemap = `<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map((url) => xmlify(url)).join("\n")}
</urlset>`

    return sitemap
}