|
| 1 | +import { Injectable } from "@angular/core"; |
| 2 | +import { HttpInfo } from "./http-info"; |
| 3 | +import { LoggerType, EventType, CommonResponse } from "../dtos"; |
| 4 | +import { HttpClient } from "@angular/common/http"; |
| 5 | + |
| 6 | +export interface NotifyPayload { |
| 7 | + logType: number; |
| 8 | + projectName: string; |
| 9 | + text: string; |
| 10 | + type: number; |
| 11 | +} |
| 12 | + |
| 13 | +export interface LoggerPayload { |
| 14 | + type: LoggerType; |
| 15 | + content: string; |
| 16 | +} |
| 17 | + |
| 18 | +export interface TaskPayload { |
| 19 | + name: string; |
| 20 | + time: number; |
| 21 | + projectName: string; |
| 22 | +} |
| 23 | + |
| 24 | +const NOTIFY_CLASS_TYPE = [ |
| 25 | + "notify-error", |
| 26 | + "notify-info", |
| 27 | + "notify-success", |
| 28 | + "notify-warning" |
| 29 | +]; |
| 30 | + |
| 31 | +@Injectable() |
| 32 | +export class WebSocketService { |
| 33 | + private conn: WebSocket; |
| 34 | + |
| 35 | + notifications: NotifyPayload[] = []; |
| 36 | + loggers: LoggerPayload[] = []; |
| 37 | + tasks: TaskPayload[] = []; |
| 38 | + |
| 39 | + constructor(private httpInfo: HttpInfo, private httpClient: HttpClient) { |
| 40 | + const conn = new WebSocket(this.httpInfo.path("/notify/", "ws")); |
| 41 | + httpClient |
| 42 | + .get<CommonResponse<TaskPayload[]>>(this.httpInfo.path("/task/all")) |
| 43 | + .subscribe(({ data }) => (this.tasks = data)); |
| 44 | + |
| 45 | + this.conn = conn; |
| 46 | + conn.onopen = this.handleConnect; |
| 47 | + conn.onclose = this.handleClose; |
| 48 | + conn.onmessage = ws => this.handleMessage(ws) as any; |
| 49 | + } |
| 50 | + |
| 51 | + private handleConnect() { |
| 52 | + console.info("connect success"); |
| 53 | + } |
| 54 | + |
| 55 | + private handleClose() { |
| 56 | + console.info("closed"); |
| 57 | + } |
| 58 | + |
| 59 | + private handleMessage(ws: MessageEvent) { |
| 60 | + const { type, payload } = JSON.parse(ws.data); |
| 61 | + |
| 62 | + if (type === EventType.TASK) { |
| 63 | + this.tasks = payload; |
| 64 | + |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + const CONTAINER_MAP = { |
| 69 | + [EventType.LOGGER]: this.loggers, |
| 70 | + [EventType.NOTIFY]: this.notifications |
| 71 | + }; |
| 72 | + const container = CONTAINER_MAP[type]; |
| 73 | + let result = payload; |
| 74 | + |
| 75 | + if (type === EventType.NOTIFY) { |
| 76 | + result.type = NOTIFY_CLASS_TYPE[payload.type]; |
| 77 | + } |
| 78 | + |
| 79 | + container.push(result); |
| 80 | + } |
| 81 | +} |
0 commit comments