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-23 11:36:32 +02:00 committed by Copybot
parent 34422b1428
commit 8e79d72cc2

View file

@ -10,6 +10,7 @@ const MODULE_BASE_PATH = Path.join(__dirname, '/../../../modules')
const _modules = []
let _modulesLoaded = false
const _hooks = {}
const _middleware = {}
let _viewIncludes = {}
function modules() {
@ -43,6 +44,7 @@ function loadModules() {
}
_modulesLoaded = true
attachHooks()
attachMiddleware()
}
function applyRouter(webRouter, privateApiRouter, publicApiRouter) {
@ -111,11 +113,9 @@ function linkedFileAgentsIncludes() {
function attachHooks() {
for (const module of modules()) {
if (module.hooks != null) {
for (const hook in module.hooks) {
const method = module.hooks[hook]
attachHook(hook, method)
}
for (const hook in module.hooks || {}) {
const method = module.hooks[hook]
attachHook(hook, method)
}
}
}
@ -127,6 +127,18 @@ function attachHook(name, 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) {
// 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
@ -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 = {
applyNonCsrfRouter,
applyRouter,
@ -158,6 +178,7 @@ module.exports = {
attach: attachHook,
fire: fireHook,
},
middleware: getMiddleware,
promises: {
hooks: {
fire: promisify(fireHook),