-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathparseRequestUrl.ts
38 lines (33 loc) · 1.37 KB
/
parseRequestUrl.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
import { basename, extname } from 'path';
import type { NextApiRequest } from 'next';
import { NEXT_REQUEST_META } from 'next/dist/server/request-meta';
export function parseRequestUrl(req: NextApiRequest, directoryPath?: string, fileName?: string): string {
const nextReqMeta = req[NEXT_REQUEST_META];
const url = (nextReqMeta?._nextDidRewrite && nextReqMeta._nextRewroteUrl
? nextReqMeta._nextRewroteUrl
: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
req.url!
).split('?')[0];
let path = url.split('/').slice(3).join('/');
// The path for parametererized routes should be set to "/", in order for the methods to be matched.
if (fileName?.startsWith('[')) {
path = '/';
}
if (directoryPath && !fileName?.startsWith('[...')) {
const pathRegExp = new RegExp(
// "pages/api/articles/index.ts" is compiled into "pages/api/articles.js" which has to be appended to the directory path for parsing
directoryPath.split('/pages')[1].replace(/(\[[0-9a-zA-Z-]+\])/, '([0-9a-zA-Z-]+)') +
(fileName && !fileName.startsWith('[...') && !fileName.startsWith('[[...')
? `/${basename(fileName, extname(fileName))}`
: '')
);
/* istanbul ignore else */
if (pathRegExp.test(url)) {
path = url.replace(pathRegExp, '');
}
}
if (!path.startsWith('/')) {
path = `/${path}`;
}
return path;
}