70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
import {
|
|
WebSocketGateway,
|
|
WebSocketServer,
|
|
SubscribeMessage,
|
|
OnGatewayConnection,
|
|
OnGatewayDisconnect,
|
|
MessageBody,
|
|
ConnectedSocket,
|
|
} from '@nestjs/websockets';
|
|
import { Server, Socket } from 'socket.io';
|
|
import { Logger, UseGuards } from '@nestjs/common';
|
|
import { WsAdminAuthGuard, type AuthenticatedSocket } from './guards/ws-admin-auth.guard';
|
|
import { WsRestId } from './decorators/ws-rest-id.decorator';
|
|
import { NotificationService } from './services/notification.service';
|
|
|
|
@WebSocketGateway({
|
|
cors: {
|
|
origin: true,
|
|
credentials: true,
|
|
},
|
|
namespace: '/notifications',
|
|
})
|
|
export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisconnect {
|
|
@WebSocketServer()
|
|
server!: Server;
|
|
|
|
private readonly logger = new Logger(NotificationsGateway.name);
|
|
|
|
constructor(private readonly notificationService: NotificationService) {}
|
|
|
|
handleConnection(client: Socket) {
|
|
this.logger.log(`Client connected: ${client.id}`);
|
|
}
|
|
|
|
handleDisconnect(client: Socket) {
|
|
this.logger.log(`Client disconnected: ${client.id}`);
|
|
}
|
|
|
|
/**
|
|
* Get admin restaurant notifications
|
|
* Requires admin authentication via JWT token
|
|
* Restaurant ID is extracted from the authenticated admin's token
|
|
* This is a WebSocket substitution for GET /admin/notifications
|
|
*/
|
|
@UseGuards(WsAdminAuthGuard)
|
|
@SubscribeMessage('get:notifications')
|
|
async handleGetNotifications(
|
|
@ConnectedSocket() client: AuthenticatedSocket,
|
|
@WsRestId() restId: string,
|
|
@MessageBody() data?: { limit?: number },
|
|
) {
|
|
try {
|
|
const limit = data?.limit ? parseInt(data.limit.toString(), 10) : 50;
|
|
const notifications = await this.notificationService.findByRestaurant(restId, limit);
|
|
|
|
void client.emit('notifications:list', { notifications });
|
|
this.logger.log(`Admin ${client.adminId} requested notifications list for restaurant ${restId}`);
|
|
} catch (error) {
|
|
this.logger.error(
|
|
`Error getting notifications list: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
);
|
|
void client.emit('error', {
|
|
message: 'Failed to get notifications list',
|
|
code: 'GET_NOTIFICATIONS_ERROR',
|
|
details: error instanceof Error ? error.message : 'Unknown error',
|
|
});
|
|
}
|
|
}
|
|
}
|