feat: custom pages use ServeLiveDirectory

they now have conditional GET suppor too
This commit is contained in:
Bobby Wibowo 2022-07-22 01:09:17 +07:00
parent 51e12e13c0
commit 30e9227a78
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF
2 changed files with 19 additions and 20 deletions

View File

@ -38,17 +38,7 @@ class ServeLiveDirectory {
* MIT Licensed
*/
#middleware (req, res, next) {
// Only process GET and HEAD requests
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next()
}
const file = this.instance.get(req.path)
if (file === undefined) {
return next()
}
handler (req, res, file) {
// set header fields
this.#setHeaders(req, res, file)
@ -74,6 +64,20 @@ class ServeLiveDirectory {
return res.send(file.buffer)
}
#middleware (req, res, next) {
// Only process GET and HEAD requests
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next()
}
const file = this.instance.get(req.path)
if (file === undefined) {
return next()
}
return this.handler(req, res, file)
}
#setHeaders (req, res, file) {
// Always do external setHeaders function first,
// in case it will overwrite the following default headers anyways

View File

@ -232,13 +232,9 @@ safe.use('/api', api)
}
}
const liveDirectoryCustomPages = new LiveDirectory({
const serveLiveDirectoryCustomPagesInstance = new ServeLiveDirectory({
path: paths.customPages,
keep: ['.html'],
ignore: path => {
// ignore dot files
return path.startsWith('.')
}
keep: ['.html']
})
// Cookie Policy
@ -254,10 +250,9 @@ safe.use('/api', api)
safe.use((req, res, next) => {
if (req.method === 'GET' || req.method === 'HEAD') {
const page = req.path === '/' ? 'home' : req.path.substring(1)
const customPage = liveDirectoryCustomPages.get(`${page}.html`)
const customPage = serveLiveDirectoryCustomPagesInstance.instance.get(`${page}.html`)
if (customPage) {
// TODO: Conditional GETs? (e.g. Last-Modified, etag, etc.)
return res.type('html').send(customPage.buffer)
return serveLiveDirectoryCustomPagesInstance.handler(req, res, customPage)
} else if (config.pages.includes(page)) {
// These rendered pages are persistently cached during production
return res.render(page, {