forked from open-constructs/cdk-serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-api.ts
269 lines (236 loc) · 8.49 KB
/
http-api.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import * as fs from 'fs';
import * as apiGW from '@aws-cdk/aws-apigatewayv2';
import * as apiGWInteg from '@aws-cdk/aws-apigatewayv2-integrations';
import * as acm from '@aws-cdk/aws-certificatemanager';
import * as lambda from '@aws-cdk/aws-lambda';
import * as route53 from '@aws-cdk/aws-route53';
import * as route53Target from '@aws-cdk/aws-route53-targets';
import * as cdk from '@aws-cdk/core';
import * as yaml from 'js-yaml';
import { OpenAPI3, OperationObject, PathItemObject } from 'openapi-typescript';
import { BaseApi, BaseApiProps } from './base-api';
import { LambdaFunction } from './func';
export interface HttpApiProps extends BaseApiProps {
/**
* Domain name of the API (e.g. example.com)
*
* @default - No custom domain is configured
*/
domainName?: string;
/**
* Hostname of the API if a domain name is specified
*
* @default api
*/
apiHostname?: string;
/**
* Generate routes for all endpoints configured in the openapi.yaml file
*
* @default true
*/
autoGenerateRoutes?: boolean;
/**
* custom options for the created HttpApi
*
* @default -
*/
httpApiProps?: apiGW.HttpApiProps;
}
export class HttpApi<PATHS, OPS> extends BaseApi {
public readonly api: apiGW.HttpApi;
public readonly apiSpec: OpenAPI3;
private _functions: { [operationId: string]: LambdaFunction } = {};
constructor(scope: cdk.Construct, id: string, private props: HttpApiProps) {
super(scope, id, props);
this.apiSpec = yaml.load(fs.readFileSync('openapi.yaml').toString()) as OpenAPI3;
let customDomainName;
if (props.domainName) {
const hostedZone = route53.HostedZone.fromLookup(this, 'Zone', { domainName: props.domainName });
const apiDomainName = `${props.apiHostname ?? 'api'}.${props.domainName}`;
customDomainName = new apiGW.DomainName(this, 'DomainName', {
domainName: apiDomainName,
certificate: new acm.Certificate(this, 'Cert', {
domainName: apiDomainName,
validation: acm.CertificateValidation.fromDns(hostedZone),
}),
});
new route53.ARecord(this, 'DnsRecord', {
zone: hostedZone,
recordName: apiDomainName,
target: route53.RecordTarget.fromAlias(
new route53Target.ApiGatewayv2DomainProperties(customDomainName.regionalDomainName, customDomainName.regionalHostedZoneId),
),
});
}
this.api = new apiGW.HttpApi(this, 'Resource', {
apiName: `${props.apiName} [${props.stageName}]`,
...customDomainName && {
defaultDomainMapping: {
domainName: customDomainName,
},
},
...props.httpApiProps,
});
if ((props.monitoring ?? true) && this.monitoring) {
this.monitoring.apiErrorsWidget.addLeftMetric(this.api.metricServerError({
statistic: 'sum',
}));
this.monitoring.apiErrorsWidget.addLeftMetric(this.api.metricClientError({
statistic: 'sum',
}));
this.monitoring.apiLatencyWidget.addLeftMetric(this.api.metricLatency({
statistic: 'Average',
}));
this.monitoring.apiLatencyWidget.addLeftMetric(this.api.metricLatency({
statistic: 'p90',
}));
this.monitoring.apiLatencyTailWidget.addLeftMetric(this.api.metricLatency({
statistic: 'p95',
}));
this.monitoring.apiLatencyTailWidget.addLeftMetric(this.api.metricLatency({
statistic: 'p99',
}));
}
if (props.autoGenerateRoutes ?? true) {
for (const path in this.apiSpec.paths) {
if (Object.prototype.hasOwnProperty.call(this.apiSpec.paths, path)) {
const pathItem = this.apiSpec.paths[path];
for (const method in pathItem) {
if (Object.prototype.hasOwnProperty.call(pathItem, method) &&
['get', 'post', 'put', 'delete', 'patch', 'options', 'head'].indexOf(method) >= 0) {
// Add all operations
this.addRestResource(path as any, method as any);
}
}
}
}
}
}
/**
* getFunctionForOperation
*/
public getFunctionForOperation(operationId: keyof OPS): LambdaFunction {
return this._functions[operationId as string];
}
public addRoute<P extends keyof PATHS>(path: P, method: keyof PATHS[P], handler: lambda.Function) {
this.addCustomRoute(path as string, method as string, handler);
}
public addCustomRoute(path: string, method: string, handler: lambda.Function) {
const apiMethod = this.methodTransform(method);
new apiGW.HttpRoute(this, `${apiMethod}${path}`, {
httpApi: this.api,
routeKey: apiGW.HttpRouteKey.with(path, apiMethod),
integration: new apiGWInteg.LambdaProxyIntegration({ handler }),
});
}
public addRestResource<P extends keyof PATHS>(path: P, method: keyof PATHS[P]) {
const oaPath = this.apiSpec.paths![path as string];
const operation = oaPath[method as keyof PathItemObject] as OperationObject;
const operationId = operation.operationId!;
const description = `${method} ${path} - ${operation.summary}`;
return this.addCustomRestResource(path as string, method as string, operationId, description);
}
public addCustomRestResource(path: string, method: string, operationId: string, description: string) {
const entryFile = `./src/lambda/rest.${operationId}.ts`;
if (!fs.existsSync(entryFile)) {
this.createEntryFile(entryFile, method as string, operationId);
}
const fn = new LambdaFunction(this, `Fn${operationId}`, {
stageName: this.props.stageName,
additionalEnv: {
...this.props.domainName && {
DOMAIN_NAME: this.props.domainName,
},
...this.props.additionalEnv,
},
entry: entryFile,
description: `[${this.props.stageName}] ${description}`,
...this.authentication && {
userPool: this.authentication?.userpool,
},
...this.singleTableDatastore && {
table: this.singleTableDatastore.table,
tableWrites: this.tableWriteAccessForMethod(method as string),
},
...this.assetCdn && {
assetDomainName: this.assetCdn.assetDomainName,
assetBucket: this.assetCdn.assetBucket,
},
lambdaOptions: this.props.lambdaOptions,
lambdaTracing: this.props.lambdaTracing,
});
this._functions[operationId] = fn;
cdk.Tags.of(fn).add('OpenAPI', description.replace(/[^\w\s\d_.:/=+\-@]/g, ''));
if (this.monitoring) {
this.monitoring.lambdaDurationsWidget.addLeftMetric(fn.metricDuration());
this.monitoring.lambdaInvokesWidget.addLeftMetric(fn.metricInvocations());
this.monitoring.lambdaErrorsWidget.addLeftMetric(fn.metricErrors());
this.monitoring.lambdaErrorsWidget.addLeftMetric(fn.metricThrottles());
}
this.addCustomRoute(path, method, fn);
return fn;
}
private createEntryFile(entryFile: string, method: string, operationId: string) {
let factoryCall;
let logs;
switch (method.toLowerCase()) {
case 'post':
case 'put':
case 'patch':
factoryCall = `http.createOpenApiHandlerWithRequestBody<operations['${operationId}']>(async (ctx, data) => {`;
logs = 'ctx.logger.info(JSON.stringify(data));';
break;
case 'options':
case 'delete':
case 'get':
case 'head':
default:
factoryCall = `http.createOpenApiHandler<operations['${operationId}']>(async (ctx) => {`;
logs = '';
break;
}
fs.writeFileSync(entryFile, `import { http, errors } from '@taimos/lambda-toolbox';
import { operations } from './types.generated';
export const handler = ${factoryCall}
ctx.logger.info(JSON.stringify(ctx.event));
${logs}
throw new errors.HttpError(500, 'Not yet implemented');
});`, {
encoding: 'utf-8',
});
}
private tableWriteAccessForMethod(method: string): boolean {
switch (method.toLowerCase()) {
case 'delete':
case 'post':
case 'put':
case 'patch':
return true;
case 'options':
case 'get':
case 'head':
default:
return false;
}
}
private methodTransform(method: string) {
switch (method.toLowerCase()) {
case 'get':
return apiGW.HttpMethod.GET;
case 'delete':
return apiGW.HttpMethod.DELETE;
case 'post':
return apiGW.HttpMethod.POST;
case 'put':
return apiGW.HttpMethod.PUT;
case 'head':
return apiGW.HttpMethod.HEAD;
case 'options':
return apiGW.HttpMethod.OPTIONS;
case 'patch':
return apiGW.HttpMethod.PATCH;
default:
return apiGW.HttpMethod.ANY;
}
}
}