javascript - Using Koa with bluebird and pg -


i have question best way use koa postgres. (really) using bluebird, i've gone approach.

'use strict';   var db = require('./modules/db.js'); var koa = require('koa'); var app = koa();  app.use(function *(){      yield db.withconnection(function *(client){          let id = this.request.query.id;         let simple_data = yield client.queryasync('select name table1 id = $1', [id]);          this.response.body = simple_data;     }.bind(this)); });  app.listen(3000); 

this db.js file, uses things mentioned in bluebird docs.

... bla bla, imports  promise.promisifyall(pg);  function getsqlconnection() {     var close;     return pg.connectasync(connectionstring).spread(function(client, done) {         close = done;         return client;     }).disposer(function() {         if (close) close();     }); }   function* withconnection(func){     yield promise.using(getsqlconnection(), function (client){             return promise.coroutine(func)(client);      }); }  module.exports.withconnection = withconnection; 

do have suggestions on improving this. now, i've tested extensively (under load, making errors/exceptions, etc), , seems work correctly. i'm pretty new these generators , other es6 stuff, it's possible i'm missing something. question why little people use approach (i find hard find examples on online)?

i'm fine using other libraries besides pg , bluebird, due number of downloads have,i prefer using popular stuff because find easier find blog posts, , documentation those. thanks!

bluebird promise library, 1 @ that, should not used guidance of how or database library use. promise.promisifyall(pg); stuff quite poor next promise solutions exist out there - knex, massive.js, pg-promise, etc.

and if want best combination of pg + bluebird, try pg-promise.

var promise = require('bluebird');  var options = {     promiselib: promise // use bluebird promise library };  var pgp = require("pg-promise")(options);  var db = pgp('postgres://username:password@host:port/database');  db.query('select name table1 id = $1', [1])     .then(function (data) {     })     .catch(function (error) {     }); 

the library supports es6 generators also, can write code in example.

from tasks example:

db.task(function * (t) {         let user = yield t.one("select * users id=$1", 123);         return yield t.any("select * events login=$1", user.name);     })     .then(function (events) {         // success;     })     .catch(function (error) {         // error;     }); 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -