feat: improve types by extending socket.io module (#6)

This commit is contained in:
Jozef Sovcik 2021-01-04 14:35:59 +01:00 committed by GitHub
parent abc1225189
commit 84b523f434
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 8 deletions

View File

@ -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)
}
}
})
```

View File

@ -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()
}
}