MCPcopy
hub / github.com/brianc/node-postgres / parse

Function parse

packages/pg-connection-string/index.js:8–161  ·  view source on GitHub ↗
(str, options = {})

Source from the content-addressed store, hash-verified

6
7//parses a connection string
8function parse(str, options = {}) {
9 //unix socket
10 if (str.charAt(0) === '/') {
11 const config = str.split(' ')
12 return { host: config[0], database: config[1] }
13 }
14
15 // Check for empty host in URL
16
17 const config = Object.create(null)
18 let result
19 let dummyHost = false
20 if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
21 // Ensure spaces are encoded as %20
22 str = encodeURI(str).replace(/%25(\d\d)/g, '%$1')
23 }
24
25 try {
26 try {
27 result = new URL(str, 'postgres://base')
28 } catch (e) {
29 // The URL is invalid so try again with a dummy host
30 result = new URL(str.replace('@/', '@___DUMMY___/'), 'postgres://base')
31 dummyHost = true
32 }
33 } catch (err) {
34 // Remove the input from the error message to avoid leaking sensitive information
35 err.input && (err.input = '*****REDACTED*****')
36 throw err
37 }
38
39 // We'd like to use Object.fromEntries() here but Node.js 10 does not support it
40 for (const entry of result.searchParams.entries()) {
41 config[entry[0]] = entry[1]
42 }
43
44 config.user = config.user || decodeURIComponent(result.username)
45 config.password = config.password || decodeURIComponent(result.password)
46
47 if (result.protocol == 'socket:') {
48 config.host = decodeURI(result.pathname)
49 config.database = result.searchParams.get('db')
50 config.client_encoding = result.searchParams.get('encoding')
51 return config
52 }
53 const hostname = dummyHost ? '' : result.hostname
54 if (!config.host) {
55 // Only set the host if there is no equivalent query param.
56 config.host = decodeURIComponent(hostname)
57 } else if (hostname && /^%2f/i.test(hostname)) {
58 // Only prepend the hostname to the pathname if it is not a URL encoded Unix socket host.
59 result.pathname = hostname + result.pathname
60 }
61 if (!config.port) {
62 // Only set the port if there is no equivalent query param.
63 config.port = result.port
64 }
65

Callers 3

parseIntoClientConfigFunction · 0.70
clientConfig.tsFile · 0.50
parse.tsFile · 0.50

Calls 2

deprecatedSslModeWarningFunction · 0.85
testMethod · 0.80

Tested by

no test coverage detected