postgrejs
Version:
Professional PostgreSQL client NodeJS
62 lines (61 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConnectionConfig = getConnectionConfig;
exports.parseConnectionString = parseConnectionString;
const objects_1 = require("@jsopen/objects");
const config_from_env_js_1 = require("./config-from-env.js");
function getConnectionConfig(config) {
const cfg = (0, config_from_env_js_1.configFromEnv)();
if (typeof config === 'string') {
(0, objects_1.merge)(cfg, parseConnectionString(config));
}
else if (typeof config === 'object') {
(0, objects_1.merge)(cfg, config);
}
if (cfg.host) {
const x = parseConnectionString('' + cfg.host);
(0, objects_1.merge)(cfg, x);
}
cfg.user = cfg.user || 'postgres';
cfg.database = cfg.database || 'postgres';
cfg.host = cfg.host || '127.0.0.1';
return cfg;
}
function parseConnectionString(str) {
if (str.startsWith('/'))
str = 'socket:/' + str;
if (!str.includes('://'))
str = 'postgres://' + str;
const parsed = new URL(str);
const getFirst = (v) => typeof v === 'string' ? v : Array.isArray(v) ? v[0] : '';
const cfg = {};
cfg.host = decodeURI(parsed.hostname || '');
if (parsed.port)
cfg.port = parseInt(parsed.port, 10);
if (parsed.protocol === 'socket:' || parsed.protocol === 'unix:') {
if (!cfg.host.startsWith('/'))
cfg.host = '/' + cfg.host;
cfg.host += decodeURI(parsed.pathname || '');
if (parsed.searchParams.get('db'))
cfg.database = decodeURI(getFirst(parsed.searchParams.get('db')));
}
else if (parsed.protocol === 'pg:' || parsed.protocol === 'postgres:') {
if (parsed.pathname)
cfg.database = decodeURI(parsed.pathname.substring(1));
}
if (parsed.searchParams.get('host'))
cfg.host = decodeURI(getFirst(parsed.searchParams.get('host')));
if (parsed.searchParams.get('db'))
cfg.database = decodeURI(getFirst(parsed.searchParams.get('db')));
if (parsed.searchParams.get('schema'))
cfg.schema = decodeURI(getFirst(parsed.searchParams.get('schema')));
if (parsed.searchParams.get('application_name')) {
cfg.applicationName = decodeURI(getFirst(parsed.searchParams.get('application_name')));
}
if (parsed.username)
cfg.user = parsed.username;
if (parsed.password)
cfg.password = parsed.password;
cfg.requireSSL = parsed.searchParams.get('sslmode') === 'require';
return cfg;
}