forked from rails/request.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_response.js
94 lines (76 loc) · 2.39 KB
/
fetch_response.js
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
export class FetchResponse {
constructor (response) {
this.response = response
}
get statusCode () {
return this.response.status
}
get redirected () {
return this.response.redirected
}
get ok () {
return this.response.ok
}
get unauthenticated () {
return this.statusCode === 401
}
get unprocessableEntity () {
return this.statusCode === 422
}
get authenticationURL () {
return this.response.headers.get('WWW-Authenticate')
}
get contentType () {
const contentType = this.response.headers.get('Content-Type') || ''
return contentType.replace(/;.*$/, '')
}
get headers () {
return this.response.headers
}
get html () {
if (this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)) {
return this.text
}
return Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`))
}
get json () {
if (this.contentType.match(/^application\/.*json$/)) {
return this.responseJson || (this.responseJson = this.response.json())
}
return Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`))
}
get text () {
return this.responseText || (this.responseText = this.response.text())
}
get isTurboStream () {
return this.contentType.match(/^text\/vnd\.turbo-stream\.html/)
}
get isScript () {
return this.contentType.match(/\b(?:java|ecma)script\b/)
}
async renderTurboStream () {
if (this.isTurboStream) {
if (window.Turbo) {
await window.Turbo.renderStreamMessage(await this.text)
} else {
console.warn('You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js')
}
} else {
return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`))
}
}
async activeScript () {
if (this.isScript) {
const script = document.createElement('script')
const metaTag = document.querySelector('meta[name=csp-nonce]')
if (metaTag) {
const nonce = metaTag.nonce === '' ? metaTag.content : metaTag.nonce
if (nonce) { script.setAttribute('nonce', nonce) }
}
script.innerHTML = await this.text
document.body.appendChild(script)
} else {
return Promise.reject(new Error(`Expected a Script response but got "${this.contentType}" instead`))
}
}
}