73 lines
2.1 KiB
JavaScript
73 lines
2.1 KiB
JavaScript
const Authentication = require('./authentication')
|
|
|
|
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
|
|
}
|
|
|
|
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] + ')')
|
|
}
|
|
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),
|
|
}
|
|
} else {
|
|
if (xhr.responseText) {
|
|
out = JSON.parse(xhr.responseText)
|
|
} else {
|
|
out = {}
|
|
}
|
|
}
|
|
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
|
|
}
|
|
|
|
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)
|
|
})
|
|
}
|
|
}
|
|
|
|
module.exports = api
|