|
1 | 1 | import { Client } from 'pg' |
2 | 2 | import { loop } from './common/function' |
3 | 3 | import { createDbService } from './dbService' |
4 | | -import { SimplePgClientOptions, SimplePgClient, ResolvedMaintenanceDbOptions, SimplePgClientEventHandlers } from './types' |
| 4 | +import { |
| 5 | + SimplePgClientOptions, |
| 6 | + SimplePgClient, |
| 7 | + ResolvedMaintenanceDbOptions, |
| 8 | + SimplePgClientEventHandlers, |
| 9 | + SimplePgClientFromClientOptions, |
| 10 | +} from './types' |
5 | 11 |
|
6 | 12 | const createDbUrl = ( |
7 | 13 | host: string, |
@@ -199,7 +205,7 @@ export const createConsoleLogEventHandlers = (): SimplePgClientEventHandlers => |
199 | 205 | }) |
200 | 206 |
|
201 | 207 | /** |
202 | | - * Creates an instance of `SimplePgClient`, connecting to a PostgreSQL database. |
| 208 | + * Creates an instance of `SimplePgClient`, connecting to a PostgreSQL server. |
203 | 209 | */ |
204 | 210 | export const createSimplePgClient = async (options: SimplePgClientOptions): Promise<SimplePgClient> => { |
205 | 211 | // Optionally create db if it does not exist, via a defined maintenance db on the server |
@@ -247,3 +253,26 @@ export const createSimplePgClient = async (options: SimplePgClientOptions): Prom |
247 | 253 | queryGetRows: dbService.queryGetRows, |
248 | 254 | } |
249 | 255 | } |
| 256 | + |
| 257 | +/** |
| 258 | + * Creates an instance of `SimplePgClient` from an already-connected `Client` instance (from `pg`). |
| 259 | + */ |
| 260 | +export const createSimplePgClientFromClient = (options: SimplePgClientFromClientOptions): SimplePgClient => { |
| 261 | + // Create db service, providing query functions on pg client |
| 262 | + const dbService = createDbService({ |
| 263 | + client: options.client, |
| 264 | + sqlLoggingTruncation: options.sqlLoggingTruncation, |
| 265 | + events: { |
| 266 | + onError: options.events?.onQueryError, |
| 267 | + onQuery: options.events?.onQuery, |
| 268 | + }, |
| 269 | + }) |
| 270 | + |
| 271 | + return { |
| 272 | + client: options.client, |
| 273 | + query: dbService.query, |
| 274 | + queryExists: dbService.queryExists, |
| 275 | + queryGetFirstRow: dbService.queryGetFirstRow, |
| 276 | + queryGetRows: dbService.queryGetRows, |
| 277 | + } |
| 278 | +} |
0 commit comments