@rails/request.js
Version:
A tiny Fetch API wrapper that allows you to make http requests without need to handle to send the CSRF Token on every request
95 lines (76 loc) • 2.45 kB
JavaScript
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`))
}
}
}