Socket.IO Controllers
A Socket.IO controller is a class that groups related event handlers under a common namespace. Each method maps to a Socket.IO event via @WSOperation decorators. OPRA validates incoming event payloads and encodes outgoing acknowledgements automatically.
Defining a Controller
Decorate the class with @WSController() and pass the namespace.
import { WSController } from '@opra/common';
@WSController('customers')
export class CustomersWsController {}
@WSController() applies @Injectable() automatically in a NestJS application, so services can be injected through the constructor without any extra decoration.
Defining Operations
Each operation is declared with @WSOperation. The event name defaults to the method name. Pass an event option to override it.
import { WSController, WSOperation, ArrayType } from '@opra/common';
import { WsContext } from '@opra/socket.io';
import { Customer, CustomerCreate, CustomerPatch } from '../models/customer.js';
@WSController('customers')
export class CustomersWsController {
@WSOperation({ response: ArrayType(Customer) })
async list(ctx: WsContext) { ... }
@WSOperation({ response: Customer })
async get(ctx: WsContext) { ... }
@WSOperation({ response: Customer })
async create(ctx: WsContext) { ... }
@WSOperation({ response: Customer })
async update(ctx: WsContext) { ... }
@WSOperation()
async delete(ctx: WsContext) { ... }
}
To use a custom event name different from the method name, pass event in the options:
@WSOperation({ event: 'customer:get', response: Customer })
async get(ctx: WsContext) { ... }
.UseType()
Registers types scoped to this operation without exposing them globally.
@WSOperation({ response: ArrayType(Customer) })
.UseType(CustomerStatus)
async list(ctx: WsContext) { ... }
NestJS Integration
Register the controller and its dependencies in OpraSocketioModule.forRoot():
import { OpraSocketioModule } from '@opra/nestjs-socketio';
import { CustomersWsController } from './controllers/customers.ws-controller.js';
import { CustomersService } from './services/customers.service.js';
OpraSocketioModule.forRoot({
controllers: [CustomersWsController],
providers: [CustomersWsController, CustomersService],
})