-
Notifications
You must be signed in to change notification settings - Fork 91
/
RawWebsocketMessage.ts
61 lines (48 loc) · 1.96 KB
/
RawWebsocketMessage.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
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import { MessageType } from "./ConnectionMessage.js";
import { ArgumentNullError, InvalidOperationError } from "./Error.js";
import { createNoDashGuid } from "./Guid.js";
export class RawWebsocketMessage {
private privMessageType: MessageType;
private privPayload: any = null;
private privId: string;
public constructor(messageType: MessageType, payload: any, id?: string) {
if (!payload) {
throw new ArgumentNullError("payload");
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (messageType === MessageType.Binary && payload.__proto__.constructor.name !== "ArrayBuffer") {
throw new InvalidOperationError("Payload must be ArrayBuffer");
}
if (messageType === MessageType.Text && !(typeof (payload) === "string")) {
throw new InvalidOperationError("Payload must be a string");
}
this.privMessageType = messageType;
this.privPayload = payload;
this.privId = id ? id : createNoDashGuid();
}
public get messageType(): MessageType {
return this.privMessageType;
}
public get payload(): any {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.privPayload;
}
public get textContent(): string {
if (this.privMessageType === MessageType.Binary) {
throw new InvalidOperationError("Not supported for binary message");
}
return this.privPayload as string;
}
public get binaryContent(): ArrayBuffer {
if (this.privMessageType === MessageType.Text) {
throw new InvalidOperationError("Not supported for text message");
}
return this.privPayload as ArrayBuffer;
}
public get id(): string {
return this.privId;
}
}