WebSocket
Overview

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

DecoratorDescriptionNote
@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

ChannelDescriptionNote
ACKNOWLEDGEMENTReply back to client directly by callback functionalso know as ACK packet
BROADCASTBroadcast event result to all clients on all instances
EVENTReply back to client with an eventlike 'todo:create:result'
LOCALBroadcast event result to all clients on same instance
MANUALManually reply to client by Socket classThe last argument always a Socket
VOLATILEReply back to client but doesn't care about the status of itwork 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",
      },
    },
  });
};
ArgumentDescriptionNote
iosocket.io configurationPlease read socket.io (opens in a new tab) Configuration for more details
compressiondata compression
wsPathglobal websocket server path