feat: improve types by extending socket.io module (#6)
This commit is contained in:
parent
abc1225189
commit
84b523f434
16
README.md
16
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user