Created
April 5, 2019 00:34
-
-
Save konsumer/77c182cbe80a411d5f7d8745750fdb65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { parse } = require('url') | |
const { decode } = require('querystring') | |
const { unflatten } = require('flat') | |
const dbUriParse = (url) => { | |
let options = { connection: {} } | |
const u = parse(url) | |
const { protocol, pathname, hostname, auth, query, port } = u | |
options.client = protocol.replace(':', '') | |
if (options.client === 'sqlite') { | |
options.client = 'sqlite3' | |
} else if (options.client === 'postgres' || options.client === 'postgresql') { | |
options.client = 'pg' | |
} | |
if (options.client === 'sqlite3') { | |
options.connection.filename = hostname && pathname ? `${hostname}${pathname}` : (hostname || pathname) | |
if (options.connection.filename === '/:memory') { | |
options.connection.filename = ':memory:' | |
} | |
} else { | |
const [user, password] = auth ? auth.split(':') : [] | |
options.connection = { | |
database: pathname.replace(/^\//, ''), | |
host: hostname, | |
user, | |
password, | |
port | |
} | |
} | |
if (query) { | |
const q = decode(query) | |
const qoptions = {} | |
Object.keys(q).forEach(k => { | |
qoptions[k] = q[k] | |
if (q[k] === 'false') { | |
qoptions[k] = false | |
} | |
if (q[k] === 'true') { | |
qoptions[k] = true | |
} | |
if (!isNaN(q[k])) { | |
qoptions[k] = Number(q[k]) | |
} | |
}) | |
options = { ...options, ...unflatten(qoptions) } | |
} | |
return options | |
} | |
const urls = `postgres://username@hostname/databasename | |
mysql://username:password@hostname:666/databasename | |
postgres:///var/run/postgresql/test?debug=1 | |
mysql://localhost/database?unix_socket=/var/lib/mysql/socket | |
sqlite://path/to/file | |
sqlite://file?useNullAsDefault=true | |
sqlite://:memory:?useNullAsDefault=true` | |
urls.split('\n').forEach(s => { | |
test(s, () => { | |
expect(dbUriParse(s)).toMatchSnapshot() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment