smartuniverse/ts/smartuniverse.classes.universeclient.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-03-13 05:15:40 +00:00
import * as plugins from './smartuniverse.plugins';
import { Observable } from 'rxjs';
2018-03-20 07:16:54 +00:00
import { Smartsocket, SmartsocketClient } from 'smartsocket';
import * as url from 'url';
import {
IServerGetMessagesRequestBody,
IServerPutMessageRequestBody
} from './smartuniverse.classes.universe';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
2018-03-13 05:15:40 +00:00
2018-03-15 00:05:13 +00:00
export interface IClientOptions {
2018-03-20 07:16:54 +00:00
serverAddress: string;
2018-03-15 00:05:13 +00:00
}
2018-04-13 13:45:48 +00:00
/**
* this class is for client side only!!!
* allows connecting to a universe server
*/
2018-03-13 05:15:40 +00:00
export class UniverseClient {
2018-03-15 00:05:13 +00:00
public options;
2018-03-20 07:16:54 +00:00
private socketClient: plugins.smartsocket.SmartsocketClient;
private observableIntake: plugins.smartrx.ObservableIntake<UniverseMessage>;
2018-03-13 05:15:40 +00:00
2018-03-15 00:05:13 +00:00
constructor(optionsArg: IClientOptions) {
this.options = optionsArg;
}
2018-03-20 07:16:54 +00:00
2018-03-15 00:16:16 +00:00
public async sendMessage(messageArg, payloadArg) {
const requestBody = {
message: messageArg,
payload: payloadArg
2018-03-20 07:16:54 +00:00
};
2018-04-13 13:45:48 +00:00
// TODO: User websocket connection if available
2018-03-15 00:16:16 +00:00
await plugins.smartrequest.post(this.options.serverAddress, {
2018-03-20 07:16:54 +00:00
requestBody
});
2018-03-13 05:15:40 +00:00
}
2018-04-13 13:45:48 +00:00
2018-03-20 07:16:54 +00:00
public getMessageObservable() {
if (!this.socketClient && !this.observableIntake) {
const parsedURL = url.parse(this.options.serverAddress);
this.socketClient = new SmartsocketClient({
alias: process.env.SOCKET_ALIAS || 'someclient',
password: 'UniverseClient',
port: parseInt(parsedURL.port, 10),
role: 'UniverseClient',
2018-04-13 13:45:48 +00:00
url: parsedURL.hostname
2018-03-20 07:16:54 +00:00
});
this.observableIntake = new plugins.smartrx.ObservableIntake();
this.socketClient.connect();
}
return this.observableIntake.observable;
2018-03-13 05:15:40 +00:00
}
2018-04-13 13:45:48 +00:00
public close() {
this.socketClient.disconnect();
}
2018-03-15 00:05:13 +00:00
}