Code coverage report for nock/lib/match_body.js

Statements: 97.3% (36 / 37)      Branches: 97.5% (39 / 40)      Functions: 100% (2 / 2)      Lines: 97.22% (35 / 36)      Ignored: none     

All files » nock/lib/ » match_body.js
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    1 1   1   229 186   43   43       43     43       43 40     43 1     42 31       42 42 11 11 5   6 1         42 4     38     1 47 1   46 8 8 9 1     7   38    
'use strict';
 
var deepEqual = require('deep-equal');
var qs = require('querystring');
 
module.exports =
function matchBody(spec, body) {
  if (typeof spec === 'undefined') {
    return true;
  }
  var options = this || {};
 
  Iif (Buffer.isBuffer(body)) {
    body = body.toString();
  }
 
  var contentType = options.headers && (options.headers['Content-Type'] ||
                                        options.headers['content-type']);
 
  var isMultipart = contentType && contentType.toString().match(/multipart/);
 
  //strip line endings from both so that we get a match no matter what OS we are running on
  //if Content-Type does not contains 'multipart'
  if (!isMultipart) {
    body = body.replace(/\r?\n|\r/g, '');
  }
 
  if (spec instanceof RegExp) {
    return body.match(spec);
  }
 
  if (typeof spec === "string") {
    spec = spec.replace(/\r?\n|\r/g, '');
  }
 
  // try to transform body to json
  var json;
  if (typeof spec === 'object' || typeof spec === 'function') {
    try { json = JSON.parse(body);} catch(err) {}
    if (json !== undefined) {
      body = json;
    } else {
      if (contentType && contentType.toString().match(/application\/x-www-form-urlencoded/)) {
        body = qs.parse(body);
      }
    }
  }
 
  if (typeof spec === "function") {
    return spec.call(this, body);
  }
 
  return deepEqualExtended(spec, body);
};
 
function deepEqualExtended(spec, body) {
  if (spec && spec.constructor === RegExp) {
    return spec.test(body);
  }
  if (spec && spec.constructor === Object && body) {
    var keys = Object.keys(spec);
    for (var i = 0; i < keys.length; i++) {
      if (!deepEqualExtended(spec[keys[i]], body[keys[i]])) {
        return false;
      }
    }
    return true;
  }
  return deepEqual(spec, body, { strict: true });
}