-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.ts
59 lines (52 loc) · 1.46 KB
/
middleware.ts
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { SidebarFragment } from '@/basehub-helpers/fragments'
import { getActiveSidebarItem } from '@/basehub-helpers/sidebar'
import { basehub } from 'basehub'
import { draftMode } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'
import nextConfig from './next.config'
export async function middleware(request: NextRequest) {
/**
* Redirect to first category page.
*/
const { pages } = await basehub({
draft: (await draftMode()).isEnabled,
}).query({ pages: { __args: { first: 1 }, items: SidebarFragment.items } })
const firstCategory = pages.items?.[0]
if (!firstCategory) return NextResponse.next()
const url = new URL(request.url)
if (firstCategory) {
const {
current: { article, path: firstArticlePath },
} = getActiveSidebarItem({
activeSlugs: [],
sidebar: firstCategory.articles,
})
if (firstArticlePath) {
return NextResponse.redirect(
new URL(
`${nextConfig.basePath ?? '/'}${firstArticlePath.join('/')}/${article?._slug}`.replace(
/\/\//g,
'/'
) +
url.search +
url.hash,
url
)
)
} else {
return NextResponse.redirect(
new URL(
(nextConfig.basePath ?? '/') +
firstCategory._slug +
url.search +
url.hash,
url
)
)
}
}
return NextResponse.next()
}
export const config = {
matcher: '/',
}