Skip to content

Commit

Permalink
Allow 'url-like' connection string
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisveness committed Apr 13, 2020
1 parent c858836 commit ae128ca
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions lib/mysqldb.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,32 @@ class MysqlDb {


/**
* Return connection parameters used to connect to MySQL (obtained from the
* DB_MYSQL_CONNECTION environment variable which should be a connection string in the format
* "host=my.host.com; user=my-un; password=my-pw; database=my-db").
* Return connection parameters used to connect to MySQL. Parameters are obtained from the
* DB_MYSQL_CONNECTION environment variable which should be a connection string either in the
* 'URI-Like' format
* mysql://my-un:my-pw@my.host.com/my-db
* or the 'Key-Value Pairs' format
* host=my.host.com; user=my-un; password=my-pw; database=my-db
* (dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html).
*
* @returns Object with host, user, password, database properties.
*/
static connectionParams() {
const connectionString = process.env.DB_MYSQL_CONNECTION;
if (!connectionString) throw new Error('No DB_MYSQL_CONNECTION available');

const dbConfigKeyVal = connectionString.split(';').map(v => v.trim().split('='));
const dbConfig = dbConfigKeyVal.reduce((config, v) => { config[v[0].toLowerCase()] = v[1]; return config; }, {});
const urlLikeConnectionString = connectionString.match(/mysql:\/\/(.+):(.+)@(.+)\/(.+)/);

if (urlLikeConnectionString) {
const [ , user, password, host, database ] = urlLikeConnectionString;
const dbConfig = { user, password, host, database };
return dbConfig;
} else {
const dbConfigKeyVal = connectionString.split(';').map(v => v.trim().split('='));
const dbConfig = dbConfigKeyVal.reduce((config, v) => { config[v[0].toLowerCase()] = v[1]; return config; }, {});
return dbConfig;
}

return dbConfig;
}


Expand Down

0 comments on commit ae128ca

Please sign in to comment.