-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda-handler.ts
More file actions
88 lines (80 loc) · 2.4 KB
/
lambda-handler.ts
File metadata and controls
88 lines (80 loc) · 2.4 KB
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
/**
* AWS Lambda Handler for ts-analytics API (Bun Runtime)
*
* Uses bun-lambda layer for native Bun runtime on AWS Lambda.
* Exports Bun server format: { fetch(request): Response }
*
* All handlers are organized in the handlers/ directory.
*/
import { router } from '../src/router'
/**
* Add CORS headers to response
*/
function addCorsHeaders(response: Response): Response {
const headers = new Headers(response.headers)
if (!headers.has('Access-Control-Allow-Origin')) {
headers.set('Access-Control-Allow-Origin', '*')
}
if (!headers.has('Access-Control-Allow-Methods')) {
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
}
if (!headers.has('Access-Control-Allow-Headers')) {
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
})
}
/**
* Bun server export for bun-lambda
*
* The bun-lambda runtime automatically converts Lambda events
* to standard Request objects and Response back to Lambda format.
*/
export default {
async fetch(request: Request): Promise<Response> {
// Log request for debugging (can be disabled in production)
if (process.env.DEBUG_REQUESTS === 'true') {
const url = new URL(request.url)
console.log('Incoming request:', {
url: request.url,
path: url.pathname,
method: request.method,
search: url.search,
})
}
// Handle OPTIONS (CORS preflight)
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
})
}
try {
const response = await router.handleRequest(request)
return addCorsHeaders(response)
}
catch (error) {
console.error('Lambda handler error:', error)
return new Response(
JSON.stringify({
error: 'Internal Server Error',
message: error instanceof Error ? error.message : 'Unknown error',
}),
{
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
},
)
}
},
}