diff --git a/lib/Transport.js b/lib/Transport.js index 3ea692b3a..265f006f6 100644 --- a/lib/Transport.js +++ b/lib/Transport.js @@ -20,6 +20,7 @@ 'use strict' const debug = require('debug')('elasticsearch') +const os = require('os') const once = require('once') const { createGzip } = require('zlib') const intoStream = require('into-stream') @@ -34,6 +35,9 @@ const { const noop = () => {} +const clientVersion = require('../package.json').version +const userAgent = `elasticsearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${process.version})` + class Transport { constructor (opts = {}) { if (typeof opts.compression === 'string' && opts.compression !== 'gzip') { @@ -46,7 +50,7 @@ class Transport { this.requestTimeout = toMs(opts.requestTimeout) this.suggestCompression = opts.suggestCompression === true this.compression = opts.compression || false - this.headers = opts.headers || {} + this.headers = Object.assign({}, { 'User-Agent': userAgent }, opts.headers) this.sniffInterval = opts.sniffInterval this.sniffOnConnectionFault = opts.sniffOnConnectionFault this.sniffEndpoint = opts.sniffEndpoint diff --git a/test/unit/transport.test.js b/test/unit/transport.test.js index b9e079dc3..867483863 100644 --- a/test/unit/transport.test.js +++ b/test/unit/transport.test.js @@ -22,6 +22,7 @@ const { test } = require('tap') const { URL } = require('url') const { createGunzip } = require('zlib') +const os = require('os') const intoStream = require('into-stream') const { buildServer, @@ -2111,6 +2112,43 @@ test('Should accept custom querystring in the optons object', t => { t.end() }) +test('Should add an User-Agent header', t => { + t.plan(2) + const clientVersion = require('../../package.json').version + const userAgent = `elasticsearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${process.version})` + + function handler (req, res) { + t.match(req.headers, { + 'user-agent': userAgent + }) + res.setHeader('Content-Type', 'application/json;utf=8') + res.end(JSON.stringify({ hello: 'world' })) + } + + buildServer(handler, ({ port }, server) => { + const pool = new ConnectionPool({ Connection }) + pool.addConnection(`http://localhost:${port}`) + + const transport = new Transport({ + emit: () => {}, + connectionPool: pool, + serializer: new Serializer(), + maxRetries: 3, + requestTimeout: 30000, + sniffInterval: false, + sniffOnStart: false + }) + + transport.request({ + method: 'GET', + path: '/hello' + }, (err, { body }) => { + t.error(err) + server.stop() + }) + }) +}) + test('Should pass request params and options to generateRequestId', t => { t.plan(3)