obolus/www/utils/api.js

29 lines
745 B
JavaScript
Raw Normal View History

2019-05-22 18:34:58 +00:00
import nextCookie from 'next-cookies'
import axios from 'axios'
import cookie from 'js-cookie'
import Router from 'next/dist/lib/router'
export const callAPI = async (ctxOrNull, { url, method, data }) => {
// Whether ctx is set or not
const token = ctxOrNull
? nextCookie(ctxOrNull).token
: cookie.get('token')
const redirect = () => process.browser
? Router.push('/login')
: ctxOrNull.res.writeHead(302, { Location: '/login' }).end()
const response = await axios({
method: method || 'get',
url,
headers: {
'Authorization': `Bearer ${token}`,
},
data,
})
if (response.status === 401) redirect()
else return response.data.body
}