user21398
user21398

Reputation: 1493

Sharing elasticsearch client in multiple expressjs routes

I'm trying to reorganize my gigantic expressjs routes into smaller chunks by creating separate files. However, several need to connect to the elasticsearch client to perform searches:

routes/index.js

var router = require('express').Router();
var models = require("../models");
var es = require('elasticsearch');
var es_client = new elasticsearch.Client({
        host: 'localhost:9200',
        log: 'trace'
});

router.get('/search', function(req, res) {
     // Do search in elasticsearch
     // es_client.search({......});
});

module.exports = router;

routes/user.js

var router = require('express').Router();
var models = require("../models");
var es = require('elasticsearch');
var es_client = new elasticsearch.Client({
        host: 'localhost:9200',
        log: 'trace'
});

router.get('/user/search', function(req, res) {
     // Do search in elasticsearch
     // es_client.search({......});
});

module.exports = router;

But this doesn't make sense since the routes are trying to connect to the es client twice, which will fail due to 'connection in use error'.

What is a good way to allow my routes files to connect to elasticsearch for searching?

Upvotes: 3

Views: 819

Answers (1)

azero0
azero0

Reputation: 2310

make a elastic.js file which is something like this:

var elasticsearch = require('elasticsearch');
exports.es_client = new elasticsearch.Client({
                               host: 'localhost:9200',
                                log: 'trace'
});

and use this in your index.js and user.js.

For eg:- in user.js do this:

var router = require('express').Router();
var models = require("../models");
var elastic = require("./elastic");

router.get('/user/search', function(req, res) {
     // Do search in elasticsearch
     // elastic.es_client.search({......});
});

Upvotes: 2

Related Questions