You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
potato-launcher/extensions/pouchdb/connector.js

82 lines
1.9 KiB

import minimist from 'minimist'
import websocket from 'websocket'
import { v4 as uuidv4 } from 'uuid'
/**
* connector creating client and routing to handlers
*
* @author Björn Hase
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
* @link https://gitea.node001.net/HerrHase/potato-launcher.git
*
*/
class Connector {
/**
* getting
*
*
* @param {object} handlers
*
*/
constructor(handlers) {
this.handlers = handlers
// getting arguments
const argv = minimist(process.argv.slice(2))
this.NL_PORT = argv['nl-port']
this.NL_TOKEN = argv['nl-token']
this.NL_EXTID = argv['nl-extension-id']
// create socket connection for receive and send events
this.client = new websocket.w3cwebsocket(`ws://localhost:${this.NL_PORT}?extensionId=${this.NL_EXTID}`)
// add events for on message to
this.client.onmessage = (event) => {
this.handleMessage(event)
}
}
/**
* send to app
*
* @param {string} eventName
* @param {array} data
*
*/
send(eventName, data) {
this.client.send(JSON.stringify({
id: uuidv4(),
method: 'app.broadcast',
accessToken: this.NL_TOKEN,
data: {
event: eventName,
data: data
}
}))
}
/**
* handle messages from app
*
* @param {object} event
*
*/
handleMessage(event) {
if (typeof event.data === 'string') {
// parse message
const message = JSON.parse(event.data)
// if event is in handlers-object mapped call it
if (this.handlers.hasOwnProperty(message.event)) {
console.log(event.data)
this.handlers[message.event].call(null, this, message.data)
}
}
}
}
export default Connector