Skip to content

Commit

Permalink
added unsubscribe method
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelpapineau committed Jan 2, 2024
1 parent e4068df commit 97ebc19
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
16 changes: 16 additions & 0 deletions examples/bun/unsubscribe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const ws = new WebSocket("ws://localhost:3000");

ws.onopen = () => {
console.log("connected");
ws.send(JSON.stringify({
method: "unsubscribe",
params: {
moduleHash: "0a363b2a63aadb76a525208f1973531d3616fbae"
}
}));
};

ws.onmessage = (event) => {
console.log(`Message from server: ${event.data}`);
};

1 change: 1 addition & 0 deletions src/websocket/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export {default as ping} from "./ping.js"
export {default as time} from "./time.js"
export {default as subscribe} from "./subscribe.js"
export {default as unsubscribe} from "./unsubscribe.js"
export {default as open} from "./open.js"
export {default as close} from "./close.js"
export {default as message} from "./message.js"
Expand Down
2 changes: 2 additions & 0 deletions src/websocket/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { parseMessage } from "./parseMessage.js";
import ping from "./ping.js";
import time from "./time.js";
import subscribe from "./subscribe.js";
import unsubscribe from "./unsubscribe.js";
import * as prometheus from "../prometheus.js";

export default function (ws: ServerWebSocket<ServerWebSocketData>, message: string|Buffer) {
Expand All @@ -15,6 +16,7 @@ export default function (ws: ServerWebSocket<ServerWebSocketData>, message: stri
if ( method === "ping" ) return ping(ws, id);
if ( method === "time" ) return time(ws, id);
if ( method === "subscribe" ) return subscribe(ws, params, id);
if ( method === "unsubscribe" ) return unsubscribe(ws, params, id);
} catch (e) {
// handle errors
logger.error(e);
Expand Down
22 changes: 22 additions & 0 deletions src/websocket/unsubscribe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ServerWebSocket } from "bun";
import { logger } from "../logger.js";
import { ServerWebSocketData, db } from "../../index.js";
import * as sqlite from "../sqlite.js";

export default function (ws: ServerWebSocket<ServerWebSocketData>, params: {[key: string]: any}, id?: string) {
const { chain, block } = params;
let { moduleHash } = params;

if ( block === true ) {
moduleHash = sqlite.selectAll(db, "moduleHash")[0].key;
}

const topic = chain ? `${chain}:${moduleHash}` : moduleHash;

if (ws.isSubscribed(topic)) {
ws.unsubscribe(topic)

}

logger.info('unsubscribed', {id, key: ws.data.key, remoteAddress: ws.remoteAddress});
}

0 comments on commit 97ebc19

Please sign in to comment.