uci-socket/src/consumer.mjs

44 lines
1004 B
JavaScript

import { Socket } from 'net'
import btc from 'better-try-catch'
export default class Consumer extends Socket {
constructor (path, opts={}) {
super()
this.path = path
this.keepAlive = opts.keepAlive ? opts.keepAlive : true
}
async connect () {
console.log('attempting to connect to socket: ', this.path)
await super.connect({ path: this.path })
console.log(`connected to ${this.path}`)
this.setKeepAlive(this.keepAlive)
this.on('error', (error) => {
'client socket error \n ', error.code
})
}
async send(packet) {
let [err, strbuf] = btc(JSON.stringify)(packet)
if (!err) {
this.write(strbuf)
}
else { console.log(`bad packet JSON syntax \n ${packet}`)}
}
async listen (app) {
this.on('data', async (buf) => {
let [err, packet] = btc(JSON.parse)(buf.toString())
if (!err) {
app(packet)
}
else { console.log(`bad packet JSON syntax \n ${buf.toString()}`)}
})
}
} // end class