|
| 1 | +import { Response } from './response' |
| 2 | +import { getCookie } from './lib/cookie' |
| 3 | + |
| 4 | +export class Request { |
| 5 | + constructor (method, url, options = {}) { |
| 6 | + this.method = method |
| 7 | + this.url = url |
| 8 | + this.options = options |
| 9 | + } |
| 10 | + |
| 11 | + async perform () { |
| 12 | + const response = new Response(await window.fetch(this.url, this.fetchOptions)) |
| 13 | + if (response.unauthenticated && response.authenticationURL) { |
| 14 | + return Promise.reject(window.location.href = response.authenticationURL) |
| 15 | + } else { |
| 16 | + return response |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + get fetchOptions () { |
| 21 | + return { |
| 22 | + method: this.method, |
| 23 | + headers: this.headers, |
| 24 | + body: this.body, |
| 25 | + signal: this.signal, |
| 26 | + credentials: 'same-origin', |
| 27 | + redirect: 'follow' |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + get headers () { |
| 32 | + return compact({ |
| 33 | + 'X-Requested-With': 'XMLHttpRequest', |
| 34 | + 'X-CSRF-Token': this.csrfToken, |
| 35 | + 'Content-Type': this.contentType, |
| 36 | + Accept: this.accept |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + get csrfToken () { |
| 41 | + return getCookie(metaContent('csrf-param')) || metaContent('csrf-token') |
| 42 | + } |
| 43 | + |
| 44 | + get contentType () { |
| 45 | + if (this.options.contentType) { |
| 46 | + return this.options.contentType |
| 47 | + } else if (this.body == null || this.body instanceof window.FormData) { |
| 48 | + return undefined |
| 49 | + } else if (this.body instanceof window.File) { |
| 50 | + return this.body.type |
| 51 | + } else { |
| 52 | + return 'application/octet-stream' |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + get accept () { |
| 57 | + switch (this.responseKind) { |
| 58 | + case 'html': |
| 59 | + return 'text/html, application/xhtml+xml' |
| 60 | + case 'json': |
| 61 | + return 'application/json' |
| 62 | + default: |
| 63 | + return '*/*' |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + get body () { |
| 68 | + return this.options.body |
| 69 | + } |
| 70 | + |
| 71 | + get responseKind () { |
| 72 | + return this.options.responseKind || 'html' |
| 73 | + } |
| 74 | + |
| 75 | + get signal () { |
| 76 | + return this.options.signal |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +function compact (object) { |
| 81 | + const result = {} |
| 82 | + for (const key in object) { |
| 83 | + const value = object[key] |
| 84 | + if (value !== undefined) { |
| 85 | + result[key] = value |
| 86 | + } |
| 87 | + } |
| 88 | + return result |
| 89 | +} |
| 90 | + |
| 91 | +function metaContent (name) { |
| 92 | + const element = document.head.querySelector(`meta[name="${name}"]`) |
| 93 | + return element && element.content |
| 94 | +} |
0 commit comments