mirror of
https://github.com/cupcakearmy/obolus.git
synced 2024-12-23 08:36:26 +00:00
29 lines
745 B
JavaScript
29 lines
745 B
JavaScript
|
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
|
||
|
}
|