Zappa(JS) v5.3: socket.io middleware

6 views
Skip to first unread message

step...@shimaore.net

unread,
Aug 22, 2016, 5:24:03 PM8/22/16
to zap...@googlegroups.com
Hello,

ZappaJS 5.3 is out and introduces socket.io middleware, for those
situations where you want to share middleware between Express and
Socket.io, or simply need to perform a common operation on all socket.io
messages (e.g. logging them).

# This is our middleware.
load_user_data = @wrap ->
@res.locals.user_data = {}
if @session.username?
# load user-data from db once the username is known
@res.locals.user_data = yield db
.get_user_data @session.username
.catch -> {}

# Use it with Express.
@use load_user_data

@get '/welcome', ->
@render 'welcome' # render() inject res.locals into the template

# Use it with Socket.io.
@io_use load_user_data

@on 'send-my-data', ->
@emit 'here-is-your-data', @res.locals.user_data

The context for the middleware wrapper has been extended to provide
`@join`, `@leave`, `@emit`, `@broadcast_to`, etc. were applicable. Also
`@res.locals`, `@req.body` (and `@body`) were added in both middleware
and socket handlers' context.

(Historically `@locals` in socket handlers referred to `@app.locals`;
I haven't changed its behavior in this minor release, but I will do that
in an upcoming major release, so that all middleware, express handlers,
and socket handlers may refer to `@res.locals` as `@locals`.)

Since `@emit` and `@broadcast_to` can also be used in Express middlewares
and handlers (as long as the Express and socket.io sessions have been
linked using `zappajs-client` on the client-side), you may also use these
in middleware shared by Express and Socket.io.

Finally, just like Express, this new feature supports both globally-applied
middleware, with the new `@io_use` command, or per-message middleware:

@on 'special-message', special_middleware, ->
# do something

Hope you enjoy this new feature! Until next time,
S.

--
tel:+33643482771
http://stephane.shimaore.net/

step...@shimaore.net

unread,
Aug 23, 2016, 5:32:28 AM8/23/16
to zap...@googlegroups.com
Sorry for the noise, quick correction and update..

> # This is our middleware.
> load_user_data = @wrap ->
> @res.locals.user_data = {}
> if @session.username?
> # load user-data from db once the username is known
> @res.locals.user_data = yield db
> .get_user_data @session.username
> .catch -> {}

Duh, that would need @next() somewhere to actually work :)

> (Historically `@locals` in socket handlers referred to `@app.locals`;
> I haven't changed its behavior in this minor release, but I will do that
> in an upcoming major release, so that all middleware, express handlers,
> and socket handlers may refer to `@res.locals` as `@locals`.)

That's done in 6.0. `@locals` inside handlers or middlewares now always
refers to `res.locals`.
Reply all
Reply to author
Forward
0 new messages