-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathapi.ts
More file actions
284 lines (251 loc) · 8.63 KB
/
api.ts
File metadata and controls
284 lines (251 loc) · 8.63 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
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
import type { Construct } from 'constructs';
import type { WebSocketRouteOptions } from './route';
import { WebSocketRoute } from './route';
import type { IGrantable } from '../../../aws-iam';
import { Grant } from '../../../aws-iam';
import { ArnFormat, Stack, Token } from '../../../core';
import { UnscopedValidationError, ValidationError } from '../../../core/lib/errors';
import { addConstructMetadata, MethodMetadata } from '../../../core/lib/metadata-resource';
import { lit } from '../../../core/lib/private/literal-string';
import { propertyInjectable } from '../../../core/lib/prop-injectable';
import { CfnApi } from '../apigatewayv2.generated';
import type { ApiReference, IApiRef } from '../apigatewayv2.generated';
import type { IApi, IpAddressType } from '../common/api';
import { ApiBase } from '../common/base';
/**
* Represents a reference to an HTTP API
*/
export interface IWebSocketApiRef extends IApiRef {
/**
* Indicates that this is a WebSocket API
*
* Will always return true, but is necessary to prevent accidental structural
* equality in TypeScript.
*/
readonly isWebsocketApi: boolean;
}
/**
* Represents a WebSocket API
*/
export interface IWebSocketApi extends IApi, IWebSocketApiRef {
}
/**
* Represents the currently available API Key Selection Expressions
*/
export class WebSocketApiKeySelectionExpression {
/**
* The API will extract the key value from the `x-api-key` header in the user request.
*/
public static readonly HEADER_X_API_KEY = new WebSocketApiKeySelectionExpression('$request.header.x-api-key');
/**
* The API will extract the key value from the `usageIdentifierKey` attribute in the `context` map,
* returned by the Lambda Authorizer.
* See https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
*/
public static readonly AUTHORIZER_USAGE_IDENTIFIER_KEY = new WebSocketApiKeySelectionExpression('$context.authorizer.usageIdentifierKey');
/**
* @param customApiKeySelector The expression used by API Gateway
*/
public constructor(public readonly customApiKeySelector: string) {}
}
/**
* Props for WebSocket API
*/
export interface WebSocketApiProps {
/**
* Name for the WebSocket API resource
* @default - id of the WebSocketApi construct.
*/
readonly apiName?: string;
/**
* An API key selection expression. Providing this option will require an API Key be provided to access the API.
* @default - Key is not required to access these APIs
*/
readonly apiKeySelectionExpression?: WebSocketApiKeySelectionExpression;
/**
* The description of the API.
* @default - none
*/
readonly description?: string;
/**
* The route selection expression for the API
* @default '$request.body.action'
*/
readonly routeSelectionExpression?: string;
/**
* Options to configure a '$connect' route
*
* @default - no '$connect' route configured
*/
readonly connectRouteOptions?: WebSocketRouteOptions;
/**
* Options to configure a '$disconnect' route
*
* @default - no '$disconnect' route configured
*/
readonly disconnectRouteOptions?: WebSocketRouteOptions;
/**
* Options to configure a '$default' route
*
* @default - no '$default' route configured
*/
readonly defaultRouteOptions?: WebSocketRouteOptions;
/**
* The IP address types that can invoke the API.
*
* @see https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-ip-address-type.html
*
* @default undefined - AWS default is IPV4
*/
readonly ipAddressType?: IpAddressType;
/**
* Avoid validating models when creating a deployment.
*
* @default false
*/
readonly disableSchemaValidation?: boolean;
}
/**
* Attributes for importing a WebSocketApi into the CDK
*/
export interface WebSocketApiAttributes {
/**
* The identifier of the WebSocketApi
*/
readonly webSocketId: string;
/**
* The endpoint URL of the WebSocketApi
* @default - throw san error if apiEndpoint is accessed.
*/
readonly apiEndpoint?: string;
}
/**
* Create a new API Gateway WebSocket API endpoint.
* @resource AWS::ApiGatewayV2::Api
*/
@propertyInjectable
export class WebSocketApi extends ApiBase implements IWebSocketApi {
/** Uniquely identifies this class. */
public static readonly PROPERTY_INJECTION_ID: string = 'aws-cdk-lib.aws-apigatewayv2.WebSocketApi';
/**
* Import an existing WebSocket API into this CDK app.
*/
public static fromWebSocketApiAttributes(scope: Construct, id: string, attrs: WebSocketApiAttributes): IWebSocketApi {
class Import extends ApiBase {
public readonly isWebsocketApi = true;
public readonly apiId = attrs.webSocketId;
public readonly websocketApiId = attrs.webSocketId;
private readonly _apiEndpoint = attrs.apiEndpoint;
public get apiEndpoint(): string {
if (!this._apiEndpoint) {
throw new ValidationError(lit`ApiEndpointConfiguredImportedWeb`, 'apiEndpoint is not configured on the imported WebSocketApi.', scope);
}
return this._apiEndpoint;
}
}
return new Import(scope, id);
}
public readonly isWebsocketApi = true;
public readonly apiId: string;
public readonly apiEndpoint: string;
/**
* A human friendly name for this WebSocket API. Note that this is different from `webSocketApiId`.
*/
public readonly webSocketApiName?: string;
constructor(scope: Construct, id: string, props?: WebSocketApiProps) {
super(scope, id);
// Enhanced CDK Analytics Telemetry
addConstructMetadata(this, props);
this.webSocketApiName = props?.apiName ?? id;
const resource = new CfnApi(this, 'Resource', {
name: this.webSocketApiName,
apiKeySelectionExpression: props?.apiKeySelectionExpression?.customApiKeySelector,
protocolType: 'WEBSOCKET',
description: props?.description,
routeSelectionExpression: props?.routeSelectionExpression ?? '$request.body.action',
ipAddressType: props?.ipAddressType,
disableSchemaValidation: props?.disableSchemaValidation,
});
this.apiId = resource.ref;
this.apiEndpoint = resource.attrApiEndpoint;
if (props?.connectRouteOptions) {
this.addRoute('$connect', props.connectRouteOptions);
}
if (props?.disconnectRouteOptions) {
this.addRoute('$disconnect', props.disconnectRouteOptions);
}
if (props?.defaultRouteOptions) {
this.addRoute('$default', props.defaultRouteOptions);
}
}
/**
* Add a new route
*/
@MethodMetadata()
public addRoute(routeKey: string, options: WebSocketRouteOptions) {
return new WebSocketRoute(this, `${routeKey}-Route`, {
webSocketApi: this,
routeKey,
...options,
});
}
/**
* Grant access to the API Gateway management API for this WebSocket API to an IAM
* principal (Role/Group/User).
* [disable-awslint:no-grants]
*
* @param identity The principal
*/
@MethodMetadata()
public grantManageConnections(identity: IGrantable): Grant {
const arn = Stack.of(this).formatArn({
service: 'execute-api',
resource: this.apiId,
});
return Grant.addToPrincipal({
grantee: identity,
actions: ['execute-api:ManageConnections'],
resourceArns: [`${arn}/*/*/@connections/*`],
});
}
/**
* Get the "execute-api" ARN.
*
* @deprecated Use `arnForExecuteApiV2()` instead.
*/
@MethodMetadata()
public arnForExecuteApi(method?: string, path?: string, stage?: string): string {
if (path && !Token.isUnresolved(path) && !path.startsWith('/')) {
throw new UnscopedValidationError(lit`PathStart`, `Path must start with '/': ${path}`);
}
if (method && method.toUpperCase() === 'ANY') {
method = '*';
}
return Stack.of(this).formatArn({
service: 'execute-api',
resource: this.apiId,
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
resourceName: `${stage ?? '*'}/${method ?? '*'}${path ?? '/*'}`,
});
}
/**
* Get the "execute-api" ARN.
*
* @default - The default behavior applies when no specific route, or stage is provided.
* In this case, the ARN will cover all routes, and all stages of this API.
* Specifically, if 'route' is not specified, it defaults to '*', representing all routes.
* If 'stage' is not specified, it also defaults to '*', representing all stages.
*/
@MethodMetadata()
public arnForExecuteApiV2(route?: string, stage?: string): string {
return Stack.of(this).formatArn({
service: 'execute-api',
resource: this.apiId,
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
resourceName: `${stage ?? '*'}/${route ?? '*'}`,
});
}
public get apiRef(): ApiReference {
return { apiId: this.apiId };
}
}