-
Notifications
You must be signed in to change notification settings - Fork 367
/
middleware.ts
118 lines (93 loc) · 2.67 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { NextRequest, NextResponse } from 'next/server'
import { keyCodeEventValues } from '~/lib/keycodes'
import { slugifyForRedirects } from '~/lib/utils/slugify'
import { KeyCodeEvent } from '~/lib/types/key-code-events'
import { capitalizeFirstLetter } from '~/lib/utils/capitalize-first-letter'
export const checkRedirectForKeycode = (
keys: KeyCodeEvent[],
pathKey: string
): KeyCodeEvent | undefined => {
if (!pathKey) {
return undefined
}
const keyWithKey = keys.find(
(keyCode: KeyCodeEvent) => keyCode.key.toLowerCase() === pathKey
)
if (keyWithKey) {
return keyWithKey
}
const keyWithCode = keys.find(
(keyCode: KeyCodeEvent) => keyCode.code?.toLowerCase() === pathKey
)
if (keyWithCode) {
return keyWithCode
}
const numberCode = parseInt(pathKey)
if (numberCode) {
const keyWithNumber = keys.find(
(keyCodeEvent: KeyCodeEvent) => keyCodeEvent.keyCode === numberCode
)
if (keyWithNumber) {
return keyWithNumber
}
}
const keyWithSlug = keys
.filter((keyCodeEvent: KeyCodeEvent) => keyCodeEvent.description)
.find(
(keyCodeEvent: KeyCodeEvent) =>
keyCodeEvent.description &&
slugifyForRedirects(keyCodeEvent.description) === pathKey
)
if (keyWithSlug) {
return keyWithSlug
}
if (pathKey.includes('-')) {
const camelCaseKey = capitalizeFirstLetter(
pathKey.replace(/-./g, x => x[1].toUpperCase())
)
const keyAux = keys
.filter((keyCodeEvent: KeyCodeEvent) => keyCodeEvent.key.toLowerCase())
.find((keyCodeEvent: KeyCodeEvent) => keyCodeEvent.key === camelCaseKey)
if (keyAux) {
return keyAux
}
}
return undefined
}
const redirect = (request: NextRequest, route: string) => {
return NextResponse.redirect(
new URL(
`${request.nextUrl.basePath}/${route.replace('/', '')}`,
request.url
)
)
}
export default async function middleware(
request: NextRequest
): Promise<NextResponse> {
const { pathname } = request.nextUrl
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/assets') ||
pathname.startsWith('/favicon') ||
pathname === '/'
) {
return NextResponse.next()
}
const simplifiedPathKey = pathname.replace('/for', '')
let pathKey = ''
try {
pathKey = decodeURIComponent(simplifiedPathKey)
} catch (e) {
pathKey = simplifiedPathKey
}
if (keyCodeEventValues.find(x => x.path === pathKey)) {
return NextResponse.next()
}
const key = pathKey.replace('/', '')
const keycodeData = checkRedirectForKeycode(keyCodeEventValues, key)
if (keycodeData?.path) {
return redirect(request, keycodeData.path)
}
return NextResponse.next()
}