forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.ts
More file actions
69 lines (61 loc) · 1.71 KB
/
message.ts
File metadata and controls
69 lines (61 loc) · 1.71 KB
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
interface IRequestMessage<T> {
req: string;
command: string;
args: T;
}
interface IReplyMessage {
seq: string;
err: any;
res: any;
}
declare var acquireVsCodeApi: any;
export const vscode = acquireVsCodeApi();
export class MessageHandler {
private _commandHandler: ((message: any) => void) | null;
private lastSentReq: number;
private pendingReplies: any;
constructor(commandHandler: any) {
this._commandHandler = commandHandler;
this.lastSentReq = 0;
this.pendingReplies = Object.create(null);
window.addEventListener('message', this.handleMessage.bind(this));
}
public registerCommandHandler(commandHandler: (message: any) => void) {
this._commandHandler = commandHandler;
}
public async postMessage(message: any): Promise<any> {
let req = String(++this.lastSentReq);
return new Promise<any>((resolve, reject) => {
this.pendingReplies[req] = {
resolve: resolve,
reject: reject
};
message = Object.assign(message, {
req: req
});
vscode.postMessage(message as IRequestMessage<any>);
});
}
// handle message should resolve promises
private handleMessage(event: any) {
const message: IReplyMessage = event.data; // The json data that the extension sent
if (message.seq) {
// this is a reply
let pendingReply = this.pendingReplies[message.seq];
if (pendingReply) {
if (message.err) {
pendingReply.reject(message.err);
} else {
pendingReply.resolve(message.res);
}
return;
}
}
if (this._commandHandler) {
this._commandHandler(message.res);
}
}
}
export function getMessageHandler(handler: ((message: any) => void) | null) {
return new MessageHandler(handler);
}