-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroute.ts
More file actions
99 lines (85 loc) · 2.6 KB
/
route.ts
File metadata and controls
99 lines (85 loc) · 2.6 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
89
90
91
92
93
94
95
96
97
98
99
import type {
ApiGatewayHandler,
JWTAuthorizedApiGatewayHandler,
} from "src/shared";
import * as aws from "@notation/aws.iac";
import { api } from "./api";
import { AuthorizerConfig } from "./auth";
import { mapAuthConfig, mapAuthType } from "./utils";
export const route = (
apiGroup: ReturnType<typeof api>,
method: string, // todo: http methods only
path: `/${string}`,
auth: AuthorizerConfig,
handler:
| ApiGatewayHandler
| JWTAuthorizedApiGatewayHandler<any>
// todo: narrow to lambda group
| aws.AwsResourceGroup,
) => {
const apiResource = apiGroup.findResource(aws.apiGateway.Api)!;
const routeId = `${apiResource.id}-${method}-${path}`;
const lambdaGroup =
handler instanceof aws.AwsResourceGroup
? handler
: // at compile time, runtime module becomes infra resource group
(handler as any as aws.AwsResourceGroup);
const lambdaResource = lambdaGroup.findResource(aws.lambda.LambdaFunction)!;
let integration = lambdaGroup.findResource(aws.apiGateway.LambdaIntegration);
if (!integration) {
integration = lambdaGroup.add(
new aws.apiGateway.LambdaIntegration({
id: `${apiResource.id}-${lambdaResource.id}-integration`,
dependencies: {
api: apiResource,
lambda: lambdaResource,
},
}),
);
}
const permission = lambdaGroup.findResource(
aws.lambda.LambdaApiGatewayV2Permission,
);
if (!permission) {
lambdaGroup.add(
new aws.lambda.LambdaApiGatewayV2Permission({
id: `${lambdaResource.id}-${apiResource.id}-permission`,
dependencies: {
api: apiResource,
lambda: lambdaResource,
},
}),
);
}
const routeGroup = new aws.AwsResourceGroup("API Gateway/Route", {
dependencies: { router: apiGroup.id, fn: lambdaGroup.id },
});
if (auth.type != "NONE") {
const authConfig = mapAuthConfig(apiResource.id, method, path, auth);
const authorizer = new aws.apiGateway.RouteAuth({
id: `${routeId}-${apiResource.id}-authorizer`,
config: authConfig,
dependencies: {
api: apiResource,
},
});
routeGroup.add(authorizer);
}
const authorizerResource = routeGroup.findResource(aws.apiGateway.RouteAuth);
routeGroup.add(
new aws.apiGateway.Route({
id: routeId,
config: {
AuthorizationScopes: auth.scopes,
RouteKey: `${method} ${path}`,
AuthorizationType: mapAuthType(auth),
},
dependencies: {
api: apiResource,
lambdaIntegration: integration,
auth: authorizerResource,
},
}),
);
return routeGroup;
};