# all files / lib/ ssdpHeader.js

97.37% Statements 37/38
76.47% Branches 13/17
100% Functions 10/10
100% Lines 37/37

    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
    721×

    1×
    16×
    16×
    16×
    16×

    16×

    1×
    4×

    1×
    31×
    31×

    1×
    16×
    16×

    1×
    17×

    1×
    3×

    1×
    17×

    1×
    17×

    17×
    17×

    17×

    17×

    17×
    5×

    12×

    17×
    119×

    17×

    17×

    1×
    17×

    1×var extend = require('extend')
      , random = require('crypto').randomBytes

    function SsdpHeader(method, headers, isResponse) {
      this._method = method
      this._headers = extend ({}, headers || {})
      this._isResponse = isResponse
      this._id = random(8).toString('hex')

      Iif (!this._method) throw new Error('SSDP header requires method.')
    }

    SsdpHeader.prototype.id = function () {
      return this._id
    }

    SsdpHeader.prototype.setHeader = function (key, value) {
      Eif (key !== undefined && value !== undefined) {
        this._headers[key] = value
      }
    }

    SsdpHeader.prototype.setHeaders = function (headers) {
      Eif (headers && headers.toString && headers.toString() === '[object Object]') {
        extend(this._headers, headers)
      }
    }

    SsdpHeader.prototype.isResponse = function () {
      return !!this._isResponse
    }

    SsdpHeader.prototype.overrideLocationOnSend = function () {
      this._overrideLocationOnSend = true
    }

    SsdpHeader.prototype.isOverrideLocationOnSend = function () {
      return !!this._overrideLocationOnSend
    }

    SsdpHeader.prototype.toString = function (extraHeaders) {
      extraHeaders = extraHeaders || {}

      // SSDP header values should be simple primitives
      // so not worried here about deep copying or modifying by reference
      var headers = extend({}, this._headers)
      extend(headers, extraHeaders)

      var message = []

      var method = this._method.toUpperCase()

      if (this.isResponse()) {
        message.push('HTTP/1.1 ' + method)
      } else {
        message.push(method + ' * HTTP/1.1')
      }

      Object.keys(headers).forEach(function (header) {
        message.push(header + ': ' + headers[header])
      })

      message.push('\r\n')

      return message.join('\r\n')
    }

    SsdpHeader.prototype.toBuffer = function (extraHeaders) {
      return Buffer.from(this.toString(extraHeaders), 'ascii')
    }

    module.exports = SsdpHeader