Repository URL to install this package:
|
Version:
1.0.1 ▾
|
touchto-database
/
database.coffee
|
|---|
# Connect to the database
SUPPRESS_NO_CONFIG_WARNING = process.env.SUPPRESS_NO_CONFIG_WARNING
process.env.SUPPRESS_NO_CONFIG_WARNING = 'y'
config = require 'config'
process.env.SUPPRESS_NO_CONFIG_WARNING = SUPPRESS_NO_CONFIG_WARNING
# If we don't have a database in the config, then let's bounce
if not config.has 'database' then return
'use strict'
mongoose = require 'mongoose'
mongoose.set 'debug', (if config.has('database.debug') then config.get('database.debug') else false)
debug_namespace = 'touchto'
debug = require('debug') "#{debug_namespace}:database"
# Store globally the attempts to connect to the database
global.database_connect_attempts = global.database_connect_attempts || 0
# If there is an error we need to know about it
mongoose.connection.on 'error', (err) ->
console.error err.stack
return
# On mongoose disconnect, attempt to reconnect
mongoose.connection.on 'disconnected', (err) ->
if global.database_connect_attempts > 2
debug 'Database connection trouble, waiting %j seconds to try again...'
setTimeout ->
process.nextTick connect
return
, 1000 * global.database_connect_attempts
else process.nextTick connect
return
# On Connected, yeah!
mongoose.connection.on 'connected', (err) ->
if err
console.error err
return
else
debug 'Database Connected'
return
# connection helper
connect = ->
global.database_connect_attempts++
uri = config.get 'database.connect'
options = if config.has('database.options') then config.get 'database.options' else null
mongoose.connect uri, options
return
connect()