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) === '= 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