ncoded-server-socket
v1.0.1
Published
SocketService implementation for managing socket connections with authorization, tracking online users and tab overtaking
Downloads
8
Keywords
Readme
Ncoded server socket library
Install
yarn add ncoded-server-socket
Usage
Create http server and start socket server using it:
import http from 'http'
import { startSocketSever, closeSocketSever } from 'ncoded-server-socket'
const server = http.createServer()
server.listen(3000, () => {
console.log('Http started on port 3000')
// for cors options, pass same origin as to 'cors' package
startSocketSever(server, '*')
// close socket and http server after 10 seconds
setTimeout(async () => {
await closeSocketSever()
server.close()
}, 10000)
})
Create socket service classes that extend SocketService
import { SocketService } from 'ncoded-server-socket'
type EventNamesType = 'hello' | 'hello:success'
class UserSocketService extends SocketService<EventNamesType> {
constructor() {
super('/users', { tabOvertaking: true })
}
async init() {
await this.initialize({
// if not sent, socketClient.id is used for identification
// payload is data sent from FE, most of the time its JWT
onAuth: (payload: any, socketClient) => {
// So you can use it later
socketClient.metadata = {
name: 'User',
id: '123'
}
return '123'
},
initHandlers: (socketClient) => {
this.sendEventToUser('123', 'hello')
socketClient.on('hello:success', () => {
console.log('Received hello')
})
},
joinRooms(socketClient) {
socketClient.join('user-room-123')
},
})
this.initializeOnlineTracking({
// when we receive heartbeat from user
trackUser: (user) => {
console.log(`${user.id}-alive`) // '123-alive'
},
})
}
}