Skip to content

Commit

Permalink
Merge pull request #3 from agnosticeng/unsubscribe
Browse files Browse the repository at this point in the history
feat: add unsubscribe
  • Loading branch information
didierfranc authored Jan 6, 2025
2 parents 3d91f19 + 0552164 commit 2b43e9f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
```

Expand Down Expand Up @@ -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<Uint8Array>`

Expand Down
15 changes: 15 additions & 0 deletions src/sql.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
10 changes: 8 additions & 2 deletions src/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8Array> {
Expand Down

0 comments on commit 2b43e9f

Please sign in to comment.