-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorsOPTIONS.ts
More file actions
42 lines (41 loc) · 1.1 KB
/
corsOPTIONS.ts
File metadata and controls
42 lines (41 loc) · 1.1 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
import type { MiddlewareObj, Request } from '@middy/core'
import type {
APIGatewayProxyEventV2,
APIGatewayProxyStructuredResultV2,
} from 'aws-lambda'
import { corsHeaders } from './corsHeaders.ts'
export const corsOPTIONS = (
...allowedMethods: string[]
): MiddlewareObj<APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2> => {
const setCorsHeaders = async (
req: Request<APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2>,
) => {
if (req.response === null) {
console.error(`[corsOPTIONS]`, `Response is null`)
return
}
req.response = {
...req.response,
headers: {
...(req.response?.headers ?? {}),
...corsHeaders(req.event, allowedMethods),
},
}
}
return {
before: async (
req: Request<APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2>,
) => {
if (req.event.requestContext.http.method === 'OPTIONS') {
console.debug(`[corsOPTIONS]`, `Handling OPTIONS request`)
return {
statusCode: 200,
headers: corsHeaders(req.event, allowedMethods),
}
}
return undefined
},
after: setCorsHeaders,
onError: setCorsHeaders,
}
}