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()
|
const clients = await io.sockets.allSockets()
|
||||||
for (const clientId of clients) {
|
if (clients != null) {
|
||||||
const client = io.sockets.sockets.get(clientId)
|
for (const clientId of clients) {
|
||||||
client.emit('messages', { message: 'Success!' })
|
const client = io.sockets.sockets.get(clientId)
|
||||||
// we can access the jwt payload of each connected client
|
client?.emit('messages', { message: 'Success!' })
|
||||||
console.log(client.decodedToken)
|
// 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'
|
import { UnauthorizedError } from './UnauthorizedError'
|
||||||
|
|
||||||
|
declare module 'socket.io' {
|
||||||
|
interface Socket extends ExtendedSocket {}
|
||||||
|
}
|
||||||
|
|
||||||
interface ExtendedError extends Error {
|
interface ExtendedError extends Error {
|
||||||
data?: any
|
data?: any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ExtendedSocket {
|
||||||
|
encodedToken?: string
|
||||||
|
decodedToken?: any
|
||||||
|
}
|
||||||
|
|
||||||
type SocketIOMiddleware = (
|
type SocketIOMiddleware = (
|
||||||
socket: Socket,
|
socket: Socket,
|
||||||
next: (err?: ExtendedError) => void
|
next: (err?: ExtendedError) => void
|
||||||
@ -41,7 +50,7 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
// Store encoded JWT
|
// Store encoded JWT
|
||||||
socket = Object.assign(socket, { encodedToken: token })
|
socket.encodedToken = token
|
||||||
let payload: any
|
let payload: any
|
||||||
try {
|
try {
|
||||||
payload = jwt.verify(token, secret, { algorithms })
|
payload = jwt.verify(token, secret, { algorithms })
|
||||||
@ -53,7 +62,7 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
// Store decoded JWT
|
// Store decoded JWT
|
||||||
socket = Object.assign(socket, { decodedToken: payload })
|
socket.decodedToken = payload
|
||||||
return next()
|
return next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user