1 | 'use strict'
|
2 |
|
3 | const debug = require('debug')('nock.interceptor')
|
4 | const stringify = require('json-stringify-safe')
|
5 | const _ = require('lodash')
|
6 | const querystring = require('querystring')
|
7 | const { URL, URLSearchParams } = require('url')
|
8 |
|
9 | const common = require('./common')
|
10 | const { remove } = require('./intercept')
|
11 | const matchBody = require('./match_body')
|
12 |
|
13 | let fs
|
14 | try {
|
15 | fs = require('fs')
|
16 | } catch (err) {
|
17 |
|
18 | }
|
19 |
|
20 | module.exports = class Interceptor {
|
21 | |
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | constructor(scope, uri, method, requestBody, interceptorOptions) {
|
32 | const uriIsStr = typeof uri === 'string'
|
33 |
|
34 |
|
35 |
|
36 | if (
|
37 | !scope.scopeOptions.filteringScope &&
|
38 | uriIsStr &&
|
39 | !uri.startsWith('/') &&
|
40 | !uri.startsWith('*')
|
41 | ) {
|
42 | throw Error(
|
43 | `Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`
|
44 | )
|
45 | }
|
46 |
|
47 | if (!method) {
|
48 | throw new Error(
|
49 | 'The "method" parameter is required for an intercept call.'
|
50 | )
|
51 | }
|
52 |
|
53 | this.scope = scope
|
54 | this.interceptorMatchHeaders = []
|
55 | this.method = method.toUpperCase()
|
56 | this.uri = uri
|
57 | this._key = `${this.method} ${scope.basePath}${scope.basePathname}${
|
58 | uriIsStr ? '' : '/'
|
59 | }${uri}`
|
60 | this.basePath = this.scope.basePath
|
61 | this.path = uriIsStr ? scope.basePathname + uri : uri
|
62 | this.queries = null
|
63 |
|
64 | this.options = interceptorOptions || {}
|
65 | this.counter = 1
|
66 | this._requestBody = requestBody
|
67 |
|
68 |
|
69 | this.reqheaders = common.headersFieldNamesToLowerCase(
|
70 | scope.scopeOptions.reqheaders || {}
|
71 | )
|
72 | this.badheaders = common.headersFieldsArrayToLowerCase(
|
73 | scope.scopeOptions.badheaders || []
|
74 | )
|
75 |
|
76 | this.delayInMs = 0
|
77 | this.delayConnectionInMs = 0
|
78 |
|
79 | this.optional = false
|
80 |
|
81 |
|
82 | if (uriIsStr && uri.includes('?')) {
|
83 |
|
84 | const parsedURL = new URL(this.path, 'http://localhost')
|
85 | this.path = parsedURL.pathname
|
86 | this.query(parsedURL.searchParams)
|
87 | this._key = `${this.method} ${scope.basePath}${this.path}`
|
88 | }
|
89 | }
|
90 |
|
91 | optionally(flag = true) {
|
92 |
|
93 | if (typeof flag !== 'boolean') {
|
94 | throw new Error('Invalid arguments: argument should be a boolean')
|
95 | }
|
96 |
|
97 | this.optional = flag
|
98 |
|
99 | return this
|
100 | }
|
101 |
|
102 | replyWithError(errorMessage) {
|
103 | this.errorMessage = errorMessage
|
104 |
|
105 | this.options = {
|
106 | ...this.scope.scopeOptions,
|
107 | ...this.options,
|
108 | }
|
109 |
|
110 | this.scope.add(this._key, this)
|
111 | return this.scope
|
112 | }
|
113 |
|
114 | reply(statusCode, body, rawHeaders) {
|
115 |
|
116 | if (typeof statusCode === 'function') {
|
117 | if (arguments.length > 1) {
|
118 |
|
119 |
|
120 | throw Error(
|
121 | 'Invalid arguments. When providing a function for the first argument, .reply does not accept other arguments.'
|
122 | )
|
123 | }
|
124 | this.statusCode = null
|
125 | this.fullReplyFunction = statusCode
|
126 | } else {
|
127 | if (statusCode !== undefined && !Number.isInteger(statusCode)) {
|
128 | throw new Error(`Invalid ${typeof statusCode} value for status code`)
|
129 | }
|
130 |
|
131 | this.statusCode = statusCode || 200
|
132 | if (typeof body === 'function') {
|
133 | this.replyFunction = body
|
134 | body = null
|
135 | }
|
136 | }
|
137 |
|
138 | this.options = {
|
139 | ...this.scope.scopeOptions,
|
140 | ...this.options,
|
141 | }
|
142 |
|
143 | this.rawHeaders = common.headersInputToRawArray(rawHeaders)
|
144 |
|
145 | if (this.scope.date) {
|
146 |
|
147 | this.rawHeaders.push('Date', this.scope.date.toUTCString())
|
148 | }
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 | this.headers = common.headersArrayToObject(
|
155 | this.rawHeaders.concat(this.scope._defaultReplyHeaders)
|
156 | )
|
157 |
|
158 |
|
159 |
|
160 | if (
|
161 | body &&
|
162 | typeof body !== 'string' &&
|
163 | !Buffer.isBuffer(body) &&
|
164 | !common.isStream(body) &&
|
165 | !common.isContentEncoded(this.headers)
|
166 | ) {
|
167 | try {
|
168 | body = stringify(body)
|
169 | } catch (err) {
|
170 | throw new Error('Error encoding response body into JSON')
|
171 | }
|
172 |
|
173 | if (!this.headers['content-type']) {
|
174 |
|
175 | this.rawHeaders.push('Content-Type', 'application/json')
|
176 | }
|
177 |
|
178 | if (this.scope.contentLen) {
|
179 |
|
180 | this.rawHeaders.push('Content-Length', body.length)
|
181 | }
|
182 | }
|
183 |
|
184 | debug('reply.headers:', this.headers)
|
185 | debug('reply.rawHeaders:', this.rawHeaders)
|
186 |
|
187 | this.body = body
|
188 |
|
189 | this.scope.add(this._key, this)
|
190 | return this.scope
|
191 | }
|
192 |
|
193 | replyWithFile(statusCode, filePath, headers) {
|
194 | if (!fs) {
|
195 | throw new Error('No fs')
|
196 | }
|
197 | const readStream = fs.createReadStream(filePath)
|
198 | readStream.pause()
|
199 | this.filePath = filePath
|
200 | return this.reply(statusCode, readStream, headers)
|
201 | }
|
202 |
|
203 |
|
204 |
|
205 | reqheaderMatches(options, key) {
|
206 | const reqHeader = this.reqheaders[key]
|
207 | let header = options.headers[key]
|
208 |
|
209 |
|
210 |
|
211 | if (header && typeof header !== 'string' && header.toString) {
|
212 | header = header.toString()
|
213 | }
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 | if (key === 'host' && (header === undefined || reqHeader === undefined)) {
|
220 | return true
|
221 | }
|
222 |
|
223 | if (reqHeader !== undefined && header !== undefined) {
|
224 | if (typeof reqHeader === 'function') {
|
225 | return reqHeader(header)
|
226 | } else if (common.matchStringOrRegexp(header, reqHeader)) {
|
227 | return true
|
228 | }
|
229 | }
|
230 |
|
231 | debug("request header field doesn't match:", key, header, reqHeader)
|
232 | return false
|
233 | }
|
234 |
|
235 | match(req, options, body) {
|
236 | if (debug.enabled) {
|
237 | debug('match %s, body = %s', stringify(options), stringify(body))
|
238 | }
|
239 |
|
240 | const method = (options.method || 'GET').toUpperCase()
|
241 | let { path = '/' } = options
|
242 | let matches
|
243 | let matchKey
|
244 | const { proto } = options
|
245 |
|
246 | if (this.method !== method) {
|
247 | debug(
|
248 | `Method did not match. Request ${method} Interceptor ${this.method}`
|
249 | )
|
250 | return false
|
251 | }
|
252 |
|
253 | if (this.scope.transformPathFunction) {
|
254 | path = this.scope.transformPathFunction(path)
|
255 | }
|
256 |
|
257 | const requestMatchesFilter = ({ name, value: predicate }) => {
|
258 | const headerValue = req.getHeader(name)
|
259 | if (typeof predicate === 'function') {
|
260 | return predicate(headerValue)
|
261 | } else {
|
262 | return common.matchStringOrRegexp(headerValue, predicate)
|
263 | }
|
264 | }
|
265 |
|
266 | if (
|
267 | !this.scope.matchHeaders.every(requestMatchesFilter) ||
|
268 | !this.interceptorMatchHeaders.every(requestMatchesFilter)
|
269 | ) {
|
270 | this.scope.logger("headers don't match")
|
271 | return false
|
272 | }
|
273 |
|
274 | const reqHeadersMatch = Object.keys(this.reqheaders).every(key =>
|
275 | this.reqheaderMatches(options, key)
|
276 | )
|
277 |
|
278 | if (!reqHeadersMatch) {
|
279 | return false
|
280 | }
|
281 |
|
282 | if (
|
283 | this.scope.scopeOptions.conditionally &&
|
284 | !this.scope.scopeOptions.conditionally()
|
285 | ) {
|
286 | return false
|
287 | }
|
288 |
|
289 | const reqContainsBadHeaders = this.badheaders.some(
|
290 | header => header in options.headers
|
291 | )
|
292 |
|
293 | if (reqContainsBadHeaders) {
|
294 | return false
|
295 | }
|
296 |
|
297 |
|
298 | if (this.queries === null) {
|
299 | debug('query matching skipped')
|
300 | } else {
|
301 |
|
302 | const [pathname, search] = path.split('?')
|
303 | const matchQueries = this.matchQuery({ search })
|
304 |
|
305 | debug(matchQueries ? 'query matching succeeded' : 'query matching failed')
|
306 |
|
307 | if (!matchQueries) {
|
308 | return false
|
309 | }
|
310 |
|
311 |
|
312 |
|
313 | path = pathname
|
314 | }
|
315 |
|
316 |
|
317 |
|
318 |
|
319 |
|
320 | if (this.__nock_filteredScope) {
|
321 | matchKey = this.__nock_filteredScope
|
322 | } else {
|
323 | matchKey = common.normalizeOrigin(proto, options.host, options.port)
|
324 | }
|
325 |
|
326 | if (typeof this.uri === 'function') {
|
327 | matches =
|
328 | common.matchStringOrRegexp(matchKey, this.basePath) &&
|
329 |
|
330 |
|
331 | this.uri.call(this, path)
|
332 | } else {
|
333 | matches =
|
334 | common.matchStringOrRegexp(matchKey, this.basePath) &&
|
335 | common.matchStringOrRegexp(path, this.path)
|
336 | }
|
337 |
|
338 | this.scope.logger(`matching ${matchKey}${path} to ${this._key}: ${matches}`)
|
339 |
|
340 | if (matches && this._requestBody !== undefined) {
|
341 | if (this.scope.transformRequestBodyFunction) {
|
342 | body = this.scope.transformRequestBodyFunction(body, this._requestBody)
|
343 | }
|
344 |
|
345 | matches = matchBody(options, this._requestBody, body)
|
346 | if (!matches) {
|
347 | this.scope.logger(
|
348 | "bodies don't match: \n",
|
349 | this._requestBody,
|
350 | '\n',
|
351 | body
|
352 | )
|
353 | }
|
354 | }
|
355 |
|
356 | return matches
|
357 | }
|
358 |
|
359 | |
360 |
|
361 |
|
362 |
|
363 | matchOrigin(options) {
|
364 | const isPathFn = typeof this.path === 'function'
|
365 | const isRegex = this.path instanceof RegExp
|
366 | const isRegexBasePath = this.scope.basePath instanceof RegExp
|
367 |
|
368 | const method = (options.method || 'GET').toUpperCase()
|
369 | let { path } = options
|
370 | const { proto } = options
|
371 |
|
372 |
|
373 | if (!isRegex) {
|
374 | path = path ? path.split('?')[0] : ''
|
375 | }
|
376 |
|
377 | if (this.scope.transformPathFunction) {
|
378 | path = this.scope.transformPathFunction(path)
|
379 | }
|
380 | const comparisonKey = isPathFn || isRegex ? this.__nock_scopeKey : this._key
|
381 | const matchKey = `${method} ${proto}://${options.host}${path}`
|
382 |
|
383 | if (isPathFn) {
|
384 | return !!(matchKey.match(comparisonKey) && this.path(path))
|
385 | }
|
386 |
|
387 | if (isRegex && !isRegexBasePath) {
|
388 | return !!matchKey.match(comparisonKey) && this.path.test(path)
|
389 | }
|
390 |
|
391 | if (isRegexBasePath) {
|
392 | return this.scope.basePath.test(matchKey) && !!path.match(this.path)
|
393 | }
|
394 |
|
395 | return comparisonKey === matchKey
|
396 | }
|
397 |
|
398 | matchHostName(options) {
|
399 | return options.hostname === this.scope.urlParts.hostname
|
400 | }
|
401 |
|
402 | matchQuery(options) {
|
403 | if (this.queries === true) {
|
404 | return true
|
405 | }
|
406 |
|
407 | const reqQueries = querystring.parse(options.search)
|
408 | debug('Interceptor queries: %j', this.queries)
|
409 | debug(' Request queries: %j', reqQueries)
|
410 |
|
411 | if (typeof this.queries === 'function') {
|
412 | return this.queries(reqQueries)
|
413 | }
|
414 |
|
415 | return common.dataEqual(this.queries, reqQueries)
|
416 | }
|
417 |
|
418 | filteringPath(...args) {
|
419 | this.scope.filteringPath(...args)
|
420 | return this
|
421 | }
|
422 |
|
423 |
|
424 |
|
425 |
|
426 | markConsumed() {
|
427 | this.interceptionCounter++
|
428 |
|
429 | remove(this)
|
430 |
|
431 | if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) {
|
432 | this.body = fs.createReadStream(this.filePath)
|
433 | this.body.pause()
|
434 | }
|
435 |
|
436 | if (!this.scope.shouldPersist() && this.counter < 1) {
|
437 | this.scope.remove(this._key, this)
|
438 | }
|
439 | }
|
440 |
|
441 | matchHeader(name, value) {
|
442 | this.interceptorMatchHeaders.push({ name, value })
|
443 | return this
|
444 | }
|
445 |
|
446 | basicAuth({ user, pass = '' }) {
|
447 | const encoded = Buffer.from(`${user}:${pass}`).toString('base64')
|
448 | this.matchHeader('authorization', `Basic ${encoded}`)
|
449 | return this
|
450 | }
|
451 |
|
452 | |
453 |
|
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 | query(queries) {
|
462 | if (this.queries !== null) {
|
463 | throw Error(`Query parameters have already been defined`)
|
464 | }
|
465 |
|
466 |
|
467 | if (queries === true) {
|
468 | this.queries = queries
|
469 | return this
|
470 | }
|
471 |
|
472 | if (typeof queries === 'function') {
|
473 | this.queries = queries
|
474 | return this
|
475 | }
|
476 |
|
477 | let strFormattingFn
|
478 | if (this.scope.scopeOptions.encodedQueryParams) {
|
479 | strFormattingFn = common.percentDecode
|
480 | }
|
481 |
|
482 | if (queries instanceof URLSearchParams) {
|
483 |
|
484 |
|
485 | queries = querystring.parse(queries.toString())
|
486 | } else if (!_.isPlainObject(queries)) {
|
487 | throw Error(`Argument Error: ${queries}`)
|
488 | }
|
489 |
|
490 | this.queries = {}
|
491 | for (const [key, value] of Object.entries(queries)) {
|
492 | const formatted = common.formatQueryValue(key, value, strFormattingFn)
|
493 | const [formattedKey, formattedValue] = formatted
|
494 | this.queries[formattedKey] = formattedValue
|
495 | }
|
496 |
|
497 | return this
|
498 | }
|
499 |
|
500 | |
501 |
|
502 |
|
503 |
|
504 |
|
505 |
|
506 |
|
507 |
|
508 |
|
509 | times(newCounter) {
|
510 | if (newCounter < 1) {
|
511 | return this
|
512 | }
|
513 |
|
514 | this.counter = newCounter
|
515 |
|
516 | return this
|
517 | }
|
518 |
|
519 | |
520 |
|
521 |
|
522 |
|
523 |
|
524 |
|
525 |
|
526 |
|
527 | once() {
|
528 | return this.times(1)
|
529 | }
|
530 |
|
531 | |
532 |
|
533 |
|
534 |
|
535 |
|
536 |
|
537 |
|
538 |
|
539 | twice() {
|
540 | return this.times(2)
|
541 | }
|
542 |
|
543 | |
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 | thrice() {
|
552 | return this.times(3)
|
553 | }
|
554 |
|
555 | |
556 |
|
557 |
|
558 |
|
559 |
|
560 |
|
561 |
|
562 |
|
563 | delay(opts) {
|
564 | let headDelay
|
565 | let bodyDelay
|
566 | if (typeof opts === 'number') {
|
567 | headDelay = opts
|
568 | bodyDelay = 0
|
569 | } else if (typeof opts === 'object') {
|
570 | headDelay = opts.head || 0
|
571 | bodyDelay = opts.body || 0
|
572 | } else {
|
573 | throw new Error(`Unexpected input opts ${opts}`)
|
574 | }
|
575 |
|
576 | return this.delayConnection(headDelay).delayBody(bodyDelay)
|
577 | }
|
578 |
|
579 | |
580 |
|
581 |
|
582 |
|
583 |
|
584 |
|
585 | delayBody(ms) {
|
586 | this.delayInMs += ms
|
587 | return this
|
588 | }
|
589 |
|
590 | |
591 |
|
592 |
|
593 |
|
594 |
|
595 |
|
596 | delayConnection(ms) {
|
597 | this.delayConnectionInMs += ms
|
598 | return this
|
599 | }
|
600 |
|
601 | |
602 |
|
603 |
|
604 |
|
605 | getTotalDelay() {
|
606 | return this.delayInMs + this.delayConnectionInMs
|
607 | }
|
608 |
|
609 | |
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 | socketDelay(ms) {
|
616 | this.socketDelayInMs = ms
|
617 | return this
|
618 | }
|
619 | }
|