Description
Manage socket.io's namespaces like services and actions.
Project example
You can find an example of moleculer-socketio
and moleculer-nextjs
at moleculer-nextjs-socketio-example
Install
$ npm install moleculer-socketio --save
USAGE
you can use moleculer-socketio
manage events like actions in services, in socket.io
it's called namespaces
so you must add it into your service.
In socket.io, the root channel is /
but you can define multiple namespaces !
namespaces: "/": // root namespace { thislogger; return "Get this data!"; } "/private": // another namespace { thislogger }
On the client side you could connect to those namespaces :
const io = ; const root = ;root;root; const private = ;private
Events
Every events for each namespaces can be code differently :
namespaces: "/": { return "somedata" } eventB: // You can specify parameter validation // Just like actions params: parameterA: "string" parameterB: "number" async { return "somedata again"; } eventC: "service.action" eventD: "service.action" { return "another data" } "service.action"
When you return data from an event, it will emit an event with it.
Middlewares
You may want to add some conditions to validate the execution of your actions. You can use a middleware for this case.
namespaces: "/private": middlewares: { if !ctxparamscrypted throw "You're missing crypted parameter"; } deleteAllUsers: middlewares: { if !ctxparamsisAdmin throw "No, you're not an admin"; } { if ctxparamsusername != "Icebob" throw "Sorry, you're not enough badass"; } { return "Destroy everything"; }
Custom response
One more thing, you can also manage custom responses.
const SocketIO = ; moduleexports = name: "socket-service" mixins: SocketIO settings: port: 5000 options: // Socket.io options { // Response Templated let payload = {}; if !error if resultslength > 1 results; else payload = results0; return error: error payload: payload ; } ;
EXAMPLE
const SocketIO = ; moduleexports = name: "socket-service" mixins: SocketIO settings: port: 5000 options: // Socket.io options actions: namespaces: "/": { thislogger; ctxsocket; } sendMessage: params: message: "string" async { thislogger; return true; } "/admin": middlewares: { if !ctxparamsisAdmin throw "Sorry you can't connect here"; } connection: middlewares: { if ctxparamsisAdmin && ctx throw "Sorry you can't connect here"; } async { thislogger; ctxsocket; } methods: { console; thisio = io; thisio; }
This should be on client side
; thissocket = ; thissocket; thissocket;thissocket;