Accessing a Postgres/Redshift Database via a Static IP from Node.js

You can route all database traffic via a Static IP in Node.js using QuotaGuard Static. Currently there is a limitation in that you can’t use the built in connection pooling so this is not recommended for high traffic applications.

This example provided by Ladislav Prskavec.

var pg = require('pg'),
    url = require('url'),
    SocksConnection = require('socksjs');

var db = url.parse(process.env.REDSHIFT_CONN_STRING),
    dbAuth = db.auth,
    dbUsername = dbAuth.split(':')[0],
    dbPassword = dbAuth.split(':')[1],
    dbName = db.pathname.replace('/', '');

var proxy = url.parse(process.env.QUOTAGUARDSTATIC_URL),
    auth = proxy.auth,
    username = auth.split(':')[0],
    pass = auth.split(':')[1];

var sock_options = {
  host: proxy.hostname,
  port: 1080,
  user: username,
  pass: pass
};

var remote_options = {
  host: db.hostname,
  port: db.port
};

var sockConn = new SocksConnection(remote_options, sock_options);

var config = {
  user: dbUsername,
  database: dbName,
  password: dbPassword,
  stream: sockConn
};

var client = new pg.Client(config);

// connect to our database
client.connect(function (err) {
  if (err) throw err;

  // execute a query on our database
  client.query('SELECT $1::text as name', ['john doe'], function (err, result) {
    if (err) throw err;

    // just print the result to the console
    console.log(result.rows[0]); // outputs: { name: 'apiary' }

    // disconnect the client
    client.end(function (err) {
      if (err) throw err;
    });
  });
});