forked from hotwired/turbo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_request.ts
286 lines (242 loc) · 7.6 KB
/
fetch_request.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
import { FetchResponse } from "./fetch_response"
import { FrameElement } from "../elements/frame_element"
import { dispatch } from "../util"
import { expandURL } from "../core/url"
export type TurboBeforeFetchRequestEvent = CustomEvent<{
fetchOptions: RequestInit
url: URL
resume: (value?: any) => void
}>
export type TurboBeforeFetchResponseEvent = CustomEvent<{
fetchResponse: FetchResponse
}>
export type TurboFetchRequestErrorEvent = CustomEvent<{
request: FetchRequest
error: Error
}>
export interface FetchRequestDelegate {
referrer?: URL
prepareRequest(request: FetchRequest): void
requestStarted(request: FetchRequest): void
requestPreventedHandlingResponse(request: FetchRequest, response: FetchResponse): void
requestSucceededWithResponse(request: FetchRequest, response: FetchResponse): void
requestFailedWithResponse(request: FetchRequest, response: FetchResponse): void
requestErrored(request: FetchRequest, error: Error): void
requestFinished(request: FetchRequest): void
}
export enum FetchMethod {
get = "get",
post = "post",
put = "put",
patch = "patch",
delete = "delete",
}
export function fetchMethodFromString(method: FetchMethod) {
switch (method.toLowerCase()) {
case "get":
return FetchMethod.get
case "post":
return FetchMethod.post
case "put":
return FetchMethod.put
case "patch":
return FetchMethod.patch
case "delete":
return FetchMethod.delete
}
}
export function fetchEnctypeFromString(encoding: string) {
switch (encoding.toLowerCase()) {
case FetchEnctype.multipart:
return FetchEnctype.multipart
case FetchEnctype.plain:
return FetchEnctype.plain
default:
return FetchEnctype.urlEncoded
}
}
export const FetchEnctype = {
urlEncoded: "application/x-www-form-urlencoded",
multipart: "multipart/form-data",
plain: "text/plain",
}
export type FetchRequestBody = FormData | URLSearchParams
export type FetchRequestHeaders = { [header: string]: string }
export interface FetchRequestOptions {
headers: FetchRequestHeaders
body: FetchRequestBody | null
credentials: "same-origin"
redirect: "follow"
method: FetchMethod
signal: AbortSignal
referrer?: string
}
export class FetchRequest {
delegate: FetchRequestDelegate
url: URL
target: FrameElement | HTMLFormElement | null
abortController = new AbortController()
fetchOptions: FetchRequestOptions
enctype: string
#resolveRequestPromise = (_value: unknown) => {}
constructor(
delegate: FetchRequestDelegate,
method: FetchMethod,
location: URL,
requestBody: FetchRequestBody = new URLSearchParams(),
target: FrameElement | HTMLFormElement | null = null,
enctype = FetchEnctype.urlEncoded,
) {
const [url, body] = buildResourceAndBody(expandURL(location), method, requestBody, enctype)
this.delegate = delegate
this.url = url
this.target = target
this.fetchOptions = {
credentials: "same-origin",
redirect: "follow",
method: method,
headers: { ...this.defaultHeaders },
body: body,
signal: this.abortSignal,
referrer: this.delegate.referrer?.href,
}
this.enctype = enctype
}
get method() {
return this.fetchOptions.method
}
set method(value: FetchMethod) {
const fetchBody = this.isSafe ? this.url.searchParams : this.fetchOptions.body || new FormData()
const fetchMethod = fetchMethodFromString(value) || FetchMethod.get
this.url.search = ""
const [url, body] = buildResourceAndBody(this.url, fetchMethod, fetchBody, this.enctype)
this.url = url
this.fetchOptions.body = body
this.fetchOptions.method = fetchMethod
}
get headers() {
return this.fetchOptions.headers
}
set headers(value) {
this.fetchOptions.headers = value
}
get body() {
if (this.isSafe) {
return this.url.searchParams
} else {
return this.fetchOptions.body
}
}
set body(value) {
this.fetchOptions.body = value
}
get location(): URL {
return this.url
}
get params(): URLSearchParams {
return this.url.searchParams
}
get entries() {
return this.body ? Array.from(this.body.entries()) : []
}
cancel() {
this.abortController.abort()
}
async perform(): Promise<FetchResponse | void> {
const { fetchOptions } = this
this.delegate.prepareRequest(this)
await this.#allowRequestToBeIntercepted(fetchOptions)
try {
this.delegate.requestStarted(this)
const response = await fetch(this.url.href, fetchOptions)
return await this.receive(response)
} catch (error) {
if ((error as Error).name !== "AbortError") {
if (this.willDelegateErrorHandling(error as Error)) {
this.delegate.requestErrored(this, error as Error)
}
throw error
}
} finally {
this.delegate.requestFinished(this)
}
}
async receive(response: Response): Promise<FetchResponse> {
const fetchResponse = new FetchResponse(response)
const event = dispatch<TurboBeforeFetchResponseEvent>("turbo:before-fetch-response", {
cancelable: true,
detail: { fetchResponse },
target: this.target,
})
if (event.defaultPrevented) {
this.delegate.requestPreventedHandlingResponse(this, fetchResponse)
} else if (fetchResponse.succeeded) {
this.delegate.requestSucceededWithResponse(this, fetchResponse)
} else {
this.delegate.requestFailedWithResponse(this, fetchResponse)
}
return fetchResponse
}
get defaultHeaders() {
return {
Accept: "text/html, application/xhtml+xml",
}
}
get isSafe() {
return isSafe(this.method)
}
get abortSignal() {
return this.abortController.signal
}
acceptResponseType(mimeType: string) {
this.headers["Accept"] = [mimeType, this.headers["Accept"]].join(", ")
}
async #allowRequestToBeIntercepted(fetchOptions: RequestInit) {
const requestInterception = new Promise((resolve) => (this.#resolveRequestPromise = resolve))
const event = dispatch<TurboBeforeFetchRequestEvent>("turbo:before-fetch-request", {
cancelable: true,
detail: {
fetchOptions,
url: this.url,
resume: this.#resolveRequestPromise,
},
target: this.target,
})
if (event.defaultPrevented) await requestInterception
}
private willDelegateErrorHandling(error: Error) {
const event = dispatch<TurboFetchRequestErrorEvent>("turbo:fetch-request-error", {
target: this.target,
cancelable: true,
detail: { request: this, error: error },
})
return !event.defaultPrevented
}
}
export function isSafe(fetchMethod: FetchMethod) {
return fetchMethodFromString(fetchMethod) == FetchMethod.get
}
function buildResourceAndBody(resource: URL, method: FetchMethod, requestBody: FetchRequestBody, enctype: string) {
const searchParams =
Array.from(requestBody).length > 0 ? new URLSearchParams(entriesExcludingFiles(requestBody)) : resource.searchParams
if (isSafe(method)) {
return [mergeIntoURLSearchParams(resource, searchParams), null] as const
} else if (enctype == FetchEnctype.urlEncoded) {
return [resource, searchParams] as const
} else {
return [resource, requestBody] as const
}
}
function entriesExcludingFiles(requestBody: FetchRequestBody) {
const entries = [] as [string, string][]
for (const [name, value] of requestBody) {
if (value instanceof File) continue
else entries.push([name, value])
}
return entries
}
function mergeIntoURLSearchParams(url: URL, requestBody: FetchRequestBody) {
const searchParams = new URLSearchParams(entriesExcludingFiles(requestBody))
url.search = searchParams.toString()
return url
}