Skip to content

Commit

Permalink
fix: New ws version, uses buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
KararTY committed Apr 15, 2022
1 parent 4a20321 commit 6659da8
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/Ws.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import sjp from 'secure-json-parse'
import { Logger } from '@adonisjs/logger'
import { schema } from '@adonisjs/validator/build/src/Schema'
import { validator } from '@adonisjs/validator/build/src/Validator'
import { MessageType } from 'befriendlier-shared'
import { EventEmitter } from 'events'
import sjp from 'secure-json-parse'
import WS from 'ws'
import WSConfig from '../config/Ws'

Expand Down Expand Up @@ -32,7 +32,7 @@ export default class Bot {
this.eventEmitter = new EventEmitter()
}

public connect () {
public connect (): void {
if (this.client !== undefined) {
this.client.removeAllListeners()
}
Expand All @@ -46,7 +46,7 @@ export default class Bot {
this.client.on('error', (err) => this.onError(err))
}

public sendMessage (type: MessageType, data: string) {
public sendMessage (type: MessageType, data: string): void {
if (this.client.readyState === 0 || this.client.readyState > 1) {
this.eventEmitter.emit('WS.CLOSED', { type, data, state: this.client.readyState })
return
Expand All @@ -55,19 +55,20 @@ export default class Bot {
this.client.send(this.socketMessage(type, data))
}

private onOpen () {
private onOpen (): void {
this.logger.info(`Ws.onOpen() ${prettySocketInfo(this.url)}`)
this.eventEmitter.emit('WS.OPEN')
this.reconnectAttempts = 0
}

private onMessage (data: WS.Data) {
this.logger.debug(`Ws.onMessage() ${prettySocketInfo(this.url)}: %O`, data)
private onMessage (data: WS.RawData): void {
const bufToStr = String(data) // TODO: This is ugly, can't I do it another way?
this.logger.debug(`Ws.onMessage() ${prettySocketInfo(this.url)}: %O`, bufToStr)

let json

try {
json = sjp.parse(data as string, null, { protoAction: 'remove' })
json = sjp.parse(bufToStr, null, { protoAction: 'remove' })
} catch (error) {
this.logger.error({ err: error }, 'Ws.onMessage(): Error with parsing websocket data.')
// Data's not JSON.
Expand All @@ -79,18 +80,19 @@ export default class Bot {
schema: this.validationSchema,
data: json,
messages: {
type: 'Invalid type.',
type: 'Invalid type.'
},
cacheKey: 'websocket',
cacheKey: 'websocket'
}).then(async (res: WsRes) => {
this.eventEmitter.emit('WS.MESSAGE', res)
}).catch((error: Error) => {
this.logger.error({ err: error }, 'Ws.onMessage()')
})
}

private onClose (code: number, reason: string) {
this.logger.error(`Ws.onClose() ${prettySocketInfo(this.url)}: code: ${code}${reason.length > 0 ? `, reason:\n${reason}` : ''}`)
private onClose (code: number, reason: Buffer): void {
const bufToStr = String(reason)
this.logger.error(`Ws.onClose() ${prettySocketInfo(this.url)}: code: ${code}${bufToStr.length > 0 ? `, reason:\n${bufToStr}` : ''}`)

this.reconnectAttempts++

Expand All @@ -103,25 +105,25 @@ export default class Bot {
}, timeSeconds * 1000)
}

private onPing (data: Buffer) {
private onPing (data: Buffer): void {
this.logger.debug(`Ws.onPing() ${prettySocketInfo(this.url)}${data.length > 0 ? `: ${data.toString()}` : ''}`)
}

private onError (error: Error) {
private onError (error: Error): void {
this.logger.error({ err: error }, `Ws.onError() ${prettySocketInfo(this.url)}`)
}

private socketMessage (type: MessageType, data: string) {
private socketMessage (type: MessageType, data: string): string {
return JSON.stringify({ type: type, data: data, timestamp: Date.now() })
}

private readonly validationSchema = schema.create({
type: schema.enum(Object.values(MessageType)),
data: schema.string.optional(),
timestamp: schema.number(),
timestamp: schema.number()
})
}

function prettySocketInfo (url: string) {
function prettySocketInfo (url: string): string {
return `[${url}]`
}

0 comments on commit 6659da8

Please sign in to comment.