2020-07-15 16:39:24 +02:00
|
|
|
function objectToParams (object) {
|
|
|
|
const urlParams = new URLSearchParams()
|
|
|
|
for (const [key, value] of Object.entries(object)) {
|
|
|
|
urlParams.append(key, value)
|
|
|
|
}
|
|
|
|
return urlParams
|
2020-07-10 18:40:28 +02:00
|
|
|
}
|
|
|
|
|
2020-08-27 18:25:40 +02:00
|
|
|
async function handleResponse (response) {
|
|
|
|
if (!response.ok) return handleErrors(response)
|
|
|
|
// FIXME the api should always return json objects
|
|
|
|
const responseText = await response.text()
|
|
|
|
try {
|
|
|
|
return JSON.parse(responseText)
|
|
|
|
} catch {
|
|
|
|
return responseText
|
|
|
|
}
|
2020-07-12 19:02:34 +02:00
|
|
|
}
|
|
|
|
|
2020-07-26 19:42:00 +02:00
|
|
|
async function handleErrors (response) {
|
2020-07-15 16:39:24 +02:00
|
|
|
if (response.status === 401) {
|
|
|
|
throw new Error('Unauthorized')
|
2020-07-26 19:42:00 +02:00
|
|
|
} else if (response.status === 400) {
|
|
|
|
const message = await response.text()
|
|
|
|
throw new Error(message)
|
2020-07-15 16:39:24 +02:00
|
|
|
}
|
2020-07-12 19:02:34 +02:00
|
|
|
}
|
|
|
|
|
2020-07-10 18:40:28 +02:00
|
|
|
export default {
|
2020-07-15 16:39:24 +02:00
|
|
|
options: {
|
|
|
|
credentials: 'include',
|
|
|
|
mode: 'cors',
|
|
|
|
headers: {
|
|
|
|
// FIXME is it important to keep this previous `Accept` header ?
|
|
|
|
// 'Accept': 'application/json, text/javascript, */*; q=0.01',
|
|
|
|
// Auto header is :
|
|
|
|
// "Accept": "*/*",
|
|
|
|
|
|
|
|
// Also is this still important ? (needed by back-end)
|
|
|
|
'X-Requested-With': 'XMLHttpRequest'
|
2020-07-10 18:40:28 +02:00
|
|
|
}
|
2020-07-15 16:39:24 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
get (uri) {
|
2020-08-27 18:25:40 +02:00
|
|
|
return fetch(
|
|
|
|
'/api/' + uri, this.options
|
|
|
|
).then(handleResponse)
|
2020-07-15 16:39:24 +02:00
|
|
|
},
|
|
|
|
|
2020-08-08 15:04:49 +02:00
|
|
|
getAll (uris) {
|
|
|
|
return Promise.all(uris.map((uri) => this.get(uri)))
|
|
|
|
},
|
|
|
|
|
|
|
|
post (uri, data = {}) {
|
2020-07-26 19:42:00 +02:00
|
|
|
return fetch('/api/' + uri, {
|
|
|
|
...this.options,
|
|
|
|
method: 'POST',
|
|
|
|
body: objectToParams(data)
|
2020-08-27 18:25:40 +02:00
|
|
|
}).then(handleResponse)
|
2020-07-26 19:42:00 +02:00
|
|
|
},
|
|
|
|
|
2020-08-08 15:04:49 +02:00
|
|
|
put (uri, data = {}) {
|
2020-07-27 20:46:27 +02:00
|
|
|
return fetch('/api/' + uri, {
|
|
|
|
...this.options,
|
|
|
|
method: 'PUT',
|
|
|
|
body: objectToParams(data)
|
2020-08-27 18:25:40 +02:00
|
|
|
}).then(handleResponse)
|
2020-07-27 20:46:27 +02:00
|
|
|
},
|
|
|
|
|
2020-08-08 15:04:49 +02:00
|
|
|
delete (uri, data = {}) {
|
2020-07-28 00:18:47 +02:00
|
|
|
return fetch('/api/' + uri, {
|
|
|
|
...this.options,
|
|
|
|
method: 'DELETE',
|
|
|
|
body: objectToParams(data)
|
|
|
|
}).then(response => response.ok ? 'ok' : handleErrors(response))
|
2020-07-15 16:39:24 +02:00
|
|
|
}
|
2020-07-10 18:40:28 +02:00
|
|
|
}
|