dpaw-monorail-plugin
Version:
JS library to link the brocket network to the QGIS/monorail server
107 lines (88 loc) • 2.77 kB
JavaScript
/**
* @fileOverview
* @name command.js
* @author Gavin Coombes
* @license BSD-3-Clause
*
* Dispatch commands to the QGIS-Monorail server
*/
let axios = require('axios');
let events = require('events');
let Rx = require('rx');
let u = require('dpaw-brocket-utility');
// Local Aliases
var log = u.log;
window.axios = axios;
var CommandModule = (function(){
let obj = Object.create(new events.EventEmitter());
obj.$type = "CommandModule";
return obj;
})();
var CommandObject = Object.create(CommandModule);
CommandObject.init = function init(opts){
log('Building command object *****************************');
let self = this;
self.opts = opts;
self.type = 'CommandObject';
self._port = opts.port || 30000;
self.baseAddress = opts.address || buildAddress(this._port);
self.fetchAddress = self.baseAddress + 'fetch';
self.interval = opts.interval || 10 * 1000;
};
CommandObject.port = function port(value) {
let self = this;
if (arguments.length) {
self._port = value;
self.address = buildAddress(self._port);
log('CommandObject.port: port now ', self._port);
} else {
return self._value;
}
};
CommandObject.fetch = function fetch(address) {
let self = this;
let promise = axios.get(self.fetchAddress)
.then( msg => log('Fetched urmap: ', msg.data))
.then(self.notify.bind(self));
// console.warn('Command.fetch: dummy fetch here');
// // let promise = axios.get('http://sso.dpaw.wa.gov.au/get_brocket_channel');
// let promise = {then: v => log('Dummy response is ', v)};
return promise;
};
CommandObject.command = function command(cmd) {
let self = this;
let {tag, payload} = cmd;
let params = `${tag}?${payload}`;
let address = self.baseAddress + params;
let promise = axios.post(address)
.then(self.notify.bind(self));
log('MonorailObject.command: Command is', cmd);
log('tag is ', tag);
log('payload is ', payload);
log('MonorailObject.command: Actual address is ' + address);
return promise;
};
CommandObject.run = function run() {
this.fetch(this.address)
.then(setTimeout(this.run.bind(this), this.interval));
};
CommandObject.notify = function notify(res) {
// let data = res.data;
this.emit('data', res);
};
function buildAddress(port) {
return `http://localhost:${port}/api/`;
}
function makeCommand(incoming$, opts) {
let c = Object.create(CommandObject);
let command$ = incoming$
.do(m => log('Command.makeCommand: prefilter msg is ', m))
.filter(m => true)
.do(m => log('Command.makeCommand: postfilter msg is ', m));
command$.subscribe(c.command.bind(c));
c.init(opts);
let outgoing$ = Rx.Observable.fromEvent(c, 'data');
c.run();
return outgoing$;
}
module.exports = makeCommand;