Skip to content

Commit

Permalink
Move DB_URI parse to MySQL
Browse files Browse the repository at this point in the history
  • Loading branch information
tomdionysus committed May 14, 2020
1 parent 68d9dec commit 01e9a7b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mysql -u root $DATABASE_NAME < sql/db_setup.sql

## Running

The server will needs a `DB_URI` in the following format, and will bind to UDP Port 53 by default. MacOS and various other OSes bind `0.0.0.0` UDP Port 53, so it's best to run it on a different one.
The server needs a `DB_URI` in the following format, and will bind to UDP Port 53 by default. MacOS and various other OSes bind `0.0.0.0` UDP Port 53, so it's best to run it on a different one.

```bash
DB_URI=mysql://root@localhost/$DATABASE_NAME LOG_LEVEL=DEBUG PORT=54 node index.js
Expand Down
10 changes: 1 addition & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,8 @@ function main () {
logger.log('', '----')
logger.log('Logging Level %s', '----', Logger.logLevelToString(logger.logLevel))

// ENV and defaults
try {
var dbUrl = new url.URL(process.env.DB_URI)
} catch (err) {
logger.error('Cannot parse env DB_URI (should be mysql://user:password@host:port/database)')
process.exit(1)
}

// Dependencies
var mysql = new MySQL({ logger: logger, host: dbUrl.host, user: dbUrl.username, database: dbUrl.pathname.substr(1), password: dbUrl.password })
var mysql = new MySQL({ logger: logger, uri: process.env.DB_URI })

// Start MySQL
mysql.connect()
Expand Down
18 changes: 17 additions & 1 deletion lib/MySQL.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const mysqllib = require('mysql')
const crypto = require('crypto')
const url = require('url')

const mysqllib = require('mysql')
const async = require('async')

const Logger = require('./Logger')
Expand All @@ -12,6 +14,8 @@ class MySQL {
this.logger = new ScopedLogger('MySQL', options.logger || new Logger())
this.mysql = options.mysql || mysqllib
this.kvstore = options.kvstore

if(this.options.uri) this._parseDBURI(this.options.uri)
}

static _query (conn, query, params, callback) {
Expand All @@ -25,6 +29,18 @@ class MySQL {
})
}

_parseDBURI(uri) {
try {
var dbUrl = new url.URL(uri)
this.options.host = dbUrl.host
this.options.user = dbUrl.username
this.options.database = dbUrl.pathname.substr(1)
this.options.password = dbUrl.password
} catch (err) {
this.logger.error('Cannot parse options.url (should be mysql://user:password@host:port/database)')
}
}

connect () {
this.pool = this.mysql.createPool({
host: this.options.host,
Expand Down

0 comments on commit 01e9a7b

Please sign in to comment.