Skip to content

Instantly share code, notes, and snippets.

@Globik

Globik/server.js

Created Oct 21, 2016
Embed
What would you like to do?
PostgresQL with node-pg(Pool) on Koa.js
'use strict';
const koa=require('koa');
const render=require('./libs/render.js');
const path=require('path');
var debug=module.exports=require('debug')('icon')
debug('Hali halo debug!');
var serve=require('koa-static');
var bodyParser=require('koa-body');
var Router=require('koa-router');
var pg=require('pg');
var config={
database:'globi',
host:'127.0.0.1',
port:5432,
max:10,
idleTimeout:30000,
user:'User'
};
var pool=new pg.Pool(config);
pool.on('error',function(err,client){
console.log(err.message,err.stack);
});
pool.on('connect',cl=>{
console.log('Connected!!!');
});
pool.on('acquire',cl=>{
console.log('Acquired!!!');
});
var app=koa();
render(app,{});
app.use(serve(__dirname+'/public'));
app.use(bodyParser());
var pub=new Router();
pub.get('/',function *(){
//var client=yield pool.connect();
/*
// 10 times requests from the browser side and the postgresQL connection is down
//(if without client.release()
try{
var result=yield client.query('select*from comp');
console.log('result: ',result.rows[0].age);
}catch(e){console.log('err: ',e);this.body={'er':e};
client.release();
}
finally{
console.log('finally ist da');
client.release();
this.body=this.render('main_page',{data:result.rows});
}
*/
try{
// and this way is all ok. One connection to DB, and many other aqcuired events
//thinking, the Pool instance has got all needed stuff built-in for a node.js request and requests
var result=yield pool.query('select*from articles where id=4');
console.log('result: ',result.rows[0]);
}catch(e){
console.log('e: ',e);
//this.status=bla-bla and other stuff
}
finally{
this.body=this.render('main_page',{data:result.rows[0]});
}
});
app.use(pub.routes());
if(process.env.NODE_ENV === 'test'){module.exports=app.callback();}
else{console.log('Server started: ',3000);app.listen(process.env.PORT || 3000);}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment