forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-handler.ts
72 lines (63 loc) · 2.07 KB
/
api-handler.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
import { parse as parseUrl } from 'url'
import { IncomingMessage, ServerResponse } from 'http'
import { apiResolver } from '../../../../server/api-utils'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { DecodeError } from '../../../../shared/lib/utils'
import { NodeNextResponse, NodeNextRequest } from '../../../../server/base-http'
export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
const {
handleRewrites,
handleBasePath,
dynamicRouteMatcher,
normalizeDynamicRouteParams,
} = getUtils(ctx)
return async (
rawReq: NodeNextRequest | IncomingMessage,
rawRes: NodeNextResponse | ServerResponse
) => {
const req =
rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq
const res =
rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = req.headers[vercelHeader]
const parsedUrl = handleRewrites(req, parseUrl(req.url!, true))
if (parsedUrl.query.nextInternalLocale) {
delete parsedUrl.query.nextInternalLocale
}
handleBasePath(req, parsedUrl)
let params = {}
if (pageIsDynamic) {
const result = normalizeDynamicRouteParams(
trustQuery
? parsedUrl.query
: (dynamicRouteMatcher!(parsedUrl.pathname) as Record<
string,
string | string[]
>)
)
params = result.params
}
await apiResolver(
req.req,
res.res,
Object.assign({}, parsedUrl.query, params),
await pageModule,
encodedPreviewProps,
true
)
} catch (err) {
console.error(err)
if (err instanceof DecodeError) {
res.statusCode = 400
res.body('Bad Request').send()
} else {
// Throw the error to crash the serverless function
throw err
}
}
}
}