-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathruntime.ts
91 lines (79 loc) · 1.93 KB
/
runtime.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
import type { Context } from 'https://edge.netlify.com'
import edgeFunction from './bundle.js'
import { buildResponse } from './utils.ts'
export interface FetchEventResult {
response: Response
waitUntil: Promise<any>
}
export interface RequestData {
geo?: {
city?: string
country?: string
region?: string
latitude?: string
longitude?: string
}
headers: Record<string, string>
ip?: string
method: string
nextConfig?: {
basePath?: string
i18n?: Record<string, unknown>
trailingSlash?: boolean
}
page?: {
name?: string
params?: { [key: string]: string }
}
url: string
body?: ReadableStream<Uint8Array>
}
export interface RequestContext {
request: Request
context: Context
}
declare global {
// deno-lint-ignore no-var
var NFRequestContextMap: Map<string, RequestContext>
}
globalThis.NFRequestContextMap ||= new Map()
const handler = async (req: Request, context: Context) => {
const url = new URL(req.url)
if (url.pathname.startsWith('/_next/static/')) {
return
}
const geo = {
country: context.geo.country?.code,
region: context.geo.subdivision?.code,
city: context.geo.city,
}
const requestId = req.headers.get('x-nf-request-id')
if (!requestId) {
console.error('Missing x-nf-request-id header')
} else {
globalThis.NFRequestContextMap.set(requestId, {
request: req,
context,
})
}
const request: RequestData = {
headers: Object.fromEntries(req.headers.entries()),
geo,
url: url.toString(),
method: req.method,
ip: context.ip,
body: req.body ?? undefined,
}
try {
const result = await edgeFunction({ request })
return buildResponse({ result, request: req, context })
} catch (error) {
console.error(error)
return new Response(error.message, { status: 500 })
} finally {
if (requestId) {
globalThis.NFRequestContextMap.delete(requestId)
}
}
}
export default handler