refactor: ServeStatic.middleware -> .handler

also moved it from middlewares to handlers directory

reasoning is that this class is better suited to handle routes directly
instead of being a global middleware
since IO stat to check if request path matches a physical file in the
disk every single time is not very performant
This commit is contained in:
Bobby Wibowo 2022-07-22 01:12:35 +07:00
parent 06178cc2c4
commit 76a73b7e83
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF
2 changed files with 9 additions and 11 deletions

View File

@ -10,8 +10,6 @@ const utils = require('./../utilsController')
const serveUtils = require('./../utils/serveUtils')
const logger = require('./../../logger')
// NOTE: This middleware must be set last if on a root path that is also used by other routes
class ServeStatic {
directory
contentDispositionStore
@ -22,8 +20,6 @@ class ServeStatic {
#options
constructor (directory, options = {}) {
logger.debug(`new ServeStatic(): ${directory}`)
if (!directory || typeof directory !== 'string') {
throw new TypeError('Root directory must be set')
}
@ -140,7 +136,7 @@ class ServeStatic {
* MIT Licensed
*/
async #middleware (req, res) {
async #handler (req, res) {
if (this.#options.ignorePatterns && this.#options.ignorePatterns.some(pattern => req.path.startsWith(pattern))) {
return errors.handleNotFound(req, res)
}
@ -279,8 +275,8 @@ class ServeStatic {
return res.stream(readStream)
}
get middleware () {
return this.#middleware.bind(this)
get handler () {
return this.#handler.bind(this)
}
}

View File

@ -43,12 +43,14 @@ const paths = require('./controllers/pathsController')
paths.initSync()
const utils = require('./controllers/utilsController')
// Custom middlewares
// Middlewares
const ExpressCompat = require('./controllers/middlewares/expressCompat')
const NunjucksRenderer = require('./controllers/middlewares/nunjucksRenderer')
const RateLimiter = require('./controllers/middlewares/rateLimiter')
const ServeLiveDirectory = require('./controllers/middlewares/serveLiveDirectory')
const ServeStatic = require('./controllers/middlewares/serveStatic')
// Handlers
const ServeStatic = require('./controllers/handlers/serveStatic')
// Routes
const album = require('./routes/album')
@ -273,8 +275,8 @@ safe.use('/api', api)
overrideContentTypes: config.overrideContentTypes,
setContentDisposition: config.setContentDisposition
})
safe.get('/*', serveStaticInstance.middleware)
safe.head('/*', serveStaticInstance.middleware)
safe.get('/*', serveStaticInstance.handler)
safe.head('/*', serveStaticInstance.handler)
utils.contentDispositionStore = serveStaticInstance.contentDispositionStore
}