mattstyles / koa-socket

Sugar for connecting socket.io to a koa instance
242 stars 50 forks source link

Mounting Middlewares to listeners koa style #9

Closed fselcukcan closed 8 years ago

fselcukcan commented 8 years ago

Is that possible to mount middleware to listeners koa.js style, that is mounting several middleware by passing them to event listener function of this module just before the event handler function.

io.on('chat', middleware1, middleware2, (ctx, data) => {
    // bla bla.
});

In ready there are examples mount middleware to the module instance, I mean mounting middleware to any event listener.

mattstyles commented 8 years ago

I'm not sure what you mean by 'koa style', koa middleware are attached to the instance, which is the same here, by design.

With socket.io you can register middleware functions per namespace but I wasnt aware you could do it per event.

I think you can solve what you're after by restructuring a bit so you add those middleware functions only to specific namespaces.

fselcukcan commented 8 years ago

It is similar to what you mean by koa v2 style :), mean in koa.js one can mount middlewares to an app instance or to a route, examples of both respectively:

app.use(middleware());
publicRouter.get('/', jwt({secret: 'my secret', cookie: 'token'}), function* (next){
    // this.state.user is set to json object decoded by middleware.
    //
    var token = this.cookies.get('token');
    console.log("/, token from this.cookies:", token);

    try {
        this.body = yield readFileThunk(__dirname + '/browser/dist/app.html');
    } catch(err) {
        console.log('/,', err);
        this.redirect('/entrance');
    }
});
fselcukcan commented 8 years ago

So, I can mount middleware per namespace with koa-socket, right?

mattstyles commented 8 years ago

Yep, each instance/namespace is totally unique and they won't inter operate with each other you can different middlewares per namespace.

Per route sounds useful (I'm actually working on something where that will be useful at the moment), given that sockets simply emit (it's far simpler than restful routing for example) there's a case for it being included in this module rather than extracted to its own place. At the same time I don't want to increase the complexity here.

On Sun, Jan 24, 2016 at 12:44 PM, Işık Faruk S. notifications@github.com wrote:

So, I can mount middleware per namespace with koa-socket, right?

Reply to this email directly or view it on GitHub: https://github.com/mattstyles/koa-socket/issues/9#issuecomment-174293103

mattstyles commented 8 years ago

Closing this as namespaces cover it I think, and routing should be handled by a separate module rather than here.