94 lines
2.6 KiB
TypeScript
94 lines
2.6 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import Auth from '@aws-amplify/auth';
|
|
import { WebSocketSubject } from 'rxjs/webSocket';
|
|
import { Observable, Subject } from 'rxjs';
|
|
export interface MyJSON {
|
|
[key: string]: any;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
|
|
|
|
export class DataService {
|
|
public serverMessages: Array<MyJSON> = [];
|
|
public message = new Subject<MyJSON[]>();
|
|
private socket$: WebSocketSubject<any>;
|
|
totalFlowRate = 0;
|
|
private roles: string[];
|
|
private groups: string[];
|
|
private currentRole: string;
|
|
private token: string;
|
|
|
|
constructor() {
|
|
Auth.currentAuthenticatedUser().then(data => {
|
|
// console.log(data);
|
|
this.roles = data.signInUserSession.idToken.payload['cognito:roles'];
|
|
this.groups = data.signInUserSession.idToken.payload['cognito:groups'];
|
|
this.groups.forEach( (element, index, array) => {
|
|
array[index] = element.replace(/_/g, ' ');
|
|
});
|
|
this.currentRole = data.signInUserSession.idToken.payload['cognito:roles'][0];
|
|
this.token = data.signInUserSession.accessToken.jwtToken;
|
|
this.message.subscribe({
|
|
next: d => d
|
|
});
|
|
this.connect();
|
|
}); }
|
|
|
|
connect() {
|
|
this.connectWS(this.token, this.currentRole);
|
|
this.subscribeWS();
|
|
this.socket$.next({action: 'getDashboardData', policy: this.currentRole});
|
|
}
|
|
|
|
connectWS(token: string, role: string) {
|
|
this.socket$ = new WebSocketSubject('wss://3fseaywb8b.execute-api.us-east-1.amazonaws.com/prototype?token=' + token +
|
|
'&role=' + role);
|
|
// console.log(this.socket$);
|
|
}
|
|
|
|
subscribeWS() {
|
|
this.socket$.subscribe((message) => {
|
|
// console.log(message);
|
|
if (message instanceof Array) {
|
|
message.forEach(element => {
|
|
this.updateList(element);
|
|
});
|
|
} else {
|
|
this.updateList(message);
|
|
}
|
|
// console.log(this.serverMessages);
|
|
this.serverMessages.sort((a, b) => a.location.localeCompare(b.location));
|
|
this.message.next(this.serverMessages);
|
|
},
|
|
(err) => console.error(err),
|
|
() => console.warn('Complete: Websocket closed')
|
|
);
|
|
}
|
|
|
|
updateList(obj: MyJSON) {
|
|
// console.log(this.serverMessages);
|
|
// console.log(obj);
|
|
const index = this.serverMessages.findIndex((e) => e.location === obj.location);
|
|
|
|
if (index === -1) {
|
|
this.serverMessages.push(obj);
|
|
|
|
} else {
|
|
Object.keys(obj).forEach(element => {
|
|
this.serverMessages[index][element] = obj[element];
|
|
});
|
|
}
|
|
}
|
|
|
|
setRole(index: number) {
|
|
this.currentRole = this.roles[index];
|
|
this.socket$.complete();
|
|
this.serverMessages = [];
|
|
this.connect();
|
|
}
|
|
|
|
}
|