diff options
| author | Melonai <einebeere@gmail.com> | 2021-05-31 01:47:38 +0200 |
|---|---|---|
| committer | Melonai <einebeere@gmail.com> | 2021-05-31 01:47:38 +0200 |
| commit | 8f1f90c3e7d836a23f1cd09617c2a0fcfac3f3f4 (patch) | |
| tree | 7359e054d13a054a661c1584dae20d0698fc4c84 /assets/src/network/channel/connection.ts | |
| parent | e0cabfea7c7b442acd3636e7495958b87e253176 (diff) | |
| download | rook-8f1f90c3e7d836a23f1cd09617c2a0fcfac3f3f4.tar.zst rook-8f1f90c3e7d836a23f1cd09617c2a0fcfac3f3f4.zip | |
Socket connection with managed state
Diffstat (limited to 'assets/src/network/channel/connection.ts')
| -rw-r--r-- | assets/src/network/channel/connection.ts | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/assets/src/network/channel/connection.ts b/assets/src/network/channel/connection.ts new file mode 100644 index 0000000..52d85d1 --- /dev/null +++ b/assets/src/network/channel/connection.ts @@ -0,0 +1,69 @@ +import { Channel, Push, Socket } from "phoenix"; +import { startRequest } from "./request"; +import { startShare } from "./share"; +import { connectSocket, fetchToken } from "./socket"; + +export enum Type { + NONE, + REQUEST, + SHARE, +} + +enum ConnectionState { + CONNECTING_SOCKET, + FETCHING_TOKEN, + CONNECTING_CHANNEL, + + CONNECTED, +} + +export type Connection = { + socket: Socket; + channel: Channel | null; + token: string | null; + state: ConnectionState; + type: Type; +}; + +const connection: Connection = { + socket: new Socket("/socket", {}), + channel: null, + token: null, + state: ConnectionState.CONNECTING_SOCKET, + type: Type.NONE, +}; + +export async function start(type: Type.REQUEST | Type.SHARE) { + connection.type = type; + + await connectSocket(connection.socket); + + updateState(ConnectionState.FETCHING_TOKEN); + connection.token = await fetchToken(connection.socket); + + updateState(ConnectionState.CONNECTING_CHANNEL); + type === Type.SHARE + ? await startShare(connection) + : await startRequest(connection); +} + +export function send(event: string, data: any): Push { + if (connection.state !== ConnectionState.CONNECTED) { + throw new Error("There is no connection yet."); + } + + return connection.channel.push(event, data); +} + +export function getOwnToken(): string { + if (connection.state <= ConnectionState.FETCHING_TOKEN) { + throw new Error("There is no token yet."); + } + + return connection.token; +} + +function updateState(state: ConnectionState) { + // TODO: Notify state listeners + connection.state = state; +} |
