diff options
| author | Melonai <einebeere@gmail.com> | 2021-06-03 02:10:52 +0200 |
|---|---|---|
| committer | Melonai <einebeere@gmail.com> | 2021-06-03 02:10:52 +0200 |
| commit | 1348f3402c9c15c37501c7cf48f6c63ae7f8c1d8 (patch) | |
| tree | 991147a82958413ed7a5c4a30ce6861bbdabb918 /assets/src/network/channel/connection.ts | |
| parent | 6f7ce856f784dce0952db2272a85ee70e6e1b159 (diff) | |
| download | rook-1348f3402c9c15c37501c7cf48f6c63ae7f8c1d8.tar.zst rook-1348f3402c9c15c37501c7cf48f6c63ae7f8c1d8.zip | |
Dynamic event handling architecture
Diffstat (limited to 'assets/src/network/channel/connection.ts')
| -rw-r--r-- | assets/src/network/channel/connection.ts | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/assets/src/network/channel/connection.ts b/assets/src/network/channel/connection.ts index 52d85d1..6d6f3de 100644 --- a/assets/src/network/channel/connection.ts +++ b/assets/src/network/channel/connection.ts @@ -1,4 +1,11 @@ import { Channel, Push, Socket } from "phoenix"; +import { + Handler, + Handlers, + registerTokenHandler, + UnregisterHandler, +} from "./messages/handler"; +import type { AnyMessage } from "./messages/messages"; import { startRequest } from "./request"; import { startShare } from "./share"; import { connectSocket, fetchToken } from "./socket"; @@ -22,6 +29,7 @@ export type Connection = { channel: Channel | null; token: string | null; state: ConnectionState; + handlers: Handlers; type: Type; }; @@ -30,6 +38,7 @@ const connection: Connection = { channel: null, token: null, state: ConnectionState.CONNECTING_SOCKET, + handlers: {}, type: Type.NONE, }; @@ -55,6 +64,21 @@ export function send(event: string, data: any): Push { return connection.channel.push(event, data); } +export function onWithToken<Message extends AnyMessage>( + event: string, + token: string | null, + handler: Handler<Message> +): UnregisterHandler { + return registerTokenHandler(connection.handlers, event, token, handler); +} + +export function on<Message extends AnyMessage>( + event: string, + handler: Handler<Message> +): UnregisterHandler { + return onWithToken(event, null, handler); +} + export function getOwnToken(): string { if (connection.state <= ConnectionState.FETCHING_TOKEN) { throw new Error("There is no token yet."); @@ -63,6 +87,14 @@ export function getOwnToken(): string { return connection.token; } +export function getChannel(): Channel { + if (connection.state <= ConnectionState.FETCHING_TOKEN) { + throw new Error("There is no channel yet."); + } + + return connection.channel; +} + function updateState(state: ConnectionState) { // TODO: Notify state listeners connection.state = state; |
