From 055216401836c1b7e6dd89b58f207b9741e9be35 Mon Sep 17 00:00:00 2001 From: didierfranc Date: Mon, 6 Jan 2025 14:54:47 +0100 Subject: [PATCH] feat: add unsubscribe --- README.md | 12 ++++++++---- src/sql.spec.ts | 15 +++++++++++++++ src/sqlite.ts | 10 ++++++++-- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 23b5b81..9445fca 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,14 @@ async function example() { const results = await db.exec('SELECT * FROM users'); console.log(results); - // Add callback for exec events - db.on('exec', (args) => { + // Add callback for exec events with unsubscribe + const unsubscribe = db.on('exec', (args) => { console.log('Query executed:', args[0]); console.log('Bindings:', args[1]); }); + + // Later unsubscribe when done + unsubscribe(); } ``` @@ -106,13 +109,14 @@ Executes an SQL query and returns the results as an array of objects. - `bind`: Optional binding parameters - **Returns:** Promise resolving to an array of row objects -##### `on(event: "exec", callback: (args: any[]) => void): void` +##### `on(event: "exec", callback: (args: any[]) => void): () => void` -Subscribes to database events. +Subscribes to database events and returns an unsubscribe function. - **Parameters:** - `event`: Event type ("exec") - `callback`: Function called when event occurs +- **Returns:** Function that when called will unsubscribe the callback ##### `export_db(): Promise` diff --git a/src/sql.spec.ts b/src/sql.spec.ts index f6250f5..b0a9692 100644 --- a/src/sql.spec.ts +++ b/src/sql.spec.ts @@ -2,6 +2,21 @@ import { describe, it, expect, vi } from "vitest"; import { SQLite } from "./sqlite"; describe("SQLite database operations", () => { + it("should test unsubscribe functionality", async () => { + const db = new SQLite(); + + const execCallback = vi.fn(); + const unsubscribe = db.on("exec", execCallback); + + await db.exec(`SELECT 1`); + expect(execCallback).toHaveBeenCalledTimes(1); + + unsubscribe(); + + await db.exec(`SELECT 2`); + expect(execCallback).toHaveBeenCalledTimes(1); + }); + it("should perform database operations and verify exports match", async () => { const db = new SQLite(); diff --git a/src/sqlite.ts b/src/sqlite.ts index 942b2ae..f181404 100644 --- a/src/sqlite.ts +++ b/src/sqlite.ts @@ -58,9 +58,15 @@ export class SQLite { }); } - on(event: "exec", callback: (args: Args) => void): void { + on(event: "exec", callback: (args: Args) => void): () => void { if (!this.callbacks[event]) this.callbacks[event] = []; - this.callbacks[event].push(callback); + const callbacks = this.callbacks[event]; + callbacks.push(callback); + + return () => { + const filtered = callbacks.filter((cb) => cb !== callback); + this.callbacks[event] = filtered; + }; } async export_db(): Promise {