forked from SwiftChainn/SwiftChain_Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
53 lines (43 loc) · 1.55 KB
/
Copy pathindex.ts
File metadata and controls
53 lines (43 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Server, Socket, Namespace } from 'socket.io';
import { Server as HttpServer } from 'http';
import registerSocketHandlers from './socketController';
import logger from '../config/logger';
import socketAuth from '../middlewares/socketAuth';
let realtimeNsp: Namespace | null = null;
export const initSocket = (httpServer: HttpServer): Server => {
const io = new Server(httpServer, {
path: '/socket.io',
cors: {
origin: process.env.CORS_ORIGIN || '*',
methods: ['GET', 'POST'],
},
});
const nsp = io.of('/api/v1/realtime');
// Store namespace for external use
realtimeNsp = nsp;
// Attach authentication middleware to namespace
nsp.use((socket, next) => socketAuth(socket as Socket, next as (err?: Error) => void));
nsp.on('connection', (socket) => {
// Join a room based on user ID if available
const userId = (socket as any).user?.id;
if (userId) {
socket.join(userId);
}
registerSocketHandlers(socket, nsp);
});
logger.info('✅ Socket.io initialized on namespace /api/v1/realtime');
return io;
};
/**
* Emits a delivery_status_updated event to a specific user's connected socket(s).
* This is intended to be called from the indexer handler when the on-chain
* delivery_status_updated event is processed.
*/
export const emitDeliveryStatusUpdated = (userId: string, payload: unknown): void => {
if (!realtimeNsp) {
logger.warn('Socket.io namespace not initialized yet');
return;
}
realtimeNsp.to(userId).emit('delivery_status_updated', payload);
};
export default initSocket;