From 123bf2e647d8dc34936d764c7a3835db179124b5 Mon Sep 17 00:00:00 2001 From: Simo Kinnunen Date: Sat, 12 Apr 2014 16:00:04 +0900 Subject: [PATCH] Automatically close database when lifecycle ends. --- lib/db/index.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/db/index.js b/lib/db/index.js index 216e5a77..7394d482 100644 --- a/lib/db/index.js +++ b/lib/db/index.js @@ -3,8 +3,10 @@ var rutil = require('../util/rutil') var logger = require('../util/logger') var lifecycle = require('../util/lifecycle') +var db = module.exports = Object.create(null) +var log = logger.createLogger('db') + function connect() { - var log = logger.createLogger('db') return rutil.connect({ host: process.env.RDB_HOST || 'localhost' , port: process.env.RDB_PORT || 28015 @@ -12,6 +14,10 @@ function connect() { , authKey: process.env.RDB_AUTHKEY }) .then(function(conn) { + lifecycle.observe(function() { + return db.close() + }) + return conn.on('error', function(err) { log.fatal('Connection error', err.stack) lifecycle.fatal() @@ -23,8 +29,6 @@ function connect() { }) } -var db = module.exports = Object.create(null) - // Export memoized connection as a Promise db.connect = (function() { var connection = connect()