-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
restapi.ts
535 lines (465 loc) · 15.5 KB
/
restapi.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { IVpcEndpoint } from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import { CfnOutput, Construct, IResource as IResourceBase, Resource, Stack } from '@aws-cdk/core';
import { ApiKey, IApiKey } from './api-key';
import { CfnAccount, CfnRestApi } from './apigateway.generated';
import { CorsOptions } from './cors';
import { Deployment } from './deployment';
import { DomainName, DomainNameOptions } from './domain-name';
import { Integration } from './integration';
import { Method, MethodOptions } from './method';
import { Model, ModelOptions } from './model';
import { RequestValidator, RequestValidatorOptions } from './requestvalidator';
import { IResource, ResourceBase, ResourceOptions } from './resource';
import { Stage, StageOptions } from './stage';
import { UsagePlan, UsagePlanProps } from './usage-plan';
export interface IRestApi extends IResourceBase {
/**
* The ID of this API Gateway RestApi.
* @attribute
*/
readonly restApiId: string;
}
export interface RestApiProps extends ResourceOptions {
/**
* Indicates if a Deployment should be automatically created for this API,
* and recreated when the API model (resources, methods) changes.
*
* Since API Gateway deployments are immutable, When this option is enabled
* (by default), an AWS::ApiGateway::Deployment resource will automatically
* created with a logical ID that hashes the API model (methods, resources
* and options). This means that when the model changes, the logical ID of
* this CloudFormation resource will change, and a new deployment will be
* created.
*
* If this is set, `latestDeployment` will refer to the `Deployment` object
* and `deploymentStage` will refer to a `Stage` that points to this
* deployment. To customize the stage options, use the `deployOptions`
* property.
*
* A CloudFormation Output will also be defined with the root URL endpoint
* of this REST API.
*
* @default true
*/
readonly deploy?: boolean;
/**
* Options for the API Gateway stage that will always point to the latest
* deployment when `deploy` is enabled. If `deploy` is disabled,
* this value cannot be set.
*
* @default - Based on defaults of `StageOptions`.
*/
readonly deployOptions?: StageOptions;
/**
* Retains old deployment resources when the API changes. This allows
* manually reverting stages to point to old deployments via the AWS
* Console.
*
* @default false
*/
readonly retainDeployments?: boolean;
/**
* A name for the API Gateway RestApi resource.
*
* @default - ID of the RestApi construct.
*/
readonly restApiName?: string;
/**
* Custom header parameters for the request.
* @see https://docs.aws.amazon.com/cli/latest/reference/apigateway/import-rest-api.html
*
* @default - No parameters.
*/
readonly parameters?: { [key: string]: string };
/**
* A policy document that contains the permissions for this RestApi
*
* @default - No policy.
*/
readonly policy?: iam.PolicyDocument;
/**
* A description of the purpose of this API Gateway RestApi resource.
*
* @default - No description.
*/
readonly description?: string;
/**
* The EndpointConfiguration property type specifies the endpoint types of a REST API
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-restapi-endpointconfiguration.html
*
* @default - No endpoint configuration
*/
readonly endpointConfiguration?: EndpointConfiguration;
/**
* A list of the endpoint types of the API. Use this property when creating
* an API.
*
* @default - No endpoint types.
* @deprecated this property is deprecated, use endpointConfiguration instead
*/
readonly endpointTypes?: EndpointType[];
/**
* The source of the API key for metering requests according to a usage
* plan.
*
* @default - Metering is disabled.
*/
readonly apiKeySourceType?: ApiKeySourceType;
/**
* The list of binary media mime-types that are supported by the RestApi
* resource, such as "image/png" or "application/octet-stream"
*
* @default - RestApi supports only UTF-8-encoded text payloads.
*/
readonly binaryMediaTypes?: string[];
/**
* Indicates whether to roll back the resource if a warning occurs while API
* Gateway is creating the RestApi resource.
*
* @default false
*/
readonly failOnWarnings?: boolean;
/**
* A nullable integer that is used to enable compression (with non-negative
* between 0 and 10485760 (10M) bytes, inclusive) or disable compression
* (when undefined) on an API. When compression is enabled, compression or
* decompression is not applied on the payload if the payload size is
* smaller than this value. Setting it to zero allows compression for any
* payload size.
*
* @default - Compression is disabled.
*/
readonly minimumCompressionSize?: number;
/**
* The ID of the API Gateway RestApi resource that you want to clone.
*
* @default - None.
*/
readonly cloneFrom?: IRestApi;
/**
* Automatically configure an AWS CloudWatch role for API Gateway.
*
* @default true
*/
readonly cloudWatchRole?: boolean;
/**
* Configure a custom domain name and map it to this API.
*
* @default - no domain name is defined, use `addDomainName` or directly define a `DomainName`.
*/
readonly domainName?: DomainNameOptions;
/**
* Export name for the CfnOutput containing the API endpoint
*
* @default - when no export name is given, output will be created without export
*/
readonly endpointExportName?: string;
}
/**
* Represents a REST API in Amazon API Gateway.
*
* Use `addResource` and `addMethod` to configure the API model.
*
* By default, the API will automatically be deployed and accessible from a
* public endpoint.
*/
export class RestApi extends Resource implements IRestApi {
public static fromRestApiId(scope: Construct, id: string, restApiId: string): IRestApi {
class Import extends Resource implements IRestApi {
public readonly restApiId = restApiId;
}
return new Import(scope, id);
}
/**
* The ID of this API Gateway RestApi.
*/
public readonly restApiId: string;
/**
* The resource ID of the root resource.
*
* @attribute
*/
public readonly restApiRootResourceId: string;
/**
* Represents the root resource ("/") of this API. Use it to define the API model:
*
* api.root.addMethod('ANY', redirectToHomePage); // "ANY /"
* api.root.addResource('friends').addMethod('GET', getFriendsHandler); // "GET /friends"
*
*/
public readonly root: IResource;
/**
* API Gateway stage that points to the latest deployment (if defined).
*
* If `deploy` is disabled, you will need to explicitly assign this value in order to
* set up integrations.
*/
public deploymentStage!: Stage;
/**
* The list of methods bound to this RestApi
*/
public readonly methods = new Array<Method>();
private _domainName?: DomainName;
private _latestDeployment: Deployment | undefined;
constructor(scope: Construct, id: string, props: RestApiProps = { }) {
super(scope, id, {
physicalName: props.restApiName || id,
});
const resource = new CfnRestApi(this, 'Resource', {
name: this.physicalName,
description: props.description,
policy: props.policy,
failOnWarnings: props.failOnWarnings,
minimumCompressionSize: props.minimumCompressionSize,
binaryMediaTypes: props.binaryMediaTypes,
endpointConfiguration: this.configureEndpoints(props),
apiKeySourceType: props.apiKeySourceType,
cloneFrom: props.cloneFrom ? props.cloneFrom.restApiId : undefined,
parameters: props.parameters
});
this.node.defaultChild = resource;
this.restApiId = resource.ref;
this.configureDeployment(props);
const cloudWatchRole = props.cloudWatchRole !== undefined ? props.cloudWatchRole : true;
if (cloudWatchRole) {
this.configureCloudWatchRole(resource);
}
this.root = new RootResource(this, props, resource.attrRootResourceId);
this.restApiRootResourceId = resource.attrRootResourceId;
if (props.domainName) {
this.addDomainName('CustomDomain', props.domainName);
}
}
/**
* The first domain name mapped to this API, if defined through the `domainName`
* configuration prop, or added via `addDomainName`
*/
public get domainName() {
return this._domainName;
}
/**
* API Gateway deployment that represents the latest changes of the API.
* This resource will be automatically updated every time the REST API model changes.
* This will be undefined if `deploy` is false.
*/
public get latestDeployment() {
return this._latestDeployment;
}
/**
* The deployed root URL of this REST API.
*/
public get url() {
return this.urlForPath();
}
/**
* Returns the URL for an HTTP path.
*
* Fails if `deploymentStage` is not set either by `deploy` or explicitly.
*/
public urlForPath(path: string = '/'): string {
if (!this.deploymentStage) {
throw new Error('Cannot determine deployment stage for API from "deploymentStage". Use "deploy" or explicitly set "deploymentStage"');
}
return this.deploymentStage.urlForPath(path);
}
/**
* Defines an API Gateway domain name and maps it to this API.
* @param id The construct id
* @param options custom domain options
*/
public addDomainName(id: string, options: DomainNameOptions): DomainName {
const domainName = new DomainName(this, id, {
...options,
mapping: this
});
if (!this._domainName) {
this._domainName = domainName;
}
return domainName;
}
/**
* Adds a usage plan.
*/
public addUsagePlan(id: string, props: UsagePlanProps = {}): UsagePlan {
return new UsagePlan(this, id, props);
}
/**
* Add an ApiKey
*/
public addApiKey(id: string): IApiKey {
return new ApiKey(this, id, {
resources: [this]
});
}
/**
* Adds a new model.
*/
public addModel(id: string, props: ModelOptions): Model {
return new Model(this, id, {
...props,
restApi: this
});
}
/**
* Adds a new request validator.
*/
public addRequestValidator(id: string, props: RequestValidatorOptions): RequestValidator {
return new RequestValidator(this, id, {
...props,
restApi: this
});
}
/**
* @returns The "execute-api" ARN.
* @default "*" returns the execute API ARN for all methods/resources in
* this API.
* @param method The method (default `*`)
* @param path The resource path. Must start with '/' (default `*`)
* @param stage The stage (default `*`)
*/
public arnForExecuteApi(method: string = '*', path: string = '/*', stage: string = '*') {
if (!path.startsWith('/')) {
throw new Error(`"path" must begin with a "/": '${path}'`);
}
if (method.toUpperCase() === 'ANY') {
method = '*';
}
return Stack.of(this).formatArn({
service: 'execute-api',
resource: this.restApiId,
sep: '/',
resourceName: `${stage}/${method}${path}`
});
}
/**
* Internal API used by `Method` to keep an inventory of methods at the API
* level for validation purposes.
*
* @internal
*/
public _attachMethod(method: Method) {
this.methods.push(method);
}
/**
* Performs validation of the REST API.
*/
protected validate() {
if (this.methods.length === 0) {
return [ 'The REST API doesn\'t contain any methods' ];
}
return [];
}
private configureDeployment(props: RestApiProps) {
const deploy = props.deploy === undefined ? true : props.deploy;
if (deploy) {
this._latestDeployment = new Deployment(this, 'Deployment', {
description: 'Automatically created by the RestApi construct',
api: this,
retainDeployments: props.retainDeployments
});
// encode the stage name into the construct id, so if we change the stage name, it will recreate a new stage.
// stage name is part of the endpoint, so that makes sense.
const stageName = (props.deployOptions && props.deployOptions.stageName) || 'prod';
this.deploymentStage = new Stage(this, `DeploymentStage.${stageName}`, {
deployment: this._latestDeployment,
...props.deployOptions
});
new CfnOutput(this, 'Endpoint', { exportName: props.endpointExportName, value: this.urlForPath() });
} else {
if (props.deployOptions) {
throw new Error('Cannot set \'deployOptions\' if \'deploy\' is disabled');
}
}
}
private configureCloudWatchRole(apiResource: CfnRestApi) {
const role = new iam.Role(this, 'CloudWatchRole', {
assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'),
managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonAPIGatewayPushToCloudWatchLogs')],
});
const resource = new CfnAccount(this, 'Account', {
cloudWatchRoleArn: role.roleArn
});
resource.node.addDependency(apiResource);
}
private configureEndpoints(props: RestApiProps): CfnRestApi.EndpointConfigurationProperty | undefined {
if (props.endpointTypes && props.endpointConfiguration) {
throw new Error('Only one of the RestApi props, endpointTypes or endpointConfiguration, is allowed');
}
if (props.endpointConfiguration) {
return {
types: props.endpointConfiguration.types,
vpcEndpointIds: props.endpointConfiguration?.vpcEndpoints?.map(vpcEndpoint => vpcEndpoint.vpcEndpointId)
};
}
if (props.endpointTypes) {
return { types: props.endpointTypes };
}
return undefined;
}
}
/**
* The endpoint configuration of a REST API, including VPCs and endpoint types.
*
* EndpointConfiguration is a property of the AWS::ApiGateway::RestApi resource.
*/
export interface EndpointConfiguration {
/**
* A list of endpoint types of an API or its custom domain name.
*
* @default - no endpoint types.
*/
readonly types: EndpointType[];
/**
* A list of VPC Endpoints against which to create Route53 ALIASes
*
* @default - no ALIASes are created for the endpoint.
*/
readonly vpcEndpoints?: IVpcEndpoint[];
}
export enum ApiKeySourceType {
/**
* To read the API key from the `X-API-Key` header of a request.
*/
HEADER = 'HEADER',
/**
* To read the API key from the `UsageIdentifierKey` from a custom authorizer.
*/
AUTHORIZER = 'AUTHORIZER',
}
export enum EndpointType {
/**
* For an edge-optimized API and its custom domain name.
*/
EDGE = 'EDGE',
/**
* For a regional API and its custom domain name.
*/
REGIONAL = 'REGIONAL',
/**
* For a private API and its custom domain name.
*/
PRIVATE = 'PRIVATE'
}
class RootResource extends ResourceBase {
public readonly parentResource?: IResource;
public readonly restApi: RestApi;
public readonly resourceId: string;
public readonly path: string;
public readonly defaultIntegration?: Integration | undefined;
public readonly defaultMethodOptions?: MethodOptions | undefined;
public readonly defaultCorsPreflightOptions?: CorsOptions | undefined;
constructor(api: RestApi, props: RestApiProps, resourceId: string) {
super(api, 'Default');
this.parentResource = undefined;
this.defaultIntegration = props.defaultIntegration;
this.defaultMethodOptions = props.defaultMethodOptions;
this.defaultCorsPreflightOptions = props.defaultCorsPreflightOptions;
this.restApi = api;
this.resourceId = resourceId;
this.path = '/';
if (this.defaultCorsPreflightOptions) {
this.addCorsPreflight(this.defaultCorsPreflightOptions);
}
}
}