smartuniverse/ts/smartuniverse.classes.clientuniverse.ts

74 lines
2.0 KiB
TypeScript
Raw Normal View History

2018-03-13 05:15:40 +00:00
import * as plugins from './smartuniverse.plugins';
2019-01-31 01:52:18 +00:00
import { Objectmap } from '@pushrocks/lik';
2018-03-13 05:15:40 +00:00
import { Observable } from 'rxjs';
2019-01-31 01:52:18 +00:00
import { Smartsocket, SmartsocketClient } from '@pushrocks/smartsocket';
2018-03-20 07:16:54 +00:00
import * as url from 'url';
2019-04-11 15:52:01 +00:00
import * as interfaces from './interfaces';
2018-03-20 07:16:54 +00:00
import {
ClientUniverseChannel,
UniverseMessage
} from './';
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
*/
export class ClientUniverse {
2018-03-15 00:05:13 +00:00
public options;
public socketClient: plugins.smartsocket.SmartsocketClient;
public observableIntake: plugins.smartrx.ObservableIntake<UniverseMessage>;
public channelCache = new Objectmap<ClientUniverseChannel>();
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
2019-01-31 01:52:18 +00:00
await plugins.smartrequest.postJson(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
public async getChannel(channelName: string): Promise<ClientUniverseChannel> {
await this.checkConnection();
const clientUniverseChannel = await ClientUniverseChannel.createClientUniverseChannel(
this,
channelName
);
this.channelCache.add(clientUniverseChannel);
return clientUniverseChannel;
}
public close() {
this.socketClient.disconnect();
}
private async checkConnection() {
2018-03-20 07:16:54 +00:00
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();
}
}
2018-03-15 00:05:13 +00:00
}