-
Notifications
You must be signed in to change notification settings - Fork 41
/
request-handler.ts
145 lines (119 loc) · 4.44 KB
/
request-handler.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import TapeStore from "./tape-store"
import { v4 as uuidv4 } from 'uuid';
import fetch from 'node-fetch'
import Tape from "./tape"
import OptionsFactory, { RecordMode, FallbackMode, Options } from "./options"
import ErrorRate from "./features/error-rate"
import Latency from "./features/latency"
import { HttpRequest, HttpResponse, MatchingContext } from "./types"
import { Logger } from "./logger"
export default class RequestHandler {
private readonly tapeStore: TapeStore
private readonly options: Options
private readonly errorRate: ErrorRate
private readonly latency: Latency
private readonly logger: Logger;
constructor(tapeStore: TapeStore, options: Options) {
this.tapeStore = tapeStore
this.options = options
this.errorRate = new ErrorRate(this.options)
this.latency = new Latency(this.options)
this.logger = Logger.for(this.options)
}
async handle(req: HttpRequest): Promise<HttpResponse> {
const matchingContext: MatchingContext = {
id: uuidv4()
}
const recordMode = typeof (this.options.record) === "string" ? this.options.record : this.options.record(req)
OptionsFactory.validateRecord(recordMode)
if (this.options.requestDecorator) {
req = this.options.requestDecorator(req, matchingContext)
if (!req) {
throw new Error("requestDecorator didn't return a req object")
}
}
let newTape = new Tape(req, this.options)
let matchingTape = this.tapeStore.find(newTape)
let resObj, responseTape
if (recordMode !== RecordMode.OVERWRITE && matchingTape) {
responseTape = matchingTape
if (this.errorRate.shouldSimulate(req, matchingTape)) {
return this.errorRate.simulate(req)
}
await this.latency.simulate(req, matchingTape)
} else {
if (matchingTape) {
responseTape = matchingTape
} else {
responseTape = newTape
}
if (recordMode === RecordMode.NEW || recordMode === RecordMode.OVERWRITE) {
resObj = await this.makeRealRequest(req)
responseTape.res = { ...resObj }
if (this.options.tapeDecorator) {
responseTape = this.options.tapeDecorator(responseTape, matchingContext)
if (!responseTape) {
throw new Error("tapeDecorator didn't return a tape object")
}
}
await this.tapeStore.save(responseTape)
} else {
resObj = await this.onNoRecord(req)
responseTape.res = { ...resObj }
}
}
resObj = responseTape.res
if (this.options.responseDecorator) {
const clonedTape = await responseTape.clone()
const resTape = this.options.responseDecorator(clonedTape, req, matchingContext)
if (!resTape) {
throw new Error("responseDecorator didn't return a tape object")
}
if (resTape.res.headers["content-length"]) {
resTape.res.headers["content-length"] = resTape.res.body.length
}
resObj = resTape.res
}
return resObj
}
private async onNoRecord(req: HttpRequest) {
const fallbackMode = typeof (this.options.fallbackMode) === "string" ? this.options.fallbackMode : this.options.fallbackMode(req)
OptionsFactory.validateFallbackMode(fallbackMode)
this.logger.info(`Tape for ${req.url} not found and recording is disabled (fallbackMode: ${fallbackMode})`)
this.logger.info({
url: req.url,
headers: req.headers
})
if (fallbackMode === FallbackMode.PROXY) {
if (this.errorRate.shouldSimulate(req, undefined)) {
return this.errorRate.simulate(req)
}
await this.latency.simulate(req, undefined)
return await this.makeRealRequest(req)
}
return {
status: 404,
headers: { "content-type": ["text/plain"] },
body: Buffer.from("talkback - tape not found")
} as HttpResponse
}
private async makeRealRequest(req: HttpRequest) {
let fetchBody: Buffer | null
let { method, url, body } = req
fetchBody = body
const headers = { ...req.headers }
delete headers.host
const host = this.options.host
this.logger.info(`Making real request to ${host}${url}`)
if (method === "GET" || method === "HEAD") {
fetchBody = null
}
const fRes = await fetch(host + url, { method, headers, body: fetchBody, compress: false, redirect: "manual", ...this.options.httpClient.fetchOptions })
const buff = await fRes.buffer()
return {
status: fRes.status,
headers: fRes.headers.raw(),
body: buff
} as HttpResponse
}
}