# All files / lib/winston/transports http.js

41.25% Statements 33/80
38.78% Branches 19/49
50% Functions 6/12
41.56% Lines 32/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197

    1x
    1x
    1x
    1x

    1x

    2x

    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    1x
    1x

    1x

    1x

    1x
    1x

    1x

    1x
    1x

    1x
    1x

    1x

    1x
    1x
    1x

    1x

     /**
     * http.js: Transport for outputting to a json-rpcserver.
     *
     * (C) 2010 Charlie Robbins
     * MIT LICENCE
     */

    'use strict';

    const http = require('http');
    const https = require('https');
    const { Stream } = require('readable-stream');
    const TransportStream = require('winston-transport');

    /**
     * Transport for outputting to a json-rpc server.
     * @type {Stream}
     * @extends {TransportStream}
     */
    module.exports = class Http extends TransportStream {
      /**
       * Constructor function for the Http transport object responsible for
       * persisting log messages and metadata to a terminal or TTY.
       * @param {!Object} [options={}] - Options for this instance.
       */
      constructor(options = {}) {
        super(options);

        this.name = 'http';
        this.ssl = !!options.ssl;
        this.host = options.host || 'localhost';
        this.port = options.port;
        this.auth = options.auth;
        this.path = options.path || '';
        this.agent = options.agent;
        this.headers = options.headers || {};
        this.headers['content-type'] = 'application/json';

        Iif (!this.port) {
          this.port = this.ssl ? 443 : 80;
        }
      }

      /**
       * Core logging method exposed to Winston.
       * @param {Object} info - TODO: add param description.
       * @param {function} callback - TODO: add param description.
       * @returns {undefined}
       */
      log(info, callback) {
        this._request(info, (err, res) => {
          Iif (res && res.statusCode !== 200) {
            err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
          }

          Iif (err) {
            this.emit('warn', err);
          } else {
            this.emit('logged', info);
          }
        });

        // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
        // and block more requests from happening?
        Eif (callback) {
          setImmediate(callback);
        }
      }

      /**
       * Query the transport. Options object is optional.
       * @param {Object} options -  Loggly-like query options for this instance.
       * @param {function} callback - Continuation to respond to when complete.
       * @returns {undefined}
       */
      query(options, callback) {
        if (typeof options === 'function') {
          callback = options;
          options = {};
        }

        options = {
          method: 'query',
          params: this.normalizeQuery(options)
        };

        if (options.params.path) {
          options.path = options.params.path;
          delete options.params.path;
        }

        if (options.params.auth) {
          options.auth = options.params.auth;
          delete options.params.auth;
        }

        this._request(options, (err, res, body) => {
          if (res && res.statusCode !== 200) {
            err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
          }

          if (err) {
            return callback(err);
          }

          if (typeof body === 'string') {
            try {
              body = JSON.parse(body);
            } catch (e) {
              return callback(e);
            }
          }

          callback(null, body);
        });
      }

      /**
       * Returns a log stream for this transport. Options object is optional.
       * @param {Object} options - Stream options for this instance.
       * @returns {Stream} - TODO: add return description
       */
      stream(options = {}) {
        const stream = new Stream();
        options = {
          method: 'stream',
          params: options
        };

        if (options.params.path) {
          options.path = options.params.path;
          delete options.params.path;
        }

        if (options.params.auth) {
          options.auth = options.params.auth;
          delete options.params.auth;
        }

        let buff = '';
        const req = this._request(options);

        stream.destroy = () => req.destroy();
        req.on('data', data => {
          data = (buff + data).split(/\n+/);
          const l = data.length - 1;

          let i = 0;
          for (; i < l; i++) {
            try {
              stream.emit('log', JSON.parse(data[i]));
            } catch (e) {
              stream.emit('error', e);
            }
          }

          buff = data[l];
        });
        req.on('error', err => stream.emit('error', err));

        return stream;
      }

      /**
       * Make a request to a winstond server or any http server which can
       * handle json-rpc.
       * @param {function} options - Options to sent the request.
       * @param {function} callback - Continuation to respond to when complete.
       */
      _request(options, callback) {
        options = options || {};

        const auth = options.auth || this.auth;
        const path = options.path || this.path || '';

        delete options.auth;
        delete options.path;

        // Prepare options for outgoing HTTP request
        const req = (this.ssl ? https : http).request({
          method: 'POST',
          host: this.host,
          port: this.port,
          path: `/${path.replace(/^\//, '')}`,
          headers: this.headers,
          auth: auth ? (`${auth.username}:${auth.password}`) : '',
          agent: this.agent
        });

        req.on('error', callback);
        req.on('response', res => (
          res.on('end', () => callback(null, res)).resume()
        ));
        req.end(Buffer.from(JSON.stringify(options), 'utf8'));
      }
    };