Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(apigateway): define Resources on imported RestApi #8270

Merged
merged 10 commits into from
Jun 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions packages/@aws-cdk/aws-apigateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ running on AWS Lambda, or any web application.
## Table of Contents

- [Defining APIs](#defining-apis)
- [Breaking up Methods and Resources across Stacks](#breaking-up-methods-and-resources-across-stacks)
- [AWS Lambda-backed APIs](#aws-lambda-backed-apis)
- [Integration Targets](#integration-targets)
- [Working with models](#working-with-models)
Expand Down Expand Up @@ -99,6 +100,18 @@ item.addMethod('GET'); // GET /items/{item}
item.addMethod('DELETE', new apigateway.HttpIntegration('http://amazon.com'));
```

### Breaking up Methods and Resources across Stacks

It is fairly common for REST APIs with a large number of Resources and Methods to hit the [CloudFormation
limit](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) of 200 resources per
stack.

To help with this, Resources and Methods for the same REST API can be re-organized across multiple stacks. A common
way to do this is to have a stack per Resource or groups of Resources, but this is not the only possible way.
The following example uses sets up two Resources '/pets' and '/books' in separate stacks using nested stacks:

[Resources grouped into nested stacks](test/integ.restapi-import.lit.ts)

## Integration Targets

Methods are associated with backend integrations, which are invoked when this
Expand Down Expand Up @@ -950,12 +963,18 @@ CDK supports creating a REST API by importing an OpenAPI definition file. It cur
v3.0 definition files. Read more about [Configuring a REST API using
OpenAPI](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-import-api.html).

It is possible to use the `addResource()` API to define additional API Gateway Resources. **Note that,** deployment
will fail if a Resource of the same name is already defined in the Open API specification.

The following code creates a REST API using an external OpenAPI definition JSON file -

```ts
const api = new apigateway.SpecRestApi(this, 'books-api', {
apiDefinition: apigateway.ApiDefinition.fromAsset('path-to-file.json')
});

const booksResource = api.root.addResource('books')
booksResource.addMethod('GET', ...);
```

There are a number of limitations in using OpenAPI definitions in API Gateway. Read the [Amazon API Gateway important
Expand All @@ -965,8 +984,6 @@ for more details.
**Note:** When starting off with an OpenAPI definition using `SpecRestApi`, it is not possible to configure some
properties that can be configured directly in the OpenAPI specification file. This is to prevent people duplication
of these properties and potential confusion.
Further, it is currently also not possible to configure Methods and Resources in addition to the ones in the
specification file.

## APIGateway v2

Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-apigateway/lib/authorizer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Construct, Resource, ResourceProps } from '@aws-cdk/core';
import { AuthorizationType } from './method';
import { RestApi } from './restapi';
import { IRestApi } from './restapi';

const AUTHORIZER_SYMBOL = Symbol.for('@aws-cdk/aws-apigateway.Authorizer');

Expand Down Expand Up @@ -28,7 +28,7 @@ export abstract class Authorizer extends Resource implements IAuthorizer {
* Called when the authorizer is used from a specific REST API.
* @internal
*/
public abstract _attachToApi(restApi: RestApi): void;
public abstract _attachToApi(restApi: IRestApi): void;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-apigateway/lib/authorizers/lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as lambda from '@aws-cdk/aws-lambda';
import { Construct, Duration, Lazy, Stack } from '@aws-cdk/core';
import { CfnAuthorizer } from '../apigateway.generated';
import { Authorizer, IAuthorizer } from '../authorizer';
import { RestApi } from '../restapi';
import { IRestApi } from '../restapi';

/**
* Base properties for all lambda authorizers
Expand Down Expand Up @@ -83,7 +83,7 @@ abstract class LambdaAuthorizer extends Authorizer implements IAuthorizer {
* Attaches this authorizer to a specific REST API.
* @internal
*/
public _attachToApi(restApi: RestApi) {
public _attachToApi(restApi: IRestApi) {
if (this.restApiId && this.restApiId !== restApi.restApiId) {
throw new Error('Cannot attach authorizer to two different rest APIs');
}
Expand Down
25 changes: 18 additions & 7 deletions packages/@aws-cdk/aws-apigateway/lib/method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { MethodResponse } from './methodresponse';
import { IModel } from './model';
import { IRequestValidator, RequestValidatorOptions } from './requestvalidator';
import { IResource } from './resource';
import { RestApi } from './restapi';
import { IRestApi, RestApi } from './restapi';
import { validateHttpMethod } from './util';

export interface MethodOptions {
Expand Down Expand Up @@ -159,13 +159,16 @@ export class Method extends Resource {

public readonly httpMethod: string;
public readonly resource: IResource;
public readonly restApi: RestApi;
/**
* The API Gateway RestApi associated with this method.
*/
public readonly api: IRestApi;

constructor(scope: Construct, id: string, props: MethodProps) {
super(scope, id);

this.resource = props.resource;
this.restApi = props.resource.restApi;
this.api = props.resource.api;
this.httpMethod = props.httpMethod.toUpperCase();

validateHttpMethod(this.httpMethod);
Expand All @@ -186,12 +189,12 @@ export class Method extends Resource {
}

if (Authorizer.isAuthorizer(authorizer)) {
authorizer._attachToApi(this.restApi);
authorizer._attachToApi(this.api);
}

const methodProps: CfnMethodProps = {
resourceId: props.resource.resourceId,
restApiId: this.restApi.restApiId,
restApiId: this.api.restApiId,
httpMethod: this.httpMethod,
operationName: options.operationName || defaultMethodOptions.operationName,
apiKeyRequired: options.apiKeyRequired || defaultMethodOptions.apiKeyRequired,
Expand All @@ -209,15 +212,23 @@ export class Method extends Resource {

this.methodId = resource.ref;

props.resource.restApi._attachMethod(this);
props.resource.api._attachMethod(this);

const deployment = props.resource.restApi.latestDeployment;
const deployment = props.resource.api.latestDeployment;
if (deployment) {
deployment.node.addDependency(resource);
deployment.addToLogicalId({ method: methodProps });
}
}

/**
* The RestApi associated with this Method
* @deprecated - Throws an error if this Resource is not associated with an instance of `RestApi`. Use `api` instead.
*/
public get restApi(): RestApi {
return this.resource.restApi;
}

/**
* Returns an execute-api ARN for this method:
*
Expand Down
33 changes: 26 additions & 7 deletions packages/@aws-cdk/aws-apigateway/lib/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,21 @@ import { Cors, CorsOptions } from './cors';
import { Integration } from './integration';
import { MockIntegration } from './integrations';
import { Method, MethodOptions } from './method';
import { RestApi } from './restapi';
import { MutableRestApi, RestApi } from './restapi';

export interface IResource extends IResourceBase {
/**
* The parent of this resource or undefined for the root resource.
*/
readonly parentResource?: IResource;

/**
* The rest API that this resource is part of.
*
* @deprecated - Throws an error if this Resource is not associated with an instance of `RestApi`. Use `api` instead.
*/
readonly restApi: RestApi;

/**
* The rest API that this resource is part of.
*
Expand All @@ -20,7 +27,7 @@ export interface IResource extends IResourceBase {
* hash to determine the ID of the deployment. This allows us to automatically update
* the deployment when the model of the REST API changes.
*/
readonly restApi: RestApi;
readonly api: MutableRestApi;

/**
* The ID of the resource.
Expand Down Expand Up @@ -154,7 +161,11 @@ export interface ResourceProps extends ResourceOptions {

export abstract class ResourceBase extends ResourceConstruct implements IResource {
public abstract readonly parentResource?: IResource;
/**
* @deprecated - Throws an error if this Resource is not associated with an instance of `RestApi`. Use `api` instead.
*/
public abstract readonly restApi: RestApi;
public abstract readonly api: MutableRestApi;
public abstract readonly resourceId: string;
public abstract readonly path: string;
public abstract readonly defaultIntegration?: Integration;
Expand Down Expand Up @@ -354,13 +365,13 @@ export abstract class ResourceBase extends ResourceConstruct implements IResourc
}

public get url(): string {
return this.restApi.urlForPath(this.path);
return this.api.urlForPath(this.path);
}
}

export class Resource extends ResourceBase {
public readonly parentResource?: IResource;
public readonly restApi: RestApi;
public readonly api: MutableRestApi;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to just expose IRestApi here and this way avoid exposing MutableRestApi as a public api?

This might require type checks in the code but it will keep the public api cleaner and with less surface.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've taken another stab at trying to erase this type from the public API. However, it requires some methods to be promoted into IRestApi. Let me know what you think here.

public readonly resourceId: string;
public readonly path: string;

Expand All @@ -380,21 +391,21 @@ export class Resource extends ResourceBase {
}

const resourceProps: CfnResourceProps = {
restApiId: props.parent.restApi.restApiId,
restApiId: props.parent.api.restApiId,
parentId: props.parent.resourceId,
pathPart: props.pathPart,
};
const resource = new CfnResource(this, 'Resource', resourceProps);

this.resourceId = resource.ref;
this.restApi = props.parent.restApi;
this.api = props.parent.api;

// render resource path (special case for root)
this.path = props.parent.path;
if (!this.path.endsWith('/')) { this.path += '/'; }
this.path += props.pathPart;

const deployment = props.parent.restApi.latestDeployment;
const deployment = props.parent.api.latestDeployment;
if (deployment) {
deployment.node.addDependency(resource);
deployment.addToLogicalId({ resource: resourceProps });
Expand All @@ -413,6 +424,14 @@ export class Resource extends ResourceBase {
this.addCorsPreflight(this.defaultCorsPreflightOptions);
}
}

/**
* The RestApi associated with this Resource
* @deprecated - Throws an error if this Resource is not associated with an instance of `RestApi`. Use `api` instead.
*/
public get restApi(): RestApi {
return this.parentResource!.restApi;
}
}

export interface ProxyResourceOptions extends ResourceOptions {
Expand Down
Loading