-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathmockttp-admin-request-builder.ts
408 lines (365 loc) · 14.7 KB
/
mockttp-admin-request-builder.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import _ = require('lodash');
import gql from 'graphql-tag';
import { MockedEndpoint, MockedEndpointData } from "../types";
import { buildBodyReader } from '../util/request-utils';
import { objectHeadersToRaw, rawHeadersToObject } from '../util/header-utils';
import type { Serialized } from '../serialization/serialization';
import { AdminQuery } from './admin-query';
import { SchemaIntrospector } from './schema-introspection';
import type { RequestRuleData } from "../rules/requests/request-rule";
import type { WebSocketRuleData } from '../rules/websockets/websocket-rule';
import { SubscribableEvent } from '../mockttp';
import { MockedEndpointClient } from "./mocked-endpoint-client";
import { AdminClient } from './admin-client';
function normalizeHttpMessage(message: any, event?: SubscribableEvent) {
if (message.timingEvents) {
// Timing events are serialized as raw JSON
message.timingEvents = JSON.parse(message.timingEvents);
} else if (event !== 'tls-client-error' && event !== 'client-error') {
// For backwards compat, all except errors should have timing events if they're missing
message.timingEvents = {};
}
if (message.rawHeaders) {
message.rawHeaders = JSON.parse(message.rawHeaders);
// We use raw headers where possible to derive headers, instead of using any pre-derived
// header data, for maximum accuracy (and to avoid any need to query for both).
message.headers = rawHeadersToObject(message.rawHeaders);
} else if (message.headers) {
// Backward compat for older servers:
message.headers = JSON.parse(message.headers);
message.rawHeaders = objectHeadersToRaw(message.headers);
}
if (message.body !== undefined) {
// Body is serialized as the raw encoded buffer in base64
message.body = buildBodyReader(Buffer.from(message.body, 'base64'), message.headers);
}
// For backwards compat, all except errors should have tags if they're missing
if (!message.tags) message.tags = [];
}
export class MockttpAdminRequestBuilder {
constructor(
private schema: SchemaIntrospector
) {}
buildAddRequestRulesQuery(
rules: Array<Serialized<RequestRuleData>>,
reset: boolean
): AdminQuery<
{ endpoints: Array<{ id: string, explanation?: string }> },
MockedEndpoint[]
> {
const requestName = (reset ? 'Set' : 'Add') + 'Rules';
const mutationName = (reset ? 'set' : 'add') + 'Rules';
return {
query: gql`
mutation ${requestName}($newRules: [MockRule!]!) {
endpoints: ${mutationName}(input: $newRules) {
id,
${this.schema.asOptionalField('MockedEndpoint', 'explanation')}
}
}
`,
variables: {
newRules: rules
},
transformResponse: (response, { adminClient }) => {
return response.endpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
)
}
};
}
buildAddWebSocketRulesQuery(
rules: Array<Serialized<WebSocketRuleData>>,
reset: boolean
): AdminQuery<
{ endpoints: Array<{ id: string, explanation?: string }> },
MockedEndpoint[]
> {
// Seperate and simpler than buildAddRequestRulesQuery, because it doesn't have to
// deal with backward compatibility.
const requestName = (reset ? 'Set' : 'Add') + 'WebSocketRules';
const mutationName = (reset ? 'set' : 'add') + 'WebSocketRules';
return {
query: gql`
mutation ${requestName}($newRules: [WebSocketMockRule!]!) {
endpoints: ${mutationName}(input: $newRules) {
id,
explanation
}
}
`,
variables: {
newRules: rules
},
transformResponse: (response, { adminClient }) => {
return response.endpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
};
buildMockedEndpointsQuery(): AdminQuery<
{ mockedEndpoints: MockedEndpointData[] },
MockedEndpoint[]
> {
return {
query: gql`
query GetAllEndpointData {
mockedEndpoints {
id,
${this.schema.asOptionalField('MockedEndpoint', 'explanation')}
}
}
`,
transformResponse: (response, { adminClient }) => {
const mockedEndpoints = response.mockedEndpoints;
return mockedEndpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
}
public buildPendingEndpointsQuery(): AdminQuery<
{ pendingEndpoints: MockedEndpointData[] },
MockedEndpoint[]
> {
return {
query: gql`
query GetPendingEndpointData {
pendingEndpoints {
id,
explanation
}
}
`,
transformResponse: (response, { adminClient }) => {
const pendingEndpoints = response.pendingEndpoints;
return pendingEndpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
}
public buildSubscriptionRequest<T>(event: SubscribableEvent): AdminQuery<unknown, T> {
// Note the asOptionalField checks - these are a quick hack for backward compatibility,
// introspecting the server schema to avoid requesting fields that don't exist on old servers.
const query = {
'request-initiated': gql`subscription OnRequestInitiated {
requestInitiated {
id,
protocol,
method,
url,
path,
${this.schema.asOptionalField('InitiatedRequest', 'remoteIpAddress')},
${this.schema.asOptionalField('InitiatedRequest', 'remotePort')},
hostname,
${this.schema.typeHasField('InitiatedRequest', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
timingEvents,
httpVersion,
${this.schema.asOptionalField('InitiatedRequest', 'tags')}
}
}`,
request: gql`subscription OnRequest {
requestReceived {
id,
${this.schema.asOptionalField('Request', 'matchedRuleId')}
protocol,
method,
url,
path,
${this.schema.asOptionalField('Request', 'remoteIpAddress')},
${this.schema.asOptionalField('Request', 'remotePort')},
hostname,
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'httpVersion')}
${this.schema.asOptionalField('Request', 'tags')}
}
}`,
response: gql`subscription OnResponse {
responseCompleted {
id,
statusCode,
statusMessage,
${this.schema.typeHasField('Response', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Response', 'timingEvents')}
${this.schema.asOptionalField('Response', 'tags')}
}
}`,
abort: gql`subscription OnAbort {
requestAborted {
id,
protocol,
method,
url,
path,
hostname,
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'tags')}
}
}`,
'tls-client-error': gql`subscription OnTlsClientError {
failedTlsRequest {
failureCause
hostname
remoteIpAddress
${this.schema.asOptionalField('TlsRequest', 'remotePort')}
${this.schema.asOptionalField('TlsRequest', 'tags')}
${this.schema.asOptionalField('TlsRequest', 'timingEvents')}
}
}`,
'client-error': gql`subscription OnClientError {
failedClientRequest {
errorCode
request {
id
timingEvents
tags
protocol
httpVersion
method
url
path
${this.schema.typeHasField('ClientErrorRequest', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
${this.schema.asOptionalField('ClientErrorRequest', 'remoteIpAddress')},
${this.schema.asOptionalField('ClientErrorRequest', 'remotePort')},
}
response {
id
timingEvents
tags
statusCode
statusMessage
${this.schema.typeHasField('Response', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body
}
}
}`,
// TODO: This is just a copy of the previous client-error section. Needs to be finished.
'handle-error': gql`subscription OnError {
failedRequest {
errorCode
request {
id
timingEvents
tags
protocol
httpVersion
method
url
path
${this.schema.typeHasField('ClientErrorRequest', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
${this.schema.asOptionalField('ClientErrorRequest', 'remoteIpAddress')},
${this.schema.asOptionalField('ClientErrorRequest', 'remotePort')},
}
response {
id
timingEvents
tags
statusCode
statusMessage
${this.schema.typeHasField('Response', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body
}
}
}`
}[event];
return {
query,
transformResponse: (data: any): T => {
if (event === 'client-error') {
data.request = _.mapValues(data.request, (v) =>
// Normalize missing values to undefined to match the local result
v === null ? undefined : v
);
normalizeHttpMessage(data.request, event);
if (data.response) {
normalizeHttpMessage(data.response, event);
} else {
data.response = 'aborted';
}
} else {
normalizeHttpMessage(data, event);
}
return data;
}
};
}
private getEndpointDataGetter = (adminClient: AdminClient<{}>, ruleId: string) =>
async (): Promise<MockedEndpointData | null> => {
let result = await adminClient.sendQuery<{
mockedEndpoint: MockedEndpointData | null
}>({
query: gql`
query GetEndpointData($id: ID!) {
mockedEndpoint(id: $id) {
seenRequests {
protocol,
method,
url,
path,
hostname
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'httpVersion')}
}
${this.schema.asOptionalField('MockedEndpoint', 'isPending')}
}
}
`,
variables: { id: ruleId }
});
const mockedEndpoint = result.mockedEndpoint;
if (!mockedEndpoint) return null;
mockedEndpoint.seenRequests.forEach(req => normalizeHttpMessage(req));
return mockedEndpoint;
}
}