2023-11-09 09:44:04 +00:00
|
|
|
const Authentication = require('./authentication')
|
|
|
|
|
2023-11-14 07:27:04 +00:00
|
|
|
const api = {
|
|
|
|
loading: false,
|
|
|
|
sendRequest: function(options, isPagination) {
|
|
|
|
api.loading = true
|
|
|
|
let token = Authentication.getToken()
|
|
|
|
let pagination = isPagination
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
options.headers = options.headers || {}
|
|
|
|
options.headers['Authorization'] = 'Bearer ' + token
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
2023-11-14 07:27:04 +00:00
|
|
|
|
|
|
|
options.extract = function(xhr) {
|
|
|
|
if (xhr.responseText && xhr.responseText.slice(0, 9) === '<!doctype') {
|
|
|
|
if (xhr.status === 500) {
|
|
|
|
throw new Error('Server is temporarily down, try again later.')
|
|
|
|
}
|
|
|
|
throw new Error('Expected JSON but got HTML (' + xhr.status + ': ' + this.url.split('?')[0] + ')')
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
2023-11-14 07:27:04 +00:00
|
|
|
let out = null
|
|
|
|
if (pagination && xhr.status < 300) {
|
|
|
|
let headers = {}
|
|
|
|
|
|
|
|
xhr.getAllResponseHeaders().split('\r\n').forEach(function(item) {
|
|
|
|
var splitted = item.split(': ')
|
|
|
|
headers[splitted[0]] = splitted[1]
|
|
|
|
})
|
|
|
|
|
|
|
|
out = {
|
|
|
|
headers: headers || {},
|
|
|
|
data: JSON.parse(xhr.responseText),
|
|
|
|
}
|
2023-11-09 09:44:04 +00:00
|
|
|
} else {
|
2023-11-14 07:27:04 +00:00
|
|
|
if (xhr.responseText) {
|
|
|
|
out = JSON.parse(xhr.responseText)
|
|
|
|
} else {
|
|
|
|
out = {}
|
|
|
|
}
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
2023-11-14 07:27:04 +00:00
|
|
|
if (xhr.status >= 300) {
|
|
|
|
if (out.message) {
|
|
|
|
throw out
|
|
|
|
}
|
|
|
|
console.error('Got error ' + xhr.status + ' but no error message:', out)
|
|
|
|
throw new Error('Unknown or empty response from server.')
|
|
|
|
}
|
|
|
|
return out
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
2023-11-14 07:27:04 +00:00
|
|
|
|
|
|
|
return m.request(options)
|
|
|
|
.then(function(res) {
|
|
|
|
api.loading = false
|
|
|
|
window.requestAnimationFrame(m.redraw.bind(m))
|
|
|
|
return res
|
|
|
|
})
|
|
|
|
.catch(function (error) {
|
|
|
|
api.loading = false
|
|
|
|
window.requestAnimationFrame(m.redraw.bind(m))
|
|
|
|
if (error.status === 403) {
|
|
|
|
Authentication.clearToken()
|
|
|
|
m.route.set('/', { redirect: m.route.get() })
|
|
|
|
}
|
|
|
|
if (error.response && error.response.status) {
|
|
|
|
return Promise.reject(error.response)
|
|
|
|
}
|
|
|
|
return Promise.reject(error)
|
|
|
|
})
|
2023-11-09 09:44:04 +00:00
|
|
|
}
|
|
|
|
}
|
2023-11-14 07:27:04 +00:00
|
|
|
|
|
|
|
module.exports = api
|