yunohost-admin/app/src/helpers/api.js

78 lines
1.8 KiB
JavaScript
Raw Normal View History

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
}
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
}
}
async function handleErrors (response) {
2020-07-15 16:39:24 +02:00
if (response.status === 401) {
throw new Error('Unauthorized')
} else if (response.status === 400) {
const message = await response.text()
throw new Error(message)
2020-07-15 16:39:24 +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-15 16:39:24 +02:00
},
get (uri) {
return fetch(
'/api/' + uri, this.options
).then(handleResponse)
2020-07-15 16:39:24 +02:00
},
getAll (uris) {
return Promise.all(uris.map((uri) => this.get(uri)))
},
post (uri, data = {}) {
return fetch('/api/' + uri, {
...this.options,
method: 'POST',
body: objectToParams(data)
}).then(handleResponse)
},
put (uri, data = {}) {
2020-07-27 20:46:27 +02:00
return fetch('/api/' + uri, {
...this.options,
method: 'PUT',
body: objectToParams(data)
}).then(handleResponse)
2020-07-27 20:46:27 +02:00
},
delete (uri, data = {}) {
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
}
}