WebSocket controllers handle real-time communication in HeronJS. They are built on top of socket.io and allow you to organize events by namespace, receive messages from clients, and send responses through different reply strategies.
Create a WebSocket controller
Create a file for your WebSocket controller, for example:
src/ws/todo.ws.ts
import { WebSocket } from '@heronjs/common';
@WebSocket('todows')
export class TodoWs {}This creates a WebSocket namespace for todows.
Create an event handler
Use @ReceiveFrom() to listen for an incoming event from the client.
@ReceiveFrom('todo:create', ReplyMethod.ACKNOWLEDGEMENT)
public async createTodo(message: Message<Any>): Promise<Any> {
return message;
}In this example:
todo:createis the event name the client sends.ReplyMethod.ACKNOWLEDGEMENTreplies directly through the socket acknowledgment callback.
Event decorators
| Decorator | Description | Note |
|---|---|---|
@ReceiveFrom(name, replyMethod) | Receives an event from the client and processes it. | |
@Guard(...) | Applies authorization rules to the event handler. | |
@SendTo(event, namespace) | Sends the result to another event or namespace. |
Reply methods
| Reply method | Description | Note |
|---|---|---|
ACKNOWLEDGEMENT | Responds directly through the client callback. | Also known as an ACK packet. |
BROADCAST | Broadcasts the result to all clients across instances. | |
EVENT | Sends the result back through another event name. | Example: todo:create:result |
LOCAL | Broadcasts the result to clients on the same instance only. | |
MANUAL | Lets you respond manually using the Socket object. | The last argument is usually a Socket. |
VOLATILE | Sends a best-effort response without guaranteeing delivery. | Similar to UDP behavior. |
Register WebSocket controllers
Register the controller in the module websockets array.
@Module({
websockets: [TodoWs],
})
export class AppModule {}Configure the WebSocket server
In HeronJS, the WebSocket server runs as a subserver. Configure it through the subServer.ws option when starting the app.
const main = async () => {
const app = await HeronJS.create({ module: AppModule });
await app.listen({
port: 3000,
options: {
cors: {
origin: '*',
preflightContinue: false,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
},
globalError: GlobalApiErrorInterceptor,
},
subServer: {
ws: {
io: {},
compression: {},
wsPath: '/ws',
},
},
});
};| Argument | Description | Note |
|---|---|---|
io | socket.io server configuration. | See socket.io for available options. |
compression | Configures payload compression. | |
wsPath | Sets the global WebSocket server path. |
Last updated on