All files / owid-grapher/adminSiteServer mockSiteRouter.tsx

65.64% Statements 107/163
100% Branches 1/1
100% Functions 0/0
65.64% Lines 107/163

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 2421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x                   1x 1x 1x   1x 1x 1x               1x 1x 1x 1x                         1x                             1x 1x         1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 3x   1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x                                                                                                                                                              
import express, { Router } from "express"
import * as path from "path"
import {
    renderFrontPage,
    renderPageBySlug,
    renderChartsPage,
    renderMenuJson,
    renderSearchPage,
    renderDonatePage,
    entriesByYearPage,
    makeAtomFeed,
    pagePerVariable,
    feedbackPage,
    renderNotFoundPage,
    renderBlogByPageNum,
    renderCovidPage,
    countryProfileCountryPage,
    renderExplorerPage,
} from "../baker/siteRenderers"
import { grapherSlugToHtmlPage } from "../baker/GrapherBaker"
import {
    BAKED_BASE_URL,
    BAKED_GRAPHER_URL,
    WORDPRESS_DIR,
    BASE_DIR,
    BAKED_SITE_DIR,
} from "../settings/serverSettings"
 
import * as db from "../db/db"
import { expectInt, renderToHtmlPage } from "../serverUtils/serverUtil"
import {
    countryProfilePage,
    countriesIndexPage,
} from "../baker/countryProfiles"
import { makeSitemap } from "../baker/sitemap"
import { OldChart } from "../db/model/Chart"
import { countryProfileSpecs } from "../site/countryProfileProjects"
import { ExplorerAdminServer } from "../explorerAdminServer/ExplorerAdminServer"
import { grapherToSVG } from "../baker/GrapherImageBaker"
import { getVariableData } from "../db/model/Variable"
import { MultiEmbedderTestPage } from "../site/multiembedder/MultiEmbedderTestPage"
import { bakeEmbedSnippet } from "../site/webpackUtils"
import { JsonError } from "../clientUtils/owidTypes"
import { GIT_CMS_DIR } from "../gitCms/GitCmsConstants"
import { isWordpressAPIEnabled } from "../db/wpdb"
import { EXPLORERS_ROUTE_FOLDER } from "../explorer/ExplorerConstants"
import { getExplorerRedirectForPath } from "../explorerAdminServer/ExplorerRedirects"
import { explorerUrlMigrationsById } from "../explorer/urlMigrations/ExplorerUrlMigrations"
 
require("express-async-errors")
 
// todo: switch to an object literal where the key is the path and the value is the request handler? easier to test, reflect on, and manipulate
const mockSiteRouter = Router()
 
mockSiteRouter.use(express.urlencoded({ extended: true }))
mockSiteRouter.use(express.json())
 
mockSiteRouter.get("/sitemap.xml", async (req, res) =>
    res.send(await makeSitemap())
)
 
mockSiteRouter.get("/atom.xml", async (req, res) =>
    res.send(await makeAtomFeed())
)
 
mockSiteRouter.get("/entries-by-year", async (req, res) =>
    res.send(await entriesByYearPage())
)
 
mockSiteRouter.get(`/entries-by-year/:year`, async (req, res) =>
    res.send(await entriesByYearPage(parseInt(req.params.year)))
)
 
mockSiteRouter.get(
    "/grapher/data/variables/:variableIds.json",
    async (req, res) => {
        res.set("Access-Control-Allow-Origin", "*")
        res.json(
            await getVariableData(
                (req.params.variableIds as string)
                    .split("+")
                    .map((v) => expectInt(v))
            )
        )
    }
)
 
mockSiteRouter.get("/grapher/embedCharts.js", async (req, res) =>
    res.send(bakeEmbedSnippet(BAKED_BASE_URL))
)
 
mockSiteRouter.get("/grapher/latest", async (req, res) => {
    const latestRows = await db.queryMysql(
        `SELECT config->>"$.slug" AS slug FROM charts where starred=1`
    )
    if (latestRows.length)
        res.redirect(`${BAKED_GRAPHER_URL}/${latestRows[0].slug}`)
    else throw new JsonError("No latest chart", 404)
})
 
const explorerAdminServer = new ExplorerAdminServer(GIT_CMS_DIR)
 
mockSiteRouter.get(`/${EXPLORERS_ROUTE_FOLDER}/:slug`, async (req, res) => {
    res.set("Access-Control-Allow-Origin", "*")
    const explorers = await explorerAdminServer.getAllPublishedExplorers()
    const explorerProgram = explorers.find(
        (program) => program.slug === req.params.slug
    )
    if (explorerProgram) res.send(await renderExplorerPage(explorerProgram))
    else
        throw new JsonError(
            "A published explorer with that slug was not found",
            404
        )
})
mockSiteRouter.get("/*", async (req, res, next) => {
    const explorerRedirect = getExplorerRedirectForPath(req.path)
    // If no explorer redirect exists, continue to next express handler
    if (!explorerRedirect) return next()

    const { migrationId, baseQueryStr } = explorerRedirect
    const { explorerSlug } = explorerUrlMigrationsById[migrationId]
    const program = await explorerAdminServer.getExplorerFromSlug(explorerSlug)
    res.send(
        await renderExplorerPage(program, {
            explorerUrlMigrationId: migrationId,
            baseQueryStr,
        })
    )
})
 
mockSiteRouter.get("/grapher/:slug", async (req, res) => {
    // XXX add dev-prod parity for this
    res.set("Access-Control-Allow-Origin", "*")
    res.send(await grapherSlugToHtmlPage(req.params.slug))
})
 
mockSiteRouter.get("/", async (req, res) => res.send(await renderFrontPage()))
 
mockSiteRouter.get("/donate", async (req, res) =>
    res.send(await renderDonatePage())
)
 
mockSiteRouter.get("/charts", async (req, res) =>
    res.send(await renderChartsPage())
)
 
countryProfileSpecs.forEach((spec) =>
    mockSiteRouter.get(`/${spec.rootPath}/:countrySlug`, async (req, res) =>
        res.send(await countryProfileCountryPage(spec, req.params.countrySlug))
    )
)
 
// Route only available on the dev server
mockSiteRouter.get("/covid", async (req, res) =>
    res.send(await renderCovidPage())
)
 
mockSiteRouter.get("/search", async (req, res) =>
    res.send(await renderSearchPage())
)
 
mockSiteRouter.get("/blog", async (req, res) =>
    res.send(await renderBlogByPageNum(1))
)
 
mockSiteRouter.get("/blog/page/:pageno", async (req, res) => {
    const pagenum = parseInt(req.params.pageno, 10)
    if (!isNaN(pagenum))
        res.send(await renderBlogByPageNum(isNaN(pagenum) ? 1 : pagenum))
    else throw new Error("invalid page number")
})
 
mockSiteRouter.get("/headerMenu.json", async (req, res) => {
    if (!isWordpressAPIEnabled) {
        res.status(404).send(await renderNotFoundPage())
        return
    }
    res.send(await renderMenuJson())
})
 
mockSiteRouter.use(
    // Not all /app/uploads paths are going through formatting
    // and being rewritten as /uploads. E.g. blog index images paths
    // on front page.
    ["/uploads", "/app/uploads"],
    express.static(path.join(WORDPRESS_DIR, "web/app/uploads"), {
        fallthrough: false,
    })
)
 
mockSiteRouter.use(
    "/exports",
    express.static(path.join(BAKED_SITE_DIR, "exports"))
)
 
mockSiteRouter.use("/grapher/exports/:slug.svg", async (req, res) => {
    const grapher = await OldChart.getBySlug(req.params.slug)
    const vardata = await grapher.getVariableData()
    res.setHeader("Content-Type", "image/svg+xml")
    res.send(await grapherToSVG(grapher.config, vardata))
})
 
mockSiteRouter.use("/", express.static(path.join(BASE_DIR, "public")))
 
mockSiteRouter.get("/indicator/:variableId/:country", async (req, res) => {
    const variableId = expectInt(req.params.variableId)
    res.send(await pagePerVariable(variableId, req.params.country))
})
 
mockSiteRouter.get("/countries", async (req, res) =>
    res.send(await countriesIndexPage(BAKED_BASE_URL))
)
 
mockSiteRouter.get("/country/:countrySlug", async (req, res) =>
    res.send(await countryProfilePage(req.params.countrySlug, BAKED_BASE_URL))
)
 
mockSiteRouter.get("/feedback", async (req, res) =>
    res.send(await feedbackPage())
)
 
mockSiteRouter.get("/multiEmbedderTest", async (req, res) =>
    res.send(
        renderToHtmlPage(
            MultiEmbedderTestPage(req.query.globalEntitySelector === "true")
        )
    )
)
 
mockSiteRouter.get("/*", async (req, res) => {
    const slug = req.path.replace(/^\//, "").replace("/", "__")
    try {
        res.send(await renderPageBySlug(slug))
    } catch (e) {
        console.error(e)
        res.status(404).send(await renderNotFoundPage())
    }
})
 
export { mockSiteRouter }