2019-05-24 13:26:06 +00:00
|
|
|
import { useEffect, useState } from 'react'
|
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
|
2019-05-24 13:26:06 +00:00
|
|
|
}
|
|
|
|
|
2019-05-24 13:50:43 +00:00
|
|
|
export const useCallAPI = (call, automatic = false) => {
|
2019-05-24 13:26:06 +00:00
|
|
|
const [data, setData] = useState(undefined)
|
|
|
|
|
|
|
|
const refresh = () => {
|
|
|
|
callAPI(null, call).then(setData)
|
|
|
|
}
|
|
|
|
|
2019-05-24 13:50:43 +00:00
|
|
|
if (automatic)
|
|
|
|
useEffect(() => {
|
|
|
|
refresh()
|
|
|
|
}, [0])
|
2019-05-24 13:26:06 +00:00
|
|
|
|
|
|
|
return [data, refresh]
|
2019-05-22 18:34:58 +00:00
|
|
|
}
|