@incdevco/framework
Version:
node.js lambda framework
100 lines (60 loc) • 1.79 kB
JavaScript
var AWS = require('aws-sdk');
var pg = require('pg');
var Promise = require('bluebird');
var Connection = require('./connection');
var Sql = require('./sql');
var Transaction = require('./transaction');
var Utilities = require('../utilities');
function Pg(config) {
'use strict';
config.Promise = Promise;
this.config = config;
this.kms = config.kms || new AWS.KMS();
this.pool = null;
this.poolPromise = null;
}
Pg.prototype.connect = function () {
'use strict';
return this.getPool()
.then(function (pool) {
return pool.connect();
})
.then(function (client) {
return new Connection(client);
});
};
Pg.prototype.getPool = function () {
'use strict';
var self = this;
if (!this.poolPromise) {
if (this.config.CiphertextBlob) {
this.poolPromise = this.kms.decrypt({
CiphertextBlob: this.config.CiphertextBlob,
EncryptionContext: this.config.EncryptionContext,
GrantTokens: this.config.GrantTokens
}).promise()
.then(function (result) {
var temp = Utilities.copy(self.config);
temp.password = result.Plaintext;
self.pool = new pg.Pool(temp);
return self.pool;
});
} else {
this.pool = new pg.Pool(this.config);
this.poolPromise = Promise.resolve(this.pool);
}
}
return this.poolPromise;
};
Pg.prototype.startTransaction = function () {
'use strict';
return this.connect()
.then(function (connection) {
return connection.query('BEGIN')
.then(function () {
return new Transaction(connection);
});
});
};
module.exports = Pg;
module.exports.Sql = Sql;