qwik-site/libs/requestHandler.js

29 lines
1.2 KiB
JavaScript
Raw Normal View History

2021-08-09 17:44:53 +02:00
import fs from 'fs'
import { mdRenderer, njkRenderer } from './siteRenderer.js'
// Handle all request and try to find a corresponding file/template.
export function requestHandler(req, res, Config) {
2022-08-13 10:47:16 +02:00
// Add some sanitization:
const path = req.path
// Remove all '..' -- should prevent path traversal.
.replace(/\.\.+/g, "")
// Remove trailing slashes ('/').
.replace(/\/+$/g, "")
2021-08-09 17:44:53 +02:00
// Check for njk files first
2022-08-13 10:47:16 +02:00
if (fs.existsSync(`./${Config.contentDir}/pages/${path}.njk`))
return res.send(njkRenderer(`./${Config.contentDir}/pages/${path}.njk`))
if (fs.existsSync(`./${Config.contentDir}/pages/${path}/index.njk`))
return res.send(njkRenderer(`./${Config.contentDir}/pages/${path}/index.njk`))
2021-08-09 17:44:53 +02:00
// Secondly search for markdown
2022-08-13 10:47:16 +02:00
if (fs.existsSync(`./${Config.contentDir}/pages/${path}.md`))
return res.send(mdRenderer(`./${Config.contentDir}/pages/${path}.md`))
if (fs.existsSync(`./${Config.contentDir}/pages/${path}/index.md`))
return res.send(mdRenderer(`./${Config.contentDir}/pages/${path}/index.md`))
2021-08-09 17:44:53 +02:00
// If no matching file is found, return a 404 error.
return res.status(404).send(njkRenderer(`./${Config.contentDir}/errors/404.njk`))
2022-08-13 10:47:16 +02:00
}