Create a Websocket
Create a file to src/ws
to create a a websocket controller:
src/websocet/todos.ws.ts
src/ws/todos.ws.ts
A new websocket namespace is now available at http://localhost:3000/todows
.
Create a Event
Let's assume you need to create a GET method api that get all todos.
@ReceiveFrom('todo:create', ReplyMethod.ACKNOWLEDGEMENT)
async createTodo(message: Message <Any>): Promise <Any> {
// handle client message here!
return message;
};
A new event todo:create
for namespace todo
is now available at http://localhost:3000/todows
Event Decorators
Decorator | Description | Note |
---|---|---|
@ReceiveFrom(name,replyMethod) | Create event with name and reply to client through a channel | |
@Guard(name) | Set GuardContext | |
@SendTo(event,namespace) | Send the result to client listening event |
Reply Methods
Channel | Description | Note |
---|---|---|
ACKNOWLEDGEMENT | Reply back to client directly by callback function | also know as ACK packet |
BROADCAST | Broadcast event result to all clients on all instances | |
EVENT | Reply back to client with an event | like 'todo:create:result' |
LOCAL | Broadcast event result to all clients on same instance | |
MANUAL | Manually reply to client by Socket class | The last argument always a Socket |
VOLATILE | Reply back to client but doesn't care about the status of it | work like UDP |
Register WebSockets
@Module({
websockets: [TodoWs],
})
export class AppModule {}
Settings
WebSocket is a subserver of Heron
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: {},
compressions: {},
wsPath: "/ws",
},
},
});
};
Argument | Description | Note |
---|---|---|
io | socket.io configuration | Please read socket.io (opens in a new tab) Configuration for more details |
compression | data compression | |
wsPath | global websocket server path |