Merge pull request #19465 from overleaf/ab-modules-middlewares

[web] Support injecting middlewares from modules

GitOrigin-RevId: efbf68d885f839b92f2e601553c7ce54b9d4b6d3
This commit is contained in:
Alexandre Bourdin
2024-07-24 08:05:09 +00:00
committed by Copybot
parent 34422b1428
commit 8e79d72cc2
+26 -5
View File
@@ -10,6 +10,7 @@ const MODULE_BASE_PATH = Path.join(__dirname, '/../../../modules')
const _modules = [] const _modules = []
let _modulesLoaded = false let _modulesLoaded = false
const _hooks = {} const _hooks = {}
const _middleware = {}
let _viewIncludes = {} let _viewIncludes = {}
function modules() { function modules() {
@@ -43,6 +44,7 @@ function loadModules() {
} }
_modulesLoaded = true _modulesLoaded = true
attachHooks() attachHooks()
attachMiddleware()
} }
function applyRouter(webRouter, privateApiRouter, publicApiRouter) { function applyRouter(webRouter, privateApiRouter, publicApiRouter) {
@@ -111,11 +113,9 @@ function linkedFileAgentsIncludes() {
function attachHooks() { function attachHooks() {
for (const module of modules()) { for (const module of modules()) {
if (module.hooks != null) { for (const hook in module.hooks || {}) {
for (const hook in module.hooks) { const method = module.hooks[hook]
const method = module.hooks[hook] attachHook(hook, method)
attachHook(hook, method)
}
} }
} }
} }
@@ -127,6 +127,18 @@ function attachHook(name, method) {
_hooks[name].push(method) _hooks[name].push(method)
} }
function attachMiddleware() {
for (const module of modules()) {
for (const middleware in module.middleware || {}) {
const method = module.middleware[middleware]
if (_middleware[middleware] == null) {
_middleware[middleware] = []
}
_middleware[middleware].push(method)
}
}
}
function fireHook(name, ...rest) { function fireHook(name, ...rest) {
// ensure that modules are loaded if we need to fire a hook // ensure that modules are loaded if we need to fire a hook
// this can happen if a script calls a method that fires a hook // this can happen if a script calls a method that fires a hook
@@ -146,6 +158,14 @@ function fireHook(name, ...rest) {
}) })
} }
function getMiddleware(name) {
// ensure that modules are loaded if we need to call a middleware
if (!_modulesLoaded) {
loadModules()
}
return _middleware[name] || []
}
module.exports = { module.exports = {
applyNonCsrfRouter, applyNonCsrfRouter,
applyRouter, applyRouter,
@@ -158,6 +178,7 @@ module.exports = {
attach: attachHook, attach: attachHook,
fire: fireHook, fire: fireHook,
}, },
middleware: getMiddleware,
promises: { promises: {
hooks: { hooks: {
fire: promisify(fireHook), fire: promisify(fireHook),