This repository was archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathConnectionMessage.ts
69 lines (53 loc) · 1.72 KB
/
ConnectionMessage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { InvalidOperationError } from "./Error";
import { CreateNoDashGuid } from "./Guid";
import { IStringDictionary } from "./IDictionary";
export enum MessageType {
Text,
Binary,
}
export class ConnectionMessage {
private messageType: MessageType;
private headers: IStringDictionary<string>;
private body: any = null;
private id: string;
public constructor(
messageType: MessageType,
body: any,
headers?: IStringDictionary<string>,
id?: string) {
if (messageType === MessageType.Text && body && !(typeof (body) === "string")) {
throw new InvalidOperationError("Payload must be a string");
}
if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) {
throw new InvalidOperationError("Payload must be ArrayBuffer");
}
this.messageType = messageType;
this.body = body;
this.headers = headers ? headers : {};
this.id = id ? id : CreateNoDashGuid();
}
public get MessageType(): MessageType {
return this.messageType;
}
public get Headers(): any {
return this.headers;
}
public get Body(): any {
return this.body;
}
public get TextBody(): string {
if (this.messageType === MessageType.Binary) {
throw new InvalidOperationError("Not supported for binary message");
}
return this.body as string;
}
public get BinaryBody(): ArrayBuffer {
if (this.messageType === MessageType.Text) {
throw new InvalidOperationError("Not supported for text message");
}
return this.body;
}
public get Id(): string {
return this.id;
}
}