@softcol/biometrics
Version:
Collection of utility methods for eLogic Biometrics
55 lines (43 loc) • 1.54 kB
text/typescript
import { EBiometricsEnvironment, EBiometricsMessage, EBiometricsState, MessageCode } from '../models';
import { EBM_WEBSOCKET_API_ENDPOINT_DEVELOPMENT, EBM_WEBSOCKET_API_ENDPOINT_PRODUCTION } from '../constants';
export class WebsocketService {
private _url: string;
private _room: string | undefined;
private _websocket: WebSocket | undefined;
constructor() {
this._url = EBM_WEBSOCKET_API_ENDPOINT_DEVELOPMENT;
}
private _configure(state: EBiometricsState): void {
this._room = state.id;
if (state.environment === EBiometricsEnvironment.production) {
this._url = EBM_WEBSOCKET_API_ENDPOINT_PRODUCTION;
}
}
private _processMessage(data: string, state: EBiometricsState): void {
const message: EBiometricsMessage = JSON.parse(data);
if (message.code === MessageCode.BIOMETRICS_RETRY) {
state.onRetry();
}
if (message.code === MessageCode.BIOMETRICS_ERROR) {
state.onError({ message: message.content });
}
if (message.code === MessageCode.BIOMETRICS_COMPLETED) {
state.onSuccess({ id: message.content });
}
}
connect(state: EBiometricsState): void {
this._configure(state);
this._websocket = new WebSocket(`${this._url}?room=${this._room}`);
this._websocket.onerror = () => {
this.connect(state);
};
this._websocket.onclose = () => {
this.connect(state);
}
this._websocket.onmessage = (event: any) => {
if (event && event.data) {
this._processMessage(event.data, state);
}
};
}
}