update to be a class

This commit is contained in:
2026-04-08 14:53:48 -05:00
parent 7e956ccf2b
commit 555fa1e220
2 changed files with 49 additions and 44 deletions
+31 -26
View File
@@ -1,15 +1,16 @@
const subscribedQueries = new Map<string, (data: any) => void>(); export class TetherClient {
let ws: WebSocket | null = null; private ws: WebSocket | null = null;
private subscribedQueries = new Map<string, (data: any) => void>();
export const connect = async (url: string): Promise<WebSocket> => { connect = (url: string) => {
ws = new WebSocket(url); this.ws = new WebSocket(url);
ws.onopen = () => { this.ws.onopen = () => {
console.log('Connected to Tether'); console.log('Connected to Tether');
}; };
ws.onmessage = (event) => { this.ws.onmessage = (event) => {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
if (data.type === 'query') { if (data.type === 'query') {
subscribedQueries.forEach((callback, query) => { this.subscribedQueries.forEach((callback, query) => {
if (data.query === query) { if (data.query === query) {
callback(data.data); callback(data.data);
} }
@@ -18,31 +19,35 @@ export const connect = async (url: string): Promise<WebSocket> => {
console.error(data.error); console.error(data.error);
} }
}; };
ws.onclose = () => { this.ws.onclose = () => {
console.log('Disconnected from Tether'); console.log('Disconnected from Tether');
}; };
return ws; };
};
export const disconnect = (ws: WebSocket) => { disconnect = () => {
ws.close(); if (!this.ws) {
};
export const subscribe = (query: string, callback: (data: any) => void) => {
subscribedQueries.set(query, callback);
};
export const unsubscribe = (query: string) => {
subscribedQueries.delete(query);
};
export const sendMutation = (mutationName: string, params: any) => {
if (!ws) {
throw new Error('Not connected to Tether'); throw new Error('Not connected to Tether');
} }
ws.send(JSON.stringify({ this.ws.close();
this.ws = null;
};
subscribe = (query: string, callback: (data: any) => void) => {
this.subscribedQueries.set(query, callback);
};
unsubscribe = (query: string) => {
this.subscribedQueries.delete(query);
};
sendMutation = (mutationName: string, params: any) => {
if (!this.ws) {
throw new Error('Not connected to Tether');
}
this.ws.send(JSON.stringify({
type: 'mutation', type: 'mutation',
name: mutationName, name: mutationName,
payload: params, payload: params,
})); }));
}; };
}
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "tether-ts", "name": "tether-ts",
"version": "1.0.0", "version": "1.0.1",
"description": "TypeScript client for Tether", "description": "TypeScript client for Tether",
"license": "ISC", "license": "ISC",
"author": "wisplite", "author": "wisplite",