@galaxy-stack/orbit-websockets
v0.1.9
Published
WebSocket gateway for Orbit framework
Readme
@galaxy-stack/orbit-websockets
Mô tả
Module WebSocket Gateway cho Orbit với decorators theo phong cách NestJS.
Tính năng chính
1. WebSocket Gateway
import {
WebSocketGateway,
SubscribeMessage,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@galaxy-stack/orbit-websockets';
@WebSocketGateway({ port: 8080 })
class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server!: WebSocketServer;
handleConnection(client: WebSocket) {
console.log('Client connected');
}
handleDisconnect(client: WebSocket) {
console.log('Client disconnected');
}
@SubscribeMessage('chat')
handleMessage(client: WebSocket, data: { message: string }) {
// Broadcast to all
this.server.emit('chat', { message: data.message });
}
}2. Message Patterns
@SubscribeMessage('joinRoom')
handleJoinRoom(client: WebSocket, data: { room: string }) {
client.join(data.room);
return { event: 'joined', room: data.room };
}
@SubscribeMessage('leaveRoom')
handleLeaveRoom(client: WebSocket, data: { room: string }) {
client.leave(data.room);
}Cấu hình Module
import { WebSocketsModule } from '@galaxy-stack/orbit-websockets';
@Module({
imports: [WebSocketsModule.forRoot()],
providers: [ChatGateway],
})
class AppModule {}Gateway Options
@WebSocketGateway({
port: 8080,
path: '/ws',
cors: {
origin: '*',
},
namespace: '/chat',
})
class ChatGateway {}Server Methods
// Emit to all clients
this.server.emit('event', data);
// Emit to specific room
this.server.to('room-1').emit('event', data);
// Emit to specific client
client.emit('event', data);
// Get all connected clients
const clients = this.server.clients;Client-side
const ws = new WebSocket('ws://localhost:8080/ws');
ws.onopen = () => {
ws.send(JSON.stringify({
event: 'chat',
data: { message: 'Hello!' }
}));
};
ws.onmessage = (event) => {
const { event: eventName, data } = JSON.parse(event.data);
console.log(eventName, data);
};Guards & Interceptors
@UseGuards(WsAuthGuard)
@WebSocketGateway()
class ProtectedGateway {
@SubscribeMessage('secure')
@UseInterceptors(LoggingInterceptor)
handleSecure(client: WebSocket, data: any) {
return { status: 'ok' };
}
}