Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: treat external connection as open #1243

Merged
merged 3 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ enum ConnectionStatus {
DISCONNECTED = 'DISCONNECTED',
CONNECTED = 'CONNECTED',
ERROR = 'ERROR',
EXTERNAL = 'EXTERNAL',
}

function db(
Expand All @@ -51,17 +52,24 @@ function db(
typeof connection === 'object' &&
'query' in connection &&
typeof connection.query === 'function';
let connectionStatus = ConnectionStatus.DISCONNECTED;

const client: Client = isExternalClient
? (connection as Client)
: new pg.Client(connection as string | ClientConfig);

let connectionStatus = isExternalClient
? ConnectionStatus.EXTERNAL
: ConnectionStatus.DISCONNECTED;

const beforeCloseListeners: any[] = [];

const connected: DBConnection['connected'] = () =>
connectionStatus === ConnectionStatus.CONNECTED ||
connectionStatus === ConnectionStatus.EXTERNAL;

const createConnection: DBConnection['createConnection'] = () =>
new Promise((resolve, reject) => {
if (isExternalClient || connectionStatus === ConnectionStatus.CONNECTED) {
if (connected()) {
resolve();
} else if (connectionStatus === ConnectionStatus.ERROR) {
reject(
Expand Down Expand Up @@ -146,7 +154,7 @@ ${error}
select,
column,

connected: () => connectionStatus === ConnectionStatus.CONNECTED,
connected,
addBeforeCloseListener: (listener) => beforeCloseListeners.push(listener),
close: async () => {
await beforeCloseListeners.reduce(
Expand Down
8 changes: 8 additions & 0 deletions test/db.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,12 @@ describe('db', () => {
expect(hoisted.client.end).toHaveBeenCalled();
});
});

describe('connected', () => {
it('should treat external connection as conencted', () => {
const mockClient = new Client();
const db = Db(mockClient, log);
expect(db.connected()).toBeTruthy();
});
});
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
});