Last active
November 1, 2016 15:29
-
-
Save kvasdopil/5083a9ce15ac239166d204ae520dabaf 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
import mysql from 'mysql'; | |
export default class Db | |
{ | |
this.conn = false; | |
connect() | |
{ | |
// fixme: db settings are hardcoded | |
// fixme: no error handling here | |
// fixme: no async here | |
this.conn = mysql.createConnection({ | |
host : 'localhost', | |
user : 'me', | |
password : 'secret', | |
database : 'my_db' | |
}); | |
this.conn.connect(); | |
} | |
close() | |
{ | |
if(this.conn) | |
this.conn.end(); | |
} | |
async query(sql, args) | |
{ | |
if(!this.conn) | |
throw 'DB not connected'; | |
return await new Promise((ok, fail) => | |
this.conn.query(sql, args, (err, rows, fields) => | |
err ? fail(err) : ok(fields) | |
); | |
); | |
} | |
async queryStream(sql, args, cb) | |
{ | |
if(!this.conn) | |
throw 'DB not connected'; | |
return await new Promise((ok, fail) => { | |
var q = this.conn.query(sql, args); | |
q.on('error', err => fail(err)); | |
q.on('end', () => ok()); | |
q.on('result', row => { | |
cb(row); q.resume(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment