Version: 8.0.3
Environment:
- Operating system: macOS Big Sur 11.5.2
- Browser: Google Chrome Version 92.0.4515.159 (Official Build) (x86_64)
- Node.js: 13.14.0
Hi,
I'm using Primus with websockets and I'm wondering if it supports async plugins. I looked at Primus docs but I didn't find what I need.
Basically I'm trying to pass an async function into Primus constructor like this:
this.primus = new Primus(server, {
pathname: '/my-path', plugin: {
'my-validator': {
server: myAsyncPlugin //this should run only on the server
}
}
});
The issue is that if I register plugin like that, it does not work and my plugin is always called after other handlers but I want it to be executed before other stuff happens as it validates some incoming parameters. (I also looked at middleware but I couldn't get it working)
So if I register my plugin in constructor and then do the following, my plugin will not work:
this.primus.on('connection', (spark) => {
//...do stuff
});
But if I remove plugin from constructor and use following code, everything works as expected as I'm using an async function like so:
this.primus.on('connection', async (spark) => {
//await myPlugin.doStuff();
//other stuff
});
And here's how example plugin code looks like:
public doPluginStuff = (primus, options) => {
primus.on('connection', async (spark) => {
await exectuteAsyncStuffHere();
});
};
So I'm curious if there's a way to achieve what I need or do I have to call my plugin directly in the 'connection' handler.
Thanks!
Problem clarified and solved as per this GitHub issue.
Basically it's better to use middleware for such issues (incoming parameters validation) and it can be done like this:
Also this plugin was given to my by the lib maintainer as an example of async plugin implementation, maybe it will be helpful to someone else.