-
-
Notifications
You must be signed in to change notification settings - Fork 533
/
Copy pathcreateSetupServer.ts
153 lines (135 loc) · 4.59 KB
/
createSetupServer.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
import { bold } from 'chalk'
import { isNodeProcess } from 'is-node-process'
import { StrictEventEmitter } from 'strict-event-emitter'
import {
createInterceptor,
MockedResponse as MockedInterceptedResponse,
Interceptor,
} from '@mswjs/interceptors'
import * as requestHandlerUtils from '../utils/internal/requestHandlerUtils'
import { ServerLifecycleEventsMap, SetupServerApi } from './glossary'
import { SharedOptions } from '../sharedOptions'
import { RequestHandler } from '../handlers/RequestHandler'
import { parseIsomorphicRequest } from '../utils/request/parseIsomorphicRequest'
import { handleRequest } from '../utils/handleRequest'
import { mergeRight } from '../utils/internal/mergeRight'
import { devUtils } from '../utils/internal/devUtils'
import { pipeEvents } from '../utils/internal/pipeEvents'
const DEFAULT_LISTEN_OPTIONS: SharedOptions = {
onUnhandledRequest: 'warn',
}
/**
* Creates a `setupServer` API using given request interceptors.
* Useful to generate identical API using different patches to request issuing modules.
*/
export function createSetupServer(...interceptors: Interceptor[]) {
const emitter = new StrictEventEmitter<ServerLifecycleEventsMap>()
const publicEmitter = new StrictEventEmitter<ServerLifecycleEventsMap>()
pipeEvents(emitter, publicEmitter)
return function setupServer(
...requestHandlers: RequestHandler[]
): SetupServerApi {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
throw new Error(
devUtils.formatMessage(
'Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).',
),
)
})
// Store the list of request handlers for the current server instance,
// so it could be modified at a runtime.
let currentHandlers: RequestHandler[] = [...requestHandlers]
// Error when attempting to run this function in a browser environment.
if (!isNodeProcess()) {
throw new Error(
devUtils.formatMessage(
'Failed to execute `setupServer` in the environment that is not Node.js (i.e. a browser). Consider using `setupWorker` instead.',
),
)
}
let resolvedOptions = {} as SharedOptions
const interceptor = createInterceptor({
modules: interceptors,
async resolver(request) {
const mockedRequest = parseIsomorphicRequest(request)
return handleRequest<MockedInterceptedResponse>(
mockedRequest,
currentHandlers,
resolvedOptions,
emitter,
{
transformResponse(response) {
return {
status: response.status,
statusText: response.statusText,
headers: response.headers.all(),
body: response.body,
}
},
},
)
},
})
interceptor.on('response', (request, response) => {
const requestId = request.headers.get('x-msw-request-id')
if (!requestId) {
return
}
if (response.headers.get('x-powered-by') === 'msw') {
emitter.emit('response:mocked', response, requestId)
} else {
emitter.emit('response:bypass', response, requestId)
}
})
return {
listen(options) {
resolvedOptions = mergeRight(
DEFAULT_LISTEN_OPTIONS,
options || {},
) as SharedOptions
interceptor.apply()
},
use(...handlers) {
requestHandlerUtils.use(currentHandlers, ...handlers)
},
restoreHandlers() {
requestHandlerUtils.restoreHandlers(currentHandlers)
},
resetHandlers(...nextHandlers) {
currentHandlers = requestHandlerUtils.resetHandlers(
requestHandlers,
...nextHandlers,
)
},
printHandlers() {
currentHandlers.forEach((handler) => {
const { header, callFrame } = handler.info
const pragma = handler.info.hasOwnProperty('operationType')
? '[graphql]'
: '[rest]'
console.log(`\
${bold(`${pragma} ${header}`)}
Declaration: ${callFrame}
`)
})
},
events: {
on(...args) {
return publicEmitter.on(...args)
},
removeListener(...args) {
return publicEmitter.removeListener(...args)
},
removeAllListeners(...args) {
return publicEmitter.removeAllListeners(...args)
},
},
close() {
emitter.removeAllListeners()
publicEmitter.removeAllListeners()
interceptor.restore()
},
}
}
}