@triplef/socketio
v0.1.0
Published
A NestJS module for building real-time applications with Socket.IO
Readme
@triplef/socketio
A NestJS module for building real-time applications with Socket.IO — room management, event handling, and a fluent emission API with Fastify/Express auto-detection.
This library is **ESM-only** and does not support CommonJS.Your project must use ES modules.
StatusBadges
DevDependencies
PeerDependencies
Features
- NestJS-native — a dynamic module (
registerAsync) wiring aSocketIOServiceto caller-suppliedSocketIOServerConfig. - Adapter auto-detection —
SocketIOModule.attach()detects Fastify or Express and attaches Socket.IO accordingly. - Room management —
joinRoom/leaveRoomhelpers plusto/in/exceptmodifiers for targeted emission. - Fluent API — every service method returns
thisfor chaining (to(room).emit(event, data)). - Full server surface —
emit,emitTo,on,timeout,fetchSockets,socketsJoin,socketsLeave,disconnectSockets,close,of,use.
Installation
pnpm add @triplef/socketioFor Fastify support:
pnpm add fastify-socket.ioUsage
Module setup
The library ships no env-driven config — supply the SocketIOServerConfig
through a factory, and validate it with the exported SocketIOConfigSchema.
import { SocketIOModule, SocketIOConfigSchema } from '@triplef/socketio';
import { ValidateReturnValue } from '@triplef/config-factory/validate-return-value';
@Module({
imports: [
SocketIOModule.registerAsync({
global: true,
inject: [MySocketIOConfigService],
useFactory: (config: MySocketIOConfigService) => config.options,
}),
],
})
export class AppModule {}Attaching the server
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { SocketIOModule } from '@triplef/socketio';
void (async () => {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
await SocketIOModule.attach(app);
await app.listen({ port: 3000 });
})();Emitting events
import { SocketIOService } from '@triplef/socketio';
@Injectable()
export class NotificationsService {
constructor(private readonly socketService: SocketIOService) {}
notifyUser(userId: string, notification: unknown) {
this.socketService.emitTo('notification', userId, notification);
}
notifyAll(notification: unknown) {
this.socketService.emit('notification', notification);
}
}