Skip to content

Commit 815ec50

Browse files
committed
feat: emit events on ready and end
Emit events on client connect and client end, and returns the Client on `connect()` and `end()` functions. Tests updated accordingly.
1 parent d283323 commit 815ec50

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/index.ts

+16-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import EventEmitter from "events";
12
import { Client as PgClient } from "pg";
23

34
import add from "./methods/add";
@@ -41,20 +42,27 @@ export type Methods =
4142
| "all"
4243
| "type";
4344

44-
export class Client {
45+
export class Client extends EventEmitter {
4546
protected dbUrl: string;
4647
protected options: ClientOptions | undefined;
47-
protected client: PgClient;
4848
protected tableName: string | undefined;
4949

50+
/**
51+
* The `pg` client instance for your database.
52+
*/
53+
54+
public client: PgClient;
55+
5056
/**
5157
* Whether the database has been connected or not.
5258
* @see connect
5359
* @see end
5460
*/
61+
5562
public connected: boolean;
5663

5764
constructor(dbUrl: string, options?: ClientOptions) {
65+
super();
5866
this.dbUrl = dbUrl;
5967
this.options = options;
6068
this.tableName = options?.table ?? undefined;
@@ -64,23 +72,28 @@ export class Client {
6472

6573
/**
6674
* Connects to the database specified when creating the client.
67-
* @returns void
75+
* @returns the client
6876
* @example await db.connect();
6977
*/
7078

7179
public async connect() {
7280
await this.client.connect();
7381
this.connected = true;
82+
this.emit("ready", this);
83+
return this;
7484
}
7585

7686
/**
7787
* Ends the connection to the database specified when creating the client.
88+
* @returns the client
7889
* @example await db.end();
7990
*/
8091

8192
public async end() {
8293
await this.client.end();
8394
this.connected = false;
95+
this.emit("end", this);
96+
return this;
8497
}
8598

8699
/**

tests/test.js

+7
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,14 @@ class Test {
3030
}
3131
}
3232

33+
db.on("ready", () => console.log("ℹ️ Database connected"));
34+
db.on("end", () => console.log("ℹ️ Database connection ended"));
35+
3336
(async () => {
3437
await db.connect();
3538

39+
console.time("Time to test (excludes connection & end)");
40+
3641
await db.set("users.0", {
3742
username: "Zero",
3843
@@ -79,6 +84,8 @@ class Test {
7984
// Test 13
8085
new Test(await db.type("users.0.points")).test("number");
8186

87+
console.timeEnd("Time to test (excludes connection & end)");
88+
8289
await db.drop();
8390
await db.end();
8491

0 commit comments

Comments
 (0)