acess function in objected, nested inside another function

Im trying to manage a connection instance, using a function to handle idle connection disconnect issues, using mysql database and node.js

At moment, i’ve got following code (coffescript):

mysql = require 'mysql'

handleDisconnect = () ->
  connection = mysql.createConnection
    host: 'localhost'
    user: 'root'
    password: 'passroot'
    database: 'mydb'

  connection.connect (err) ->
    if err
      console.log 'Error connecting to db: ', err
    setTimeout handleDisconnect, 2000

  connection.on 'error', (err) ->
    console.log 'db error', err
    if err.code == 'PROTOCOL_CONNECTION_LOST'
      handleDisconnect()
    else
      throw err

  handleDisconnect.instance = connection

module.exports = handleDisconnect

and

express = require 'express'
router = express.Router()
connection = require('../database')().instance

bcrypt = require 'bcryptjs'

router.post '/', (req, res) ->
  credential = connection.escape req.body.credential
  password = connection.escape req.body.password
  res.send credential+password

module.exports = router

Problem is, when i try to access the route, i get following error:

Cannot read property ‘escape’ of undefined

What am i doing wrong?

Solution:

I believe your issue is that the final line of handleDisconnect is returning the instance, so you’re trying to get the instance from instance, not from handleDisconnect. So you’ll need the function to return itself at the end if you want to access properties on it.

You also want the function to be using the equivalent of “this” (@ in coffeescript) rather than specifically referring to handleDisconnect.

Example code:

mysql = require 'mysql'

handleDisconnect = () ->
  connection = mysql.createConnection
    host: 'localhost'
    user: 'root'
    password: 'passroot'
    database: 'mydb'

  connection.connect (err) ->
    if err
      console.log 'Error connecting to db: ', err
    setTimeout handleDisconnect, 2000

  connection.on 'error', (err) ->
    console.log 'db error', err
    if err.code == 'PROTOCOL_CONNECTION_LOST'
      handleDisconnect()
    else
      throw err

  @instance = connection
  @

module.exports = handleDisconnect

Although I’d personally just do the following, don’t bother with “instance” at all:

  1. Use @connection in your function
  2. Scrap the @instance = connection
  3. Get the function to return itself
  4. Access it with require('../database')().connection.