nfp_sites/app/api/common.js

52 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-02-22 14:53:43 +00:00
const m = require('mithril')
const Authentication = require('../authentication')
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) {
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 = {}
}
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) {
if (error.code === 403) {
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)
})
}