From 738c52c73a1a942b1fa585f40ec8e7bb7e9fa9d4 Mon Sep 17 00:00:00 2001
From: Dustin Deus <deusdustin@gmail.com>
Date: Fri, 30 Mar 2018 13:21:06 +0200
Subject: [PATCH] pass err instead exit the client, add onClose Hook

---
 index.js | 30 +++++++++++++++++-------------
 1 file changed, 17 insertions(+), 13 deletions(-)

diff --git a/index.js b/index.js
index 74701e8..a8d51b3 100644
--- a/index.js
+++ b/index.js
@@ -11,18 +11,24 @@ function hemeraElasticSearch(hemera, opts, done) {
     opts.elasticsearchInstance || new Elasticsearch.Client(opts.elasticsearch)
   hemera.decorate('elasticsearch', client)
 
-  /**
-   * Check if cluster is available otherwise exit this client.
-   */
-  client
-    .ping({
+  client.ping(
+    {
       requestTimeout: opts.elasticsearch.timeout
-    })
-    .then(() => hemera.log.debug('elasticsearch cluster is available'))
-    .catch(err => {
-      hemera.log.error(err, 'elasticsearch cluster is down!')
-      hemera.fatal()
-    })
+    },
+    function(err) {
+      if (err) {
+        done(err)
+      } else {
+        hemera.log.debug('elasticsearch cluster is available')
+        done()
+      }
+    }
+  )
+
+  hemera.ext('onClose', function closeESClient() {
+    hemera.log.debug('elasticsearch client is closing ...')
+    return client.close()
+  })
 
   hemera.add(
     {
@@ -132,8 +138,6 @@ function hemeraElasticSearch(hemera, opts, done) {
     },
     req => client.refresh(req.data)
   )
-
-  done()
 }
 
 module.exports = Hp(hemeraElasticSearch, {