|
| 1 | +import deepmerge from 'deepmerge'; |
| 2 | +import { getPgEnvVars, PgConfig } from 'pg-env'; |
| 3 | +import { |
| 4 | + getConnections as getPgConnections, |
| 5 | + type GetConnectionOpts, |
| 6 | + type GetConnectionResult |
| 7 | +} from 'pgsql-test'; |
| 8 | +import type { PgTestConnectionOptions } from '@pgpmjs/types'; |
| 9 | + |
| 10 | +/** |
| 11 | + * InsForge default connection options |
| 12 | + */ |
| 13 | +const INSFORGE_DEFAULTS: Partial<PgTestConnectionOptions> = { |
| 14 | + roles: { |
| 15 | + anonymous: 'anon', |
| 16 | + authenticated: 'authenticated', |
| 17 | + administrator: 'project_admin', |
| 18 | + default: 'anon', |
| 19 | + }, |
| 20 | + connections: { |
| 21 | + app: { |
| 22 | + user: 'postgres', |
| 23 | + password: 'postgres', |
| 24 | + } |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * InsForge default PostgreSQL config |
| 30 | + */ |
| 31 | +const INSFORGE_PG_DEFAULTS: Partial<PgConfig> = { |
| 32 | + port: 5432, |
| 33 | + user: 'postgres', |
| 34 | + password: 'postgres', |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * Get connections with InsForge defaults applied. |
| 39 | + * Uses deepmerge for proper nested config merging. |
| 40 | + * |
| 41 | + * Precedence (later wins): |
| 42 | + * 1. InsForge defaults |
| 43 | + * 2. Environment variables (PGUSER/PGPASSWORD) |
| 44 | + * 3. User-provided options |
| 45 | + */ |
| 46 | +export const getConnections = async ( |
| 47 | + cn: GetConnectionOpts = {}, |
| 48 | + seedAdapters?: Parameters<typeof getPgConnections>[1] |
| 49 | +): Promise<GetConnectionResult> => { |
| 50 | + // Get environment variables (only includes defined keys) |
| 51 | + const pgEnvVars = getPgEnvVars(); |
| 52 | + |
| 53 | + // Build env overrides - pgEnvVars already only has defined keys |
| 54 | + // Mirror user/password to connections.app for the app connection |
| 55 | + const envOverrides: Partial<GetConnectionOpts> = { |
| 56 | + pg: pgEnvVars, |
| 57 | + db: { |
| 58 | + connections: { |
| 59 | + app: { |
| 60 | + ...(pgEnvVars.user && { user: pgEnvVars.user }), |
| 61 | + ...(pgEnvVars.password && { password: pgEnvVars.password }), |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + // Merge: InsForge defaults -> env vars -> user overrides |
| 68 | + const mergedOpts = deepmerge.all([ |
| 69 | + { pg: INSFORGE_PG_DEFAULTS, db: INSFORGE_DEFAULTS }, |
| 70 | + envOverrides, |
| 71 | + cn, |
| 72 | + ]) as GetConnectionOpts; |
| 73 | + |
| 74 | + return getPgConnections(mergedOpts, seedAdapters); |
| 75 | +}; |
| 76 | + |
| 77 | +// Re-export types |
| 78 | +export type { GetConnectionOpts, GetConnectionResult }; |
0 commit comments