Skip to content

Instantly share code, notes, and snippets.

@kvasdopil
Last active November 1, 2016 15:29
Show Gist options
  • Save kvasdopil/5083a9ce15ac239166d204ae520dabaf to your computer and use it in GitHub Desktop.
Save kvasdopil/5083a9ce15ac239166d204ae520dabaf to your computer and use it in GitHub Desktop.
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