Node.js DRY with MySQL clients

so here's a quick question. Basically I'm making an express application that connects to a MySQL server. Pretty simple. But how do I stop adding all the connection code between files so I don't have to change multiple files if I change password or database.

Example:

app.coffee

client = mysql.createClient
  user: config.db.user,
  password: config.db.pass

app.get '/', routes.index

routes/index.coffee

client = mysql.createClient
  user: config.db.user,
  password: config.db.pass

exports.index = (req, res) ->
  res.render 'index'

I've tried to create a file called lib/mysql.coffee which is the following:

config = require '../config'
mysql = require 'mysql'

module.exports = ( ->
  mysql.createClient
    host: config.db.host
    user: config.db.user
    password: config.db.pass
    database: config.db.name
)

So in app, I can go:

mysql = require './lib/mysql'
mysql.query 'SHOW TABLES', (err,r,f) ->
    console.log err

but it keeps giving:

TypeError: Object function () {
    return mysql.createClient({
      host: config.db.host,
      user: config.db.user,
      password: config.db.pass,
      database: config.db.name
    });
  } has no method 'query'

Module: https://github.com/felixge/node-mysql

Right now you are exporting the function and no its return value.

Apparently you can create a self-executing function with the do keyword in CoffeeScript, so try this:

module.exports = do ( ->
  mysql.createClient
    host: config.db.host
    user: config.db.user
    password: config.db.pass
    database: config.db.name
)

Or do what µ is too short suggests and call the exported function. That would be cleaner anyway.

My node-fu isn't that strong but this:

module.exports = ( ->
  mysql.createClient
    ...
)

is exporting a function that returns a MySQL connection. Your error message:

TypeError: Object function () {
    return mysql.createClient({
      ...
    });
  } has no method 'query'

says as much; that says that mysql is a function object that has no query method.

You can keep doing what you're doing and say:

mysql = require './lib/mysql'
db    = mysql()
db.query 'SHOW TABLES', (err,r,f) ->
  console.log err

Or you could export a connect method:

module.exports =
  connect: ->
    mysql.createClient(...)

and use that:

mysql = require './lib/mysql'
db    = mysql.connect()
db.query ...