Here's the middleware that I use in express:
const app = express();
const port = 8000;
const f = () => {
return async (req, res, next) => {
await new Promise(resolve => setTimeout(resolve, 3000));
return next();
}
}
const namedFunction = f();
app.use(namedFunction); // earlier I was using `app.use(f());`
But my function still appear as anonymous function in profiler: Something like this:
A bit of background: We want to see which middleware is causing the high latency, but because the middlewares are anonymous, we can't narrow down the cause in our APM + JS profiler. The preceding is just one example; we use approximately 40 middleware packages over which we have no control.
That's why I thought passing f()
to namedFunction
should fix the issue but it wasn't so looking for help on this.
Other tries till now: As per Jonsharpe's comment I tried:
app.use(function namedFunction() { f()(...arguments) });
But in profiler it still appear as an anonymous function
After a lot many tries of assigning name, refactoring use I came up with this and finally the profiler was able to point out that it's the wrappedFunction which is causing it so going ahead I'll need to create a wrapperFunction for each of the case.
Here's a sample of what worked in the end:
const f = () => {
return async (req, res, next) => {
await new Promise(resolve => setTimeout(resolve, 3000));
return next();
}
}
const wrappedFunction = async(req, res, next) => {
await new Promise(resolve => f()(req, res, resolve)); // Now since time is spent in this block that's why profiler is picking this up instead of the anonymous function as the main resource consuming function
next();
}
app.use(wrappedFunction);
And here's what it looks like in profiler now:
Just an note to others who might not know the context:
By default the official middlewares are usually named functions but some 3rd party middleware return an anonymous function which profiler/APM isn't able to pick up and point to code block from there.
That's why it's important to have a named function instead of anonymous middleware
showing up in UI and being unclear where to look at.