| 10 | const logger = getServiceChildLogger('websockets/namespaces') |
| 11 | |
| 12 | export default class WebSocketNamespace<TSocket extends ISocket = ISocket> { |
| 13 | private readonly log: Logger |
| 14 | |
| 15 | public readonly socketIoNamespace: Namespace |
| 16 | |
| 17 | public constructor( |
| 18 | socketIoServer: Server, |
| 19 | public readonly namespace: string, |
| 20 | public readonly authenticated: boolean, |
| 21 | ) { |
| 22 | this.log = logger.child({ namespace }, true) |
| 23 | |
| 24 | this.socketIoNamespace = socketIoServer.of(namespace) |
| 25 | |
| 26 | // database middleware |
| 27 | this.socketIoNamespace.use(async (socket: any, next: NextFunction) => { |
| 28 | try { |
| 29 | socket.database = await databaseInit() |
| 30 | next() |
| 31 | } catch (err) { |
| 32 | this.log.error(err, 'Database connection error!') |
| 33 | next(err) |
| 34 | } |
| 35 | }) |
| 36 | |
| 37 | if (authenticated) { |
| 38 | // auth middleware |
| 39 | this.socketIoNamespace.use(async (socket: any, next: NextFunction) => { |
| 40 | try { |
| 41 | if (socket.handshake.query && socket.handshake.query.token) { |
| 42 | socket.user = await AuthService.findByToken(socket.handshake.query.token, socket) |
| 43 | next() |
| 44 | } else { |
| 45 | next(new Error('Authentication error')) |
| 46 | } |
| 47 | } catch (err) { |
| 48 | this.log.error(err, 'WebSockets authentication error!') |
| 49 | next(err) |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | // handle connect |
| 55 | this.socketIoNamespace.on('connection', (socket: ISocket) => { |
| 56 | if (authenticated) { |
| 57 | this.log.info( |
| 58 | { userId: (socket as IAuthenticatedSocket).user.id }, |
| 59 | 'Authenticated user connected!', |
| 60 | ) |
| 61 | // add to user room if we need to send a notification to this user only |
| 62 | socket.join(`user-${(socket as IAuthenticatedSocket).user.id}`) |
| 63 | } else { |
| 64 | this.log.info('User connected!') |
| 65 | } |
| 66 | |
| 67 | socket.emit('connected') |
| 68 | |
| 69 | // handle disconnect |
nothing calls this directly
no outgoing calls
no test coverage detected