Files
doneit-web/src/app/services/socket/interface/socket-interface.service.ts
T

86 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-01-07 09:03:15 +01:00
import { Injectable } from '@angular/core';
2022-01-07 14:29:41 +01:00
import { v4 as uuidv4 } from 'uuid';
2022-01-07 09:03:15 +01:00
@Injectable({
providedIn: 'root'
})
export class SocketInterfaceService {
private socket!: WebSocket;
private url = ''
private connected = false
private callBacks: {
2022-01-07 11:21:14 +01:00
type: 'Offline' | 'Online' | 'Open' ,
2022-01-07 09:03:15 +01:00
object?: string
funx: Function
}[] = []
2022-01-07 14:29:41 +01:00
private msgQueue : {
message: object,
requestId: string
}[] = []
private msgQueueIds = []
private disconnect: Function
2022-01-07 09:03:15 +01:00
constructor() { }
2022-01-07 11:21:14 +01:00
registerCallback(type: 'Offline' | 'Online' | 'Open', funx: Function, object = '') {
this.callBacks.push({
type,
funx,
object
})
}
2022-01-07 09:03:15 +01:00
connect(url) {
this.url = url
this.socket = new WebSocket(this.url);
// bind function
this.socket.onopen = this.onopen;
this.socket.onmessage = this.onmessage;
this.socket.onclose = this.onclose;
this.socket.onerror = this.onerror;
}
2022-01-07 11:21:14 +01:00
onopen() {
this.connected = true
// send all saved data due to internet connection
this.msgQueue.forEach((item, index, object) => {
2022-01-07 14:29:41 +01:00
this.send(item.message, item.requestId);
2022-01-07 11:21:14 +01:00
object.splice(index, 1);
2022-01-07 14:29:41 +01:00
this.msgQueueIds.slice(index, 1)
2022-01-07 11:21:14 +01:00
})
}
2022-01-07 14:29:41 +01:00
send(message: object, requestId = uuidv4()) {
2022-01-07 11:21:14 +01:00
if (this.connected === false) { // save data to send when back online
2022-01-07 14:29:41 +01:00
this.msgQueue.push({message, requestId})
this.msgQueueIds.push(requestId)
2022-01-07 09:03:15 +01:00
} else {
let messageStr = JSON.stringify(message)
this.socket.send(messageStr)
}
2022-01-07 14:29:41 +01:00
return requestId
2022-01-07 09:03:15 +01:00
}
2022-01-07 11:21:14 +01:00
onmessage(event: any) {
console.log('event.data', JSON.parse(event.data))
2022-01-07 09:03:15 +01:00
}
onclose(event: any) {
2022-01-07 11:21:14 +01:00
this.connected = false
2022-01-07 09:03:15 +01:00
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
setTimeout(()=>{
this.connect(this.url)
}, 500)
}
onerror = (event: any) => {
console.log(`[error] ${event.message}`);
}
}