import {ajax} from "rxjs/ajax"; import {delay, map, retryWhen, tap} from "rxjs/operators"; import {Observable, Subject} from "rxjs"; import {IrisMessage} from "./model/message"; import {IrisChannel, IrisConfig, IrisSimChannel} from "../index"; import {webSocket} from "rxjs/webSocket"; export interface IrisConnectApiType { createChannel(): Observable; getChannel(channelId: string): Observable; connectWithPhoneNumber(channel: IrisChannel, phoneNumber: string): Observable; websocket(channel: IrisChannel): Subject; websocketNV(channel: IrisChannel): Subject; deleteChannel(channel: IrisChannel): Observable; } interface CreateSessionResponse { sessionId: string; } export class IrisConnectApi implements IrisConnectApiType { private _config: IrisConfig; constructor(config: IrisConfig) { this._config = config; } public createChannel(): Observable { return ajax({ url: `${this._config.httpBase}/channels`, method: 'POST' }).pipe( map(response => { return { id: response.response.channelId, status: response.response.status } }) ) }; public getChannel(channelId: string): Observable { return ajax({ url: `${this._config.httpBase}/channels/${channelId}`, method: 'GET' }).pipe( map(response => { return { id: response.response.channelId, status: response.response.status } }) ) }; public deleteChannel(irisChannel: IrisChannel): Observable { return ajax({ url: `${this._config.httpBase}/channels/${irisChannel.id}`, method: 'DELETE' }).pipe( map(response => response.response as boolean) ) }; public connectWithPhoneNumber(irisChannel: IrisChannel, phoneNumber: string): Observable { return ajax({ url: `${this._config.httpBase}/channels/${irisChannel.id}?phoneNumber=${phoneNumber}`, method: 'PUT' }).pipe( map(response => response.response as IrisSimChannel) ) }; public websocket(irisChannel: IrisChannel): Subject { const ws = webSocket({ url: `${this._config.websocketBase}/connect/application/${irisChannel.id}` }); ws.subscribe( msg => console.log('message received: ' + msg), err => { console.log(err); this.websocket(irisChannel)}, () => console.log('complete') ); return ws; }; public websocketNV(irisChannel: IrisChannel): Subject { const ws = webSocket({ url: `${this._config.websocketBase}/connect/application/${irisChannel.id}` }); ws.pipe( retryWhen(errors => errors.pipe( tap(err => { console.error(`[${irisChannel.id}] error`, err); }), delay(1000) ) ) ).subscribe( msg => console.log(`[${irisChannel.id}] msg received`), err => console.error(`[${irisChannel.id}] error`, err), () => console.log(`[${irisChannel.id}] complete`) ); return ws; }; }