Skip to content

Commit 4cdd7c9

Browse files
committed
feat: implement 'isConnected' helper function
1 parent 3b9b1e2 commit 4cdd7c9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/postgres/__tests__/base-pg-store.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,15 @@ describe('BasePgStore', () => {
118118
expect(sqlTransactionContext.getStore()).toBeUndefined();
119119
expect(db.sql).toEqual(obj);
120120
});
121+
122+
test('isConnected returns true when the connection is alive', async () => {
123+
const connected = await db.isConnected();
124+
expect(connected).toBe(true);
125+
});
126+
127+
test('isConnected returns false when the connection is not alive', async () => {
128+
jest.spyOn(db, 'sql').mockRejectedValueOnce(new Error('Connection lost'));
129+
const connected = await db.isConnected();
130+
expect(connected).toBe(false);
131+
});
121132
});

src/postgres/base-pg-store.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,19 @@ export abstract class BasePgStore {
8484
isProdEnv ? this.sql`CONCURRENTLY` : this.sql``
8585
} ${this.sql(viewName)}`;
8686
}
87+
88+
/**
89+
* Checks if the database connection is alive.
90+
* @returns True if connected, false otherwise.
91+
*/
92+
async isConnected(): Promise<boolean> {
93+
try {
94+
await this.sql`SELECT NOW()`;
95+
return true;
96+
} catch (error) {
97+
return false;
98+
}
99+
}
87100
}
88101

89102
/**
@@ -114,4 +127,7 @@ export abstract class BasePgStoreModule {
114127
async refreshMaterializedView(viewName: string): Promise<void> {
115128
return this.parent.refreshMaterializedView(viewName);
116129
}
130+
async isConnected(): Promise<boolean> {
131+
return this.parent.isConnected();
132+
}
117133
}

0 commit comments

Comments
 (0)