From 84b523f4348c81933887f0dc700f438c84bd779a Mon Sep 17 00:00:00 2001 From: Jozef Sovcik Date: Mon, 4 Jan 2021 14:35:59 +0100 Subject: [PATCH] feat: improve types by extending socket.io module (#6) --- README.md | 16 ++++++++++------ src/authorize.ts | 13 +++++++++++-- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 9f7d9c5..18e37b1 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,17 @@ io.use( }) ) -io.on('connection', async () => { +io.on('connection', async (socket) => { + // jwt payload of the connected client + console.log(socket.decodedToken) const clients = await io.sockets.allSockets() - for (const clientId of clients) { - const client = io.sockets.sockets.get(clientId) - client.emit('messages', { message: 'Success!' }) - // we can access the jwt payload of each connected client - console.log(client.decodedToken) + if (clients != null) { + for (const clientId of clients) { + const client = io.sockets.sockets.get(clientId) + client?.emit('messages', { message: 'Success!' }) + // we can access the jwt payload of each connected client + console.log(client?.decodedToken) + } } }) ``` diff --git a/src/authorize.ts b/src/authorize.ts index c445eb7..e7ca83d 100644 --- a/src/authorize.ts +++ b/src/authorize.ts @@ -3,10 +3,19 @@ import { Socket } from 'socket.io' import { UnauthorizedError } from './UnauthorizedError' +declare module 'socket.io' { + interface Socket extends ExtendedSocket {} +} + interface ExtendedError extends Error { data?: any } +interface ExtendedSocket { + encodedToken?: string + decodedToken?: any +} + type SocketIOMiddleware = ( socket: Socket, next: (err?: ExtendedError) => void @@ -41,7 +50,7 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => { ) } // Store encoded JWT - socket = Object.assign(socket, { encodedToken: token }) + socket.encodedToken = token let payload: any try { payload = jwt.verify(token, secret, { algorithms }) @@ -53,7 +62,7 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => { ) } // Store decoded JWT - socket = Object.assign(socket, { decodedToken: payload }) + socket.decodedToken = payload return next() } }