forked from awesome-fc/webserverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.ts
64 lines (50 loc) · 1.76 KB
/
writer.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
import { Message } from 'vscode-jsonrpc/lib/messages';
import { } from 'vscode-jsonrpc/lib/messageWriter';
import { Channel } from './channel';
import { Emitter, Event } from 'vscode-jsonrpc/lib/events';
export abstract class AbstractMessageWriter {
private errorEmitter: Emitter<[Error, Message | undefined, number | undefined]>;
private closeEmitter: Emitter<void>;
constructor() {
this.errorEmitter = new Emitter<[Error, Message, number]>();
this.closeEmitter = new Emitter<void>();
}
public dispose(): void {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
public get onError(): Event<[Error, Message | undefined, number | undefined]> {
return this.errorEmitter.event;
}
protected fireError(error: any, message?: Message, count?: number): void {
this.errorEmitter.fire([this.asError(error), message, count]);
}
public get onClose(): Event<void> {
return this.closeEmitter.event;
}
protected fireClose(): void {
this.closeEmitter.fire(undefined);
}
private asError(error: any): Error {
if (error instanceof Error) {
return error;
} else {
return new Error(`Writer received error. Reason: ${typeof error.message === 'string' ? error.message : 'unknown'}`);
}
}
}
export class ChannelMessageWriter extends AbstractMessageWriter {
protected errorCount = 0;
constructor(protected readonly channel: Channel) {
super();
}
write(msg: Message): void {
try {
const content = JSON.stringify(msg);
this.channel.send(content);
} catch (e) {
this.errorCount++;
this.fireError(e, msg, this.errorCount);
}
}
}