uci-base/examples/four-in-one.mjs

94 lines
2.4 KiB
JavaScript

import Base from '../src/base'
const USOCKET = __dirname + '/sample.sock'
const basefuncs = {
write: function(packet){
packet.cmd='log'
packet.response='return of write command'
return packet
},
write2: function(packet){
packet.cmd='log'
packet.response='return of write2 command'
return packet
}
}
;
(async () => {
const delay = time => new Promise(res=>setTimeout(()=>res(),time))
// let app = new Base({com:'us,uc,ts,tc', id:'example', path: USOCKET, log:false})
let app = new Base({sockets:'uc,us,tc,ts', id:'example', log:false})
app.amendPacketProcessing(basefuncs)
await app.init()
app.amendPacketProcessing('tc',{
log: packet => {
console.log('==============Packet returned to TCP consumer==========')
console.dir(packet)
console.log('===========================')
}
})
app.registerPacketProcessor('ts',
async function (packet) {
packet.test = 'this went through custom tcp socket processor'
if (!packet.cmd) return {error: 'no command in packet', packet: packet }
if (this.context) if (this.context[packet.cmd]) return await this.context[packet.cmd].bind(this.context)(packet)
if (this[packet.cmd]) return await this[packet.cmd](packet)
return {error: 'no socket processing function supplied for command', packet: packet }
})
let packet = {}
console.log('=============sending============')
packet = {cmd:'echo', data:'some data to echo'}
await app.send('tc',packet)
app.registerPacketContext('ts',tcpfuncs)
packet = {cmd:'write', data:'data to write'}
await app.send(packet)
await delay(500)
app.amendPacketContext(
{write: function(packet){
packet.cmd='log'
packet.response='return of AMMEDED write command'
return packet
}}
)
await delay(500)
packet = {cmd:'write', data:'2ND data to write'}
await app.sendIPC(packet)
packet = {cmd:'write2', data:'data to write'}
await app.sendTCP(packet)
//
await delay(2000)
process.kill(process.pid, 'SIGTERM')
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
process.kill(process.pid, 'SIGTERM')
})
const tcpfuncs = {
write: function(packet){
packet.cmd='log'
packet.response='return of write command'
packet.via = 'tcp write'
return packet
},
write2: function(packet){
packet.cmd='log'
packet.response='return of write2 command'
packet.via = 'tcp write2'
return packet
}
}