Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

t3MobileClient.ts

60 lines2.2 KB

1import {
2 OrchestrationEvent,
3 OrchestrationReadModel,
4 ORCHESTRATION_WS_CHANNELS,
5 ORCHESTRATION_WS_METHODS,
6 WS_CHANNELS,
7 WsWelcomePayload,
8} from "@t3tools/contracts";
9import { Cause, Schema } from "effect";
10​
11import { buildSocketUrl, type BackendProfile } from "./backendProfiles";
12import { type TransportStatus, WsTransport } from "./wsTransport";
13​
14const decodeWelcomePayload = Schema.decodeUnknownExit(WsWelcomePayload);
15const decodeOrchestrationEvent = Schema.decodeUnknownExit(OrchestrationEvent);
16const decodeOrchestrationReadModel = Schema.decodeUnknownExit(OrchestrationReadModel);
17​
18export class T3MobileClient {
19 private readonly transport: WsTransport;
20​
21 constructor(options: {
22 readonly profile: Pick<BackendProfile, "url" | "authToken">;
23 readonly onStatus?: (status: TransportStatus) => void;
24 }) {
25 this.transport = new WsTransport(buildSocketUrl(options.profile), options.onStatus);
26 }
27​
28 getSnapshot = async (): Promise<typeof OrchestrationReadModel.Type> => {
29 const raw = await this.transport.request(ORCHESTRATION_WS_METHODS.getSnapshot);
30 const decoded = decodeOrchestrationReadModel(raw);
31 if (decoded._tag === "Failure") {
32 throw new Error(`Invalid orchestration snapshot payload: ${Cause.pretty(decoded.cause)}`);
33 }
34 return decoded.value;
35 };
36​
37 onWelcome = (callback: (payload: typeof WsWelcomePayload.Type) => void): (() => void) =>
38 this.transport.subscribe(WS_CHANNELS.serverWelcome, (data) => {
39 const decoded = decodeWelcomePayload(data);
40 if (decoded._tag === "Failure") {
41 console.warn("Dropped server welcome payload", { issue: Cause.pretty(decoded.cause) });
42 return;
43 }
44 callback(decoded.value);
45 });
46​
47 onDomainEvent = (callback: (event: typeof OrchestrationEvent.Type) => void): (() => void) =>
48 this.transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (data) => {
49 const decoded = decodeOrchestrationEvent(data);
50 if (decoded._tag === "Failure") {
51 console.warn("Dropped orchestration domain event", { issue: Cause.pretty(decoded.cause) });
52 return;
53 }
54 callback(decoded.value);
55 });
56​
57 dispose(): void {
58 this.transport.dispose();
59 }