onedrive/utils/tools.ts

64 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-08-29 14:50:38 +00:00
import axios from 'axios'
2021-08-30 00:35:52 +00:00
import useSWR, { cache, Key } from 'swr'
import siteConfig from '../config/site.json'
2021-08-29 14:50:38 +00:00
/**
* Extract the current web page's base url
* @returns base url of the page
*/
export const getBaseUrl = () => {
if (typeof window !== 'undefined') {
return window.location.origin
}
return ''
}
2021-08-29 14:50:38 +00:00
// Common axios fetch function
2021-08-30 11:45:01 +00:00
const fetcher = (url: string, token?: string) => {
return token
? axios
.get(url, {
headers: { 'od-protected-token': token },
})
.then(res => res.data)
: axios.get(url).then(res => res.data)
}
2021-08-29 14:50:38 +00:00
/**
* Use stale SWR instead of revalidating on each request. Not ideal for this scenario but have to do
* if fetching serverside props from component instead of pages.
2021-08-30 00:35:52 +00:00
* @param url request url
2021-08-29 14:50:38 +00:00
* @returns useSWR instance
*/
2021-08-30 00:43:42 +00:00
export const useStaleSWR = (url: Key, path: string = '') => {
2021-08-29 14:50:38 +00:00
const revalidationOptions = {
2021-08-30 13:34:37 +00:00
revalidateOnMount: !(cache.has(`arg@"${url}"@null`) || cache.has(url)),
2021-08-29 14:50:38 +00:00
revalidateOnFocus: false,
2021-08-30 13:34:37 +00:00
revalidateOnReconnect: true,
2021-08-29 14:50:38 +00:00
}
2021-08-30 00:35:52 +00:00
const token =
typeof window !== 'undefined' ? JSON.parse(localStorage.getItem(matchProtectedRoute(path)) as string) : ''
return useSWR([url, token], fetcher, revalidationOptions)
}
export const matchProtectedRoute = (route: string) => {
const protectedRoutes = siteConfig.protectedRoutes
let authTokenPath = ''
for (const r of protectedRoutes) {
if (
route.startsWith(
r
.split('/')
.map(p => encodeURIComponent(p))
.join('/')
)
) {
authTokenPath = r
break
}
}
return authTokenPath
2021-08-29 14:50:38 +00:00
}