Skip to content

Commit

Permalink
fix(ui5-middleware-ui5): ensure middlware stack order when hooking (#865
Browse files Browse the repository at this point in the history
)
  • Loading branch information
petermuessig authored Oct 3, 2023
1 parent d1b184b commit 7fd61f2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
4 changes: 2 additions & 2 deletions packages/ui5-middleware-ui5/lib/ui5.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ module.exports = async ({ log, options, middlewareUtil }) => {
} else {
return hook(
"ui5-middleware-ui5",
async ({ app }) => {
async ({ use }) => {
const ui5Modules = await findUI5Modules({
cwd,
log,
Expand All @@ -52,7 +52,7 @@ module.exports = async ({ log, options, middlewareUtil }) => {
basePath: modulePath,
...(options || {}),
});
app.use(mountPath, router);
use(mountPath, router);
}
},
function (req, res, next) {
Expand Down
20 changes: 17 additions & 3 deletions packages/ui5-middleware-websocket/lib/hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,13 @@ module.exports = function hook(name, callback, middleware) {
app,
server,
on: server.on.bind(server),
use: app.use.bind(app),
options: {
mountpath: "/",
},
});
} else {
console.error(
`\x1b[36m[ui5-middleware-websocket]\x1b[0m \x1b[31m[ERROR]\x1b[0m Failed to install websocket support on current server (most likely it is a connect server, and this only works on express)!`
);
console.error(`\x1b[36m[~~hook~~]\x1b[0m \x1b[31m[ERROR]\x1b[0m Failed to hook into current server (most likely it is a connect server, and this only works on express)!`);
}
initializedByRouter = true;
}
Expand All @@ -100,6 +99,9 @@ module.exports = function hook(name, callback, middleware) {
emit: (event, app) => {
// intercept the mount event to get access to the app
if (event === "mount") {
// store the position into which new custom middlewares should
// be placed into when using the "use" function of the callback
const middlewareIndex = app?._router?.stack?.length;
// intercept the listen call to get access to the server
const { listen } = app;
app.listen = function () {
Expand All @@ -117,6 +119,18 @@ module.exports = function hook(name, callback, middleware) {
app: this,
server,
on: server.on.bind(server),
use: function use() {
app.use.apply(app, arguments);
// move the middleware function just after the mounted
// express app in the middleware stack to ensure proper
// order and execution in the middleware chain!
if (middlewareIndex != null && middlewareIndex !== -1) {
const middlewareStack = app?._router?.stack;
const cmw = middlewareStack.pop();
middlewareStack.splice(middlewareIndex, 0, cmw);
}
return app;
},
options,
});
return server;
Expand Down

0 comments on commit 7fd61f2

Please sign in to comment.