2022-08-05 14:26:29 +00:00
|
|
|
const Authentication = require('./authentication')
|
2019-02-22 14:53:43 +00:00
|
|
|
|
2019-09-14 19:03:38 +00:00
|
|
|
exports.sendRequest = function(options, isPagination) {
|
2019-02-22 14:53:43 +00:00
|
|
|
let token = Authentication.getToken()
|
2019-09-14 19:03:38 +00:00
|
|
|
let pagination = isPagination
|
2019-02-22 14:53:43 +00:00
|
|
|
|
|
|
|
if (token) {
|
|
|
|
options.headers = options.headers || {}
|
|
|
|
options.headers['Authorization'] = 'Bearer ' + token
|
|
|
|
}
|
|
|
|
|
2019-09-14 19:03:38 +00:00
|
|
|
options.extract = function(xhr) {
|
2021-02-05 11:50:01 +00:00
|
|
|
if (xhr.responseText && xhr.responseText.slice(0, 9) === '<!doctype') {
|
|
|
|
throw new Error('Expected JSON but got HTML (' + xhr.status + ': ' + this.url.split('?')[0] + ')')
|
|
|
|
}
|
2019-09-14 19:03:38 +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),
|
|
|
|
}
|
|
|
|
} else {
|
2019-09-15 01:53:38 +00:00
|
|
|
if (xhr.responseText) {
|
|
|
|
out = JSON.parse(xhr.responseText)
|
|
|
|
} else {
|
|
|
|
out = {}
|
|
|
|
}
|
2019-09-14 19:03:38 +00:00
|
|
|
}
|
|
|
|
if (xhr.status >= 300) {
|
|
|
|
throw out
|
|
|
|
}
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2019-02-22 14:53:43 +00:00
|
|
|
return m.request(options)
|
|
|
|
.catch(function (error) {
|
2022-07-20 00:33:06 +00:00
|
|
|
if (error.status === 403) {
|
2019-02-22 14:53:43 +00:00
|
|
|
Authentication.clearToken()
|
|
|
|
m.route.set('/login', { redirect: m.route.get() })
|
|
|
|
}
|
2019-09-13 13:33:10 +00:00
|
|
|
if (error.response && error.response.status) {
|
|
|
|
return Promise.reject(error.response)
|
|
|
|
}
|
2019-02-22 14:53:43 +00:00
|
|
|
return Promise.reject(error)
|
|
|
|
})
|
|
|
|
}
|