UNPKG

2.5 kBJavaScriptView Raw
1'use strict'
2
3const { EventEmitter } = require('events')
4const debug = require('debug')('nock.socket')
5
6module.exports = class Socket extends EventEmitter {
7 constructor(options) {
8 super()
9
10 if (options.proto === 'https') {
11 // https://github.com/nock/nock/issues/158
12 this.authorized = true
13 }
14
15 this.bufferSize = 0
16 this.writableLength = 0
17 this.writable = true
18 this.readable = true
19 this.pending = false
20 this.destroyed = false
21 this.connecting = true
22
23 // Undocumented flag used by ClientRequest to ensure errors aren't double-fired
24 this._hadError = false
25
26 // Maximum allowed delay. 0 means unlimited.
27 this.timeout = 0
28
29 const ipv6 = options.family === 6
30 this.remoteFamily = ipv6 ? 'IPv6' : 'IPv4'
31 this.localAddress = this.remoteAddress = ipv6 ? '::1' : '127.0.0.1'
32 this.localPort = this.remotePort = parseInt(options.port)
33 }
34
35 setNoDelay() {}
36 setKeepAlive() {}
37 resume() {}
38 ref() {}
39 unref() {}
40
41 address() {
42 return {
43 port: this.remotePort,
44 family: this.remoteFamily,
45 address: this.remoteAddress,
46 }
47 }
48
49 setTimeout(timeoutMs, fn) {
50 this.timeout = timeoutMs
51 if (fn) {
52 this.once('timeout', fn)
53 }
54 return this
55 }
56
57 /**
58 * Artificial delay that will trip socket timeouts when appropriate.
59 *
60 * Doesn't actually wait for time to pass.
61 * Timeout events don't necessarily end the request.
62 * While many clients choose to abort the request upon a timeout, Node itself does not.
63 */
64 applyDelay(delayMs) {
65 if (this.timeout && delayMs > this.timeout) {
66 debug('socket timeout')
67 this.emit('timeout')
68 }
69 }
70
71 getPeerCertificate() {
72 return Buffer.from(
73 (Math.random() * 10000 + Date.now()).toString()
74 ).toString('base64')
75 }
76
77 /**
78 * Denotes that no more I/O activity should happen on this socket.
79 *
80 * The implementation in Node if far more complex as it juggles underlying async streams.
81 * For the purposes of Nock, we just need it to set some flags and on the first call
82 * emit a 'close' and optional 'error' event. Both events propagate through the request object.
83 */
84 destroy(err) {
85 if (this.destroyed) {
86 return this
87 }
88
89 debug('socket destroy')
90 this.destroyed = true
91 this.readable = this.writable = false
92
93 process.nextTick(() => {
94 if (err) {
95 this._hadError = true
96 this.emit('error', err)
97 }
98 this.emit('close')
99 })
100
101 return this
102 }
103}