-
Notifications
You must be signed in to change notification settings - Fork 435
/
fetch_request.ts
174 lines (153 loc) · 4.77 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
import { FetchResponse } from "./fetch_response"
import { FrameElement } from "../elements/frame_element"
import { dispatch } from "../util"
export type TurboBeforeFetchRequestEvent = CustomEvent<{
fetchOptions: RequestInit
url: URL
resume: (value: any) => void
}>
export type TurboBeforeFetchResponseEvent = CustomEvent<{
fetchResponse: FetchResponse
}>
export interface FetchRequestDelegate {
referrer?: URL
prepareHeadersForRequest?(headers: FetchRequestHeaders, 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,
post,
put,
patch,
delete,
}
export function fetchMethodFromString(method: string) {
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 type FetchRequestBody = FormData | URLSearchParams
export type FetchRequestHeaders = { [header: string]: string }
export interface FetchRequestOptions {
headers: FetchRequestHeaders
body: FetchRequestBody
followRedirects: boolean
}
export class FetchRequest {
readonly delegate: FetchRequestDelegate
readonly method: FetchMethod
readonly headers: FetchRequestHeaders
readonly url: URL
readonly body?: FetchRequestBody
readonly target?: FrameElement | HTMLFormElement | null
readonly abortController = new AbortController()
private resolveRequestPromise = (_value: any) => {}
constructor(
delegate: FetchRequestDelegate,
method: FetchMethod,
location: URL,
body: FetchRequestBody = new URLSearchParams(),
target: FrameElement | HTMLFormElement | null = null
) {
this.delegate = delegate
this.method = method
this.headers = this.defaultHeaders
this.body = body
this.url = location
this.target = target
}
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.prepareHeadersForRequest?.(this.headers, 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") {
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 as EventTarget,
})
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 fetchOptions(): RequestInit {
return {
method: FetchMethod[this.method].toUpperCase(),
credentials: "same-origin",
headers: this.headers,
redirect: "follow",
body: this.isIdempotent ? null : this.body,
signal: this.abortSignal,
referrer: this.delegate.referrer?.href,
}
}
get defaultHeaders() {
return {
Accept: "text/html, application/xhtml+xml",
}
}
get isIdempotent() {
return this.method == FetchMethod.get
}
get abortSignal() {
return this.abortController.signal
}
private 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 as EventTarget,
})
if (event.defaultPrevented) await requestInterception
}
}