1 | 'use strict'
|
2 |
|
3 | const _ = require('lodash')
|
4 | const querystring = require('querystring')
|
5 |
|
6 | const common = require('./common')
|
7 |
|
8 | module.exports = function matchBody(options, spec, body) {
|
9 | if (spec instanceof RegExp) {
|
10 | return spec.test(body)
|
11 | }
|
12 |
|
13 | if (Buffer.isBuffer(spec)) {
|
14 | const encoding = common.isUtf8Representable(spec) ? 'utf8' : 'hex'
|
15 | spec = spec.toString(encoding)
|
16 | }
|
17 |
|
18 | const contentType = (
|
19 | (options.headers &&
|
20 | (options.headers['Content-Type'] || options.headers['content-type'])) ||
|
21 | ''
|
22 | ).toString()
|
23 |
|
24 | const isMultipart = contentType.includes('multipart')
|
25 | const isUrlencoded = contentType.includes('application/x-www-form-urlencoded')
|
26 |
|
27 |
|
28 | let json
|
29 | if (typeof spec === 'object' || typeof spec === 'function') {
|
30 | try {
|
31 | json = JSON.parse(body)
|
32 | } catch (err) {
|
33 |
|
34 | }
|
35 | if (json !== undefined) {
|
36 | body = json
|
37 | } else if (isUrlencoded) {
|
38 | body = querystring.parse(body)
|
39 | }
|
40 | }
|
41 |
|
42 | if (typeof spec === 'function') {
|
43 | return spec.call(options, body)
|
44 | }
|
45 |
|
46 |
|
47 |
|
48 | if (!isMultipart && typeof body === 'string') {
|
49 | body = body.replace(/\r?\n|\r/g, '')
|
50 | }
|
51 |
|
52 | if (!isMultipart && typeof spec === 'string') {
|
53 | spec = spec.replace(/\r?\n|\r/g, '')
|
54 | }
|
55 |
|
56 |
|
57 |
|
58 | if (isUrlencoded) {
|
59 | spec = mapValuesDeep(spec, val => (val instanceof RegExp ? val : `${val}`))
|
60 | }
|
61 |
|
62 | return common.dataEqual(spec, body)
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | function mapValuesDeep(obj, cb) {
|
70 | if (Array.isArray(obj)) {
|
71 | return obj.map(v => mapValuesDeep(v, cb))
|
72 | }
|
73 | if (_.isPlainObject(obj)) {
|
74 | return _.mapValues(obj, v => mapValuesDeep(v, cb))
|
75 | }
|
76 | return cb(obj)
|
77 | }
|