Skip to content

Commit 2b43e9f

Browse files
authored
Merge pull request #3 from agnosticeng/unsubscribe
feat: add unsubscribe
2 parents 3d91f19 + 0552164 commit 2b43e9f

File tree

3 files changed

+31
-6
lines changed

3 files changed

+31
-6
lines changed

README.md

+8-4
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,14 @@ async function example() {
5454
const results = await db.exec('SELECT * FROM users');
5555
console.log(results);
5656

57-
// Add callback for exec events
58-
db.on('exec', (args) => {
57+
// Add callback for exec events with unsubscribe
58+
const unsubscribe = db.on('exec', (args) => {
5959
console.log('Query executed:', args[0]);
6060
console.log('Bindings:', args[1]);
6161
});
62+
63+
// Later unsubscribe when done
64+
unsubscribe();
6265
}
6366
```
6467

@@ -106,13 +109,14 @@ Executes an SQL query and returns the results as an array of objects.
106109
- `bind`: Optional binding parameters
107110
- **Returns:** Promise resolving to an array of row objects
108111

109-
##### `on(event: "exec", callback: (args: any[]) => void): void`
112+
##### `on(event: "exec", callback: (args: any[]) => void): () => void`
110113

111-
Subscribes to database events.
114+
Subscribes to database events and returns an unsubscribe function.
112115

113116
- **Parameters:**
114117
- `event`: Event type ("exec")
115118
- `callback`: Function called when event occurs
119+
- **Returns:** Function that when called will unsubscribe the callback
116120

117121
##### `export_db(): Promise<Uint8Array>`
118122

src/sql.spec.ts

+15
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,21 @@ import { describe, it, expect, vi } from "vitest";
22
import { SQLite } from "./sqlite";
33

44
describe("SQLite database operations", () => {
5+
it("should test unsubscribe functionality", async () => {
6+
const db = new SQLite();
7+
8+
const execCallback = vi.fn();
9+
const unsubscribe = db.on("exec", execCallback);
10+
11+
await db.exec(`SELECT 1`);
12+
expect(execCallback).toHaveBeenCalledTimes(1);
13+
14+
unsubscribe();
15+
16+
await db.exec(`SELECT 2`);
17+
expect(execCallback).toHaveBeenCalledTimes(1);
18+
});
19+
520
it("should perform database operations and verify exports match", async () => {
621
const db = new SQLite();
722

src/sqlite.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,15 @@ export class SQLite {
5858
});
5959
}
6060

61-
on(event: "exec", callback: (args: Args) => void): void {
61+
on(event: "exec", callback: (args: Args) => void): () => void {
6262
if (!this.callbacks[event]) this.callbacks[event] = [];
63-
this.callbacks[event].push(callback);
63+
const callbacks = this.callbacks[event];
64+
callbacks.push(callback);
65+
66+
return () => {
67+
const filtered = callbacks.filter((cb) => cb !== callback);
68+
this.callbacks[event] = filtered;
69+
};
6470
}
6571

6672
async export_db(): Promise<Uint8Array> {

0 commit comments

Comments
 (0)