/
conditional-intercept.js
51 lines (38 loc) · 1.24 KB
/
conditional-intercept.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
const http = require('node:http')
const got = require('got')
const intercept = require('../index.js')
/**
* If request goes to example.com, respond with a mocked "Hello World" response.
* Otherwise let the request pass through
*
* @param {any} options
* @param {http.ClientRequest} request
*/
function onIntercept(options, request) {
if (options.hostname === 'example.com') {
return request.sendRealRequest()
}
const response = new http.IncomingMessage(request.socket)
// (1) set response header data
response.statusCode = 200
response.rawHeaders = []
response.headers = {}
// @ts-expect-error - no idea why `.req` is not typed on ClientRequest
request.res = response
// @ts-expect-error - no idea why `.res` is not typed on IncomingMessage
response.req = request
request.emit('response', response)
// (2) set response body data
response.push('Hello, world!')
// (3) finish the response
response.complete = true
response.push(null)
}
run()
async function run() {
intercept(onIntercept)
console.log(`await got('https://example.com').text()`)
console.log(await got('https://example.com').text())
console.log(`await got('https://google.com').text()`)
console.log(await got('https://google.com').text())
}