-
-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathSetupServerApi.ts
158 lines (136 loc) · 4.39 KB
/
SetupServerApi.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
import chalk from 'chalk'
import { invariant } from 'outvariant'
import {
BatchInterceptor,
HttpRequestEventMap,
Interceptor,
InterceptorReadyState,
IsomorphicResponse,
MockedResponse as MockedInterceptedResponse,
} from '@mswjs/interceptors'
import { SetupApi } from '../SetupApi'
import { RequestHandler } from '../handlers/RequestHandler'
import { LifeCycleEventsMap, SharedOptions } from '../sharedOptions'
import { RequiredDeep } from '../typeUtils'
import { mergeRight } from '../utils/internal/mergeRight'
import { MockedRequest } from '../utils/request/MockedRequest'
import { handleRequest } from '../utils/handleRequest'
import { devUtils } from '../utils/internal/devUtils'
/**
* @see https://github.com/mswjs/msw/pull/1399
*/
const { bold } = chalk
export type ServerLifecycleEventsMap = LifeCycleEventsMap<IsomorphicResponse>
const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {
onUnhandledRequest: 'warn',
}
export class SetupServerApi extends SetupApi<ServerLifecycleEventsMap> {
protected readonly interceptor: BatchInterceptor<
Array<Interceptor<HttpRequestEventMap>>,
HttpRequestEventMap
>
private resolvedOptions: RequiredDeep<SharedOptions>
constructor(
interceptors: Array<{
new (): Interceptor<HttpRequestEventMap>
}>,
...handlers: Array<RequestHandler>
) {
super(...handlers)
this.interceptor = new BatchInterceptor({
name: 'setup-server',
interceptors: interceptors.map((Interceptor) => new Interceptor()),
})
this.resolvedOptions = {} as RequiredDeep<SharedOptions>
this.init()
}
/**
* Subscribe to all requests that are using the interceptor object
*/
private init(): void {
this.interceptor.on('request', async (request) => {
const mockedRequest = new MockedRequest(request.url, {
...request,
body: await request.arrayBuffer(),
})
const response = await handleRequest<
MockedInterceptedResponse & { delay?: number }
>(
mockedRequest,
this.currentHandlers,
this.resolvedOptions,
this.emitter,
{
transformResponse(response) {
return {
status: response.status,
statusText: response.statusText,
headers: response.headers.all(),
body: response.body,
delay: response.delay,
}
},
},
)
if (response) {
// Delay Node.js responses in the listener so that
// the response lookup logic is not concerned with responding
// in any way. The same delay is implemented in the worker.
if (response.delay) {
await new Promise((resolve) => {
setTimeout(resolve, response.delay)
})
}
request.respondWith(response)
}
return
})
this.interceptor.on('response', (request, response) => {
if (!request.id) {
return
}
if (response.headers.get('x-powered-by') === 'msw') {
this.emitter.emit('response:mocked', response, request.id)
} else {
this.emitter.emit('response:bypass', response, request.id)
}
})
}
public listen(options: Partial<SharedOptions> = {}): void {
this.resolvedOptions = mergeRight(
DEFAULT_LISTEN_OPTIONS,
options,
) as RequiredDeep<SharedOptions>
// Apply the interceptor when starting the server.
this.interceptor.apply()
// Assert that the interceptor has been applied successfully.
// Also guards us from forgetting to call "interceptor.apply()"
// as a part of the "listen" method.
invariant(
[InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(
this.interceptor.readyState,
),
devUtils.formatMessage(
'Failed to start "setupServer": the interceptor failed to apply. This is likely an issue with the library and you should report it at "%s".',
),
'https://github.com/mswjs/msw/issues/new/choose',
)
}
public printHandlers(): void {
const handlers = this.listHandlers()
handlers.forEach((handler) => {
const { header, callFrame } = handler.info
const pragma = handler.info.hasOwnProperty('operationType')
? '[graphql]'
: '[rest]'
console.log(`\
${bold(`${pragma} ${header}`)}
Declaration: ${callFrame}
`)
})
}
public close(): void {
super.dispose()
this.interceptor.dispose()
}
}