-
Notifications
You must be signed in to change notification settings - Fork 132
/
DefaultChannel.ts
78 lines (65 loc) · 2.91 KB
/
DefaultChannel.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
70
71
72
73
74
75
76
77
import { ContextHandler, DisplayMetadata, Listener, Channel } from "@kite9/fdc3-standard"
import { Context } from "@kite9/fdc3-context";
import { Messaging } from "../Messaging"
import { DefaultContextListener } from "../listeners/DefaultContextListener"
import { BrowserTypes } from "@kite9/fdc3-schema"
type BroadcastRequest = BrowserTypes.BroadcastRequest
type BroadcastResponse = BrowserTypes.BroadcastResponse
type GetCurrentContextResponse = BrowserTypes.GetCurrentContextResponse
type GetCurrentContextRequest = BrowserTypes.GetCurrentContextRequest
export class DefaultChannel implements Channel {
readonly messaging: Messaging
readonly id: string
readonly type: "user" | "app" | "private"
readonly displayMetadata?: DisplayMetadata | undefined;
constructor(messaging: Messaging, id: string, type: "user" | "app" | "private", displayMetadata?: DisplayMetadata) {
this.messaging = messaging
this.id = id
this.type = type
this.displayMetadata = displayMetadata
}
async broadcast(context: Context): Promise<void> {
const done = await this.messaging.exchange<BroadcastResponse>({
meta: this.messaging.createMeta(),
payload: {
channelId: this.id,
context
},
type: "broadcastRequest"
} as BroadcastRequest, 'broadcastResponse')
console.log("broadcast done", done)
}
async getCurrentContext(contextType?: string | undefined): Promise<Context | null> {
// first, ensure channel state is up-to-date
const response = await this.messaging.exchange<GetCurrentContextResponse>({
meta: this.messaging.createMeta(),
payload: {
channelId: this.id,
contextType: contextType ?? null
},
type: "getCurrentContextRequest"
} as GetCurrentContextRequest, 'getCurrentContextResponse')
return response.payload.context ?? null
}
async addContextListener(contextType: any, handler?: ContextHandler): Promise<Listener> {
let theContextType: string | null
let theHandler: ContextHandler
if (contextType == null) {
theContextType = null;
theHandler = handler as ContextHandler;
} else if (typeof contextType === 'string') {
theContextType = contextType
theHandler = handler as ContextHandler;
} else {
// deprecated one-arg version
theContextType = null;
theHandler = contextType as ContextHandler;
}
return await this.addContextListenerInner(theContextType, theHandler);
}
async addContextListenerInner(contextType: string | null, theHandler: ContextHandler): Promise<Listener> {
const listener = new DefaultContextListener(this.messaging, this.id, contextType, theHandler);
await listener.register()
return listener
}
}