-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrailsHttpClient.js
More file actions
36 lines (36 loc) · 1.35 KB
/
railsHttpClient.js
File metadata and controls
36 lines (36 loc) · 1.35 KB
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
module.exports = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
options.headers.append('X-CSRF-Token', document.head.querySelector('meta[name="csrf-token"]').content)
return fetch(url, options).then(response => {
const contentType = response.headers.get('content-type')
// 204 No Content response will not have content-type
const isJson = contentType ? contentType.indexOf('application/json') !== -1 : null
if (response.ok) {
if (response.status === 201 || response.status === 204) {
return { headers: response.headers, json: {} }
} else if (isJson) {
return response.json().then(json => { return { headers: response.headers, json: json } })
} else {
console.log('Unexpected response status and content-type combination: ' + response.status + ' / ' + contentType)
}
} else {
if (isJson) {
return response.json().then(json => {
const err = new Error(json.title)
err.messages = json.messages
err.full_messages = json.full_messages
err.status = response.status
throw err
})
} else {
return response.text().then(text => {
const err = new Error(text)
err.status = response.status
throw err
})
}
}
})
}