Created
April 16, 2017 06:00
-
-
Save Toyz/ef675507bc5105e52c490f1b96041b3c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const express = require('express'), | |
format = require('string-format'); | |
let pg = undefined; | |
try { | |
require.resolve('pg-native'); | |
pg = require('pg').native; | |
console.log('Using pg-native'); | |
} catch(e) { | |
pg = require('pg'); | |
console.log('Using pg'); | |
} | |
let app = express(); | |
let database = {}; | |
//change me to change the pool size limit | |
let connection_pool_limit = Math.floor(100 / 4); //default is 100 (server default as well) | |
let config = { | |
user: '', | |
database: '', | |
password: "", | |
host: 'localhost', | |
port: 5432, | |
max: 0, | |
idleTimeoutMillis: 1000 | |
}; | |
database = { | |
connect: (threads, limit = 100) => { | |
if (threads) connection_pool_limit = (limit / threads); | |
config.max = connection_pool_limit; | |
this.pool = new pg.Pool(config); | |
}, | |
connString: () => { | |
return `postgres://${config.user}:${config.password}@${config.host}:${config.port}/${config.database}`; | |
}, | |
getPg: (pool = false) => { | |
return (pool) ? this.pool : pg; | |
}, | |
rawQuery: (sql, params, cb) => { | |
let self = this; | |
if(!cb) { | |
return new Promise((resolve, reject) => { | |
try { | |
self.pool.connect((err, client, done) => { | |
client.query(sql, params, (err, result) => { | |
done(); | |
if(err) { | |
return reject(err); | |
} | |
resolve(result); | |
}); | |
}); | |
} catch(e) { | |
reject(e); | |
} | |
}); | |
} else { | |
self.pool.connect((err, client, done) => { | |
client.query(sql, params, (err, result) => { | |
done(); | |
if(err){ | |
return cb(false, err); | |
} | |
cb(result); | |
}); | |
}); | |
} | |
} | |
} | |
module.exports = (threads, limit) => { | |
database.connect(threads, limit); | |
return database; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment