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