forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestRedirect.tsx
41 lines (36 loc) · 1.58 KB
/
RestRedirect.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Cookies from 'js-cookie'
import { useVersion } from './hooks/useVersion'
import { useMainContext } from './context/MainContext'
export const API_VERSION_COOKIE_NAME = 'apiVersionPreferred'
// This component allows us to set the URL Param for the REST API Calendar Date version
// We set a cookie as well to remember what calendar date version the user is on
export function RestRedirect() {
const router = useRouter()
const { currentVersion } = useVersion()
const { allVersions } = useMainContext()
const validApiVersions = allVersions[currentVersion].apiVersions
const isReleaseVersioned = allVersions[currentVersion].apiVersions.length > 0
const latestValidApiVersion = allVersions[currentVersion].latestApiVersion
const queryApiVersion = router.query.apiVersion
useEffect(() => {
if (
isReleaseVersioned &&
(!queryApiVersion || !validApiVersions.includes(queryApiVersion as string))
) {
const versionCookie = Cookies.get(API_VERSION_COOKIE_NAME)
const date =
versionCookie && validApiVersions.includes(versionCookie)
? versionCookie
: latestValidApiVersion
const hash = router.asPath.split('#')[1]
const [asPathRoot, asPathQuery = ''] = router.asPath.split('#')[0].split('?')
const params = new URLSearchParams(asPathQuery)
params.set('apiVersion', date)
const url = `/${router.locale}${asPathRoot}?${params}${hash ? '#' + hash : ''}`
router.replace(url)
}
}, [router.asPath, currentVersion])
return null
}