/
MockedRequest.ts
180 lines (159 loc) · 5.09 KB
/
MockedRequest.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
import * as cookieUtils from 'cookie'
import { store } from '@mswjs/cookies'
import { IsomorphicRequest, RequestInit } from '@mswjs/interceptors'
import { decodeBuffer } from '@mswjs/interceptors/lib/utils/bufferUtils'
import { Headers } from 'headers-polyfill/lib'
import { DefaultBodyType } from '../../handlers/RequestHandler'
import { MockedResponse } from '../../response'
import { getRequestCookies } from './getRequestCookies'
import { parseBody } from './parseBody'
import { isStringEqual } from '../internal/isStringEqual'
export type RequestCache =
| 'default'
| 'no-store'
| 'reload'
| 'no-cache'
| 'force-cache'
| 'only-if-cached'
export type RequestMode = 'navigate' | 'same-origin' | 'no-cors' | 'cors'
export type RequestRedirect = 'follow' | 'error' | 'manual'
export type RequestDestination =
| ''
| 'audio'
| 'audioworklet'
| 'document'
| 'embed'
| 'font'
| 'frame'
| 'iframe'
| 'image'
| 'manifest'
| 'object'
| 'paintworklet'
| 'report'
| 'script'
| 'sharedworker'
| 'style'
| 'track'
| 'video'
| 'xslt'
| 'worker'
export type RequestPriority = 'high' | 'low' | 'auto'
export type RequestReferrerPolicy =
| ''
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
export interface MockedRequestInit extends RequestInit {
id?: string
cache?: RequestCache
redirect?: RequestRedirect
integrity?: string
keepalive?: boolean
mode?: RequestMode
priority?: RequestPriority
destination?: RequestDestination
referrer?: string
referrerPolicy?: RequestReferrerPolicy
cookies?: Record<string, string>
}
export class MockedRequest<
RequestBody extends DefaultBodyType = DefaultBodyType,
> extends IsomorphicRequest {
public readonly cache: RequestCache
public readonly cookies: Record<string, string>
public readonly destination: RequestDestination
public readonly integrity: string
public readonly keepalive: boolean
public readonly mode: RequestMode
public readonly priority: RequestPriority
public readonly redirect: RequestRedirect
public readonly referrer: string
public readonly referrerPolicy: RequestReferrerPolicy
constructor(url: URL, init: MockedRequestInit = {}) {
super(url, init)
if (init.id) {
this.id = init.id
}
this.cache = init.cache || 'default'
this.destination = init.destination || ''
this.integrity = init.integrity || ''
this.keepalive = init.keepalive || false
this.mode = init.mode || 'cors'
this.priority = init.priority || 'auto'
this.redirect = init.redirect || 'follow'
this.referrer = init.referrer || ''
this.referrerPolicy = init.referrerPolicy || 'no-referrer'
this.cookies = init.cookies || this.getCookies()
}
/**
* Get parsed request body. The type is inferred from the content type.
*
* @deprecated - Use `req.text()`, `req.json()` or `req.arrayBuffer()`
* to read the request body as a plain text, JSON, or ArrayBuffer.
*/
public get body(): RequestBody {
const text = decodeBuffer(this['_body'])
/**
* @deprecated https://github.com/mswjs/msw/issues/1318
* @fixme Remove this assumption and let the users read
* request body explicitly using ".json()"/".text()"/".arrayBuffer()".
*/
// Parse the request's body based on the "Content-Type" header.
const body = parseBody(text, this.headers)
if (isStringEqual(this.method, 'GET') && body === '') {
return undefined as RequestBody
}
return body as RequestBody
}
/**
* Bypass the intercepted request.
* This will make a call to the actual endpoint requested.
*/
public passthrough(): MockedResponse<null> {
return {
// Constructing a dummy "101 Continue" mocked response
// to keep the return type of the resolver consistent.
status: 101,
statusText: 'Continue',
headers: new Headers(),
body: null,
// Setting "passthrough" to true will signal the response pipeline
// to perform this intercepted request as-is.
passthrough: true,
once: false,
}
}
private getCookies(): Record<string, string> {
// Parse the cookies passed in the original request "cookie" header.
const requestCookiesString = this.headers.get('cookie')
const ownCookies = requestCookiesString
? cookieUtils.parse(requestCookiesString)
: {}
store.hydrate()
const cookiesFromStore = Array.from(
store.get({ ...this, url: this.url.href })?.entries(),
).reduce((cookies, [name, { value }]) => {
return Object.assign(cookies, { [name.trim()]: value })
}, {})
// Get existing document cookies that are applicable
// to this request based on its "credentials" policy.
const cookiesFromDocument = getRequestCookies(this)
const forwardedCookies = {
...cookiesFromDocument,
...cookiesFromStore,
}
for (const [name, value] of Object.entries(forwardedCookies)) {
this.headers.append('cookie', `${name}=${value}`)
}
return {
...forwardedCookies,
...ownCookies,
}
}
}