-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
81 lines (73 loc) · 2.12 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { parse as parsePg } from "pg-connection-string"
interface Options {
/* If provided, overrides user */
user?: string
/* If provided, overrides database*/
database?: string
/* If provided, overrides process.env */
env?: any
/* fallback defaults are used when the environment doesn't have a value */
fallbackDefaults?: {
user?: string
host?: string
port?: number
database?: string
databaseName?: string
password?: string
}
}
export const getPgConnectionFromEnv = (opts: Options = {}) => {
const {
user,
env = process.env,
database,
fallbackDefaults: defaults = {},
} = opts
const uri =
env.POSTGRES_URI || env.PG_URI || env.DATABASE_URL || env.DATABASE_URI
if (uri) {
const uriObj = parsePg(uri)
return {
...uriObj,
database: database || uriObj.database,
user: user || uriObj.user,
ssl: uriObj.ssl
? { ...(uriObj as any).ssl, rejectUnauthorized: false }
: false,
}
} else {
return {
host: env.POSTGRES_HOST || defaults.host || "localhost",
user:
user ||
env.POSTGRES_USER ||
env.POSTGRES_USERNAME ||
defaults.user ||
"postgres",
port: env.POSTGRES_PORT || defaults.port || 5432,
password:
env.POSTGRES_PASS || env.POSTGRES_PASSWORD || defaults.password || "",
database:
database ||
env.POSTGRES_DATABASE ||
env.POSTGRES_DB ||
defaults.database ||
defaults.databaseName ||
"postgres",
// TODO more refined ssl handling
ssl: env.POSTGRES_SSL ? { rejectUnauthorized: false } : false,
}
}
}
export const getConnectionStringFromEnv = (opts: Options = {}) => {
const env = opts.env || process.env
const uri =
env.POSTGRES_URI || env.PG_URI || env.DATABASE_URL || env.DATABASE_URI
const uriParams = (uri || "").split("?")?.[1] || ""
const { host, password, port, database, user } = getPgConnectionFromEnv(opts)
// TODO sslmode?
return `postgresql://${user}:${password}@${host}:${port}/${database}${
uriParams ? `?${uriParams}` : ""
}`
}
export default getPgConnectionFromEnv