Last active
August 29, 2015 14:05
-
-
Save avovsya/e1c83a205059c8ab4b23 to your computer and use it in GitHub Desktop.
Postgres db service wrapper
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
var pg = require('pg'); | |
var Service = function (connectionConfig) { | |
this.connectionConfig = connectionConfig; | |
this._client = null; | |
this._releaseClient = null; | |
this.isConnected = false; | |
}; | |
Service.prototype._connection = function (callback) { | |
var self = this; | |
if (this.isConnected) { | |
return callback(null, this._client); | |
} | |
pg.connect(this.connectionConfig, function (err, client, done) { | |
self._client = client; | |
self._releaseClient = done; | |
self.isConnected = true; | |
callback(err, client); | |
}); | |
}; | |
Service.prototyp._disconnect = function () { | |
this.isConnected = false; | |
this._client = null; | |
this._releaseClient(); | |
}; | |
Service.prototy.getSomething = function (params, callback) { | |
this._connection(function (err, client) { | |
client.query("SELECT * FROM something", params, function (err, result) { | |
if (err) { | |
return callback(err); | |
} | |
if (result.rows.lenght === 0) { | |
return callback(null, null); | |
} | |
return callback(null, result.rows); | |
}); | |
}); | |
}; | |
module.exports = Service; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment