From 4ac184248777edf702ac5f2f9d23af0ce9fbc5a7 Mon Sep 17 00:00:00 2001 From: Eric Caron Date: Tue, 10 Sep 2013 23:21:23 -0500 Subject: [PATCH] Introducing ability for the system to automatically parse all responses into JSON --- README.md | 3 ++- lib/elasticsearchclient/calls/elasticSearchCall.js | 2 ++ package.json | 2 +- test/core.test.js | 14 ++++++++++++++ 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7c1b08f..d9ae11b 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ var serverOptions = { host: 'localhost', port: 9200, pathPrefix:'optional pathPrefix', + parseJSON: true||false,//default false secure: true||false, //Optional basic HTTP Auth auth: { @@ -53,7 +54,7 @@ var qryObj = { elasticSearchClient.search('my_index_name', 'my_type_name', qryObj) .on('data', function(data) { - console.log(JSON.parse(data)) + console.log(JSON.parse(data)) //Necessary if parseJSON is false }) .on('done', function(){ //always returns 0 right now diff --git a/lib/elasticsearchclient/calls/elasticSearchCall.js b/lib/elasticsearchclient/calls/elasticSearchCall.js index eebce68..108c893 100644 --- a/lib/elasticsearchclient/calls/elasticSearchCall.js +++ b/lib/elasticsearchclient/calls/elasticSearchCall.js @@ -13,6 +13,7 @@ function ElasticSearchCall(params, options, cb) { self.defaultMethod = options.defaultMethod || 'GET'; self.auth = options.auth || false; self.params = params || {}; + self.parseJSON = options.parseJSON || false; self.path = [ options.pathPrefix || '', options.path || ''].join(''); self.timeout = options.timeout || false; self.callback = cb || false; @@ -65,6 +66,7 @@ ElasticSearchCall.prototype.exec = function (cb) { body += chunk; }); response.on('end', function () { + if (self.parseJSON) body = JSON.parse(body); if (typeof self.callback == 'function') { self.callback(undefined, body); } else { diff --git a/package.json b/package.json index 8a74631..29682ad 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "name": "elasticsearchclient", "description": "A client for Elastic Search", "keywords": ["elasticsearch", "elastic", "search", "client"], - "version": "0.5.1", + "version": "0.5.2", "repository": { "url": "" }, diff --git a/test/core.test.js b/test/core.test.js index 0613696..4406116 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -421,4 +421,18 @@ describe("ElasticSearchClient Core api", function(){ .exec(); }); }); + + describe('#automatically parse JSON', function() { + it('should automatically parse the JSON response into an object', function(done) { + var serverOptionsWithParseJSON = JSON.parse(JSON.stringify(serverOptions)); + serverOptionsWithParseJSON.parseJSON = true; + var elasticSearchClient = new ElasticSearchClient(serverOptionsWithParseJSON; + elasticSearchClient.get(indexName, objName, "sushi") + .on('data', function(data) { + data.should.be.an('object'); + done(); + }) + .exec(); + }); + }); });