/
api-gateway-v2.adapter.ts
213 lines (179 loc) · 4.96 KB
/
api-gateway-v2.adapter.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
//#region Imports
import type { APIGatewayProxyEventV2, Context } from 'aws-lambda';
import type { APIGatewayProxyStructuredResultV2 } from 'aws-lambda/trigger/api-gateway-proxy';
import {
AdapterContract,
AdapterRequest,
GetResponseAdapterProps,
OnErrorProps,
} from '../../contracts';
import {
getDefaultIfUndefined,
getEventBodyAsBuffer,
getFlattenedHeadersMap,
getMultiValueHeadersMap,
getPathWithQueryStringParams,
} from '../../core';
//#endregion
/**
* The options to customize the {@link ApiGatewayV2Adapter}
*/
export interface ApiGatewayV2Options {
/**
* Strip base path for custom domains
*
* @default ''
*/
stripBasePath?: string;
}
/**
* The adapter to handle requests from AWS Api Gateway V2
*
* As per {@link https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html know issues}, we throw an exception when you send the `transfer-encoding=chunked`, currently, API Gateway doesn't support chunked transfer.
*
* @example```typescript
* const stripBasePath = '/any/custom/base/path'; // default ''
* const adapter = new ApiGatewayV2Adapter({ stripBasePath });
* ```
*
* {@link https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html Event Reference}
*/
export class ApiGatewayV2Adapter
implements
AdapterContract<
APIGatewayProxyEventV2,
Context,
APIGatewayProxyStructuredResultV2
>
{
//#region Constructor
/**
* Default constructor
*
* @param options The options to customize the {@link ApiGatewayV2Adapter}
*/
constructor(protected readonly options?: ApiGatewayV2Options) {}
//#endregion
//#region Public Methods
/**
* @inheritDoc
*/
public getAdapterName(): string {
return ApiGatewayV2Adapter.name;
}
/**
* @inheritDoc
*/
public canHandle(event: unknown): event is APIGatewayProxyEventV2 {
const apiGatewayEvent = event as Partial<APIGatewayProxyEventV2> & {
version?: string;
};
return !!(
apiGatewayEvent?.requestContext && apiGatewayEvent.version === '2.0'
);
}
/**
* @inheritDoc
*/
public getRequest(event: APIGatewayProxyEventV2): AdapterRequest {
const method = event.requestContext.http.method;
const path = this.getPathFromEvent(event);
const headers = getFlattenedHeadersMap(event.headers, ',', true);
if (event.cookies) headers.cookie = event.cookies.join('; ');
let body: Buffer | undefined;
if (event.body) {
const [bufferBody, contentLength] = getEventBodyAsBuffer(
event.body,
event.isBase64Encoded,
);
body = bufferBody;
headers['content-length'] = String(contentLength);
}
const remoteAddress = event.requestContext.http.sourceIp;
return {
method,
headers,
body,
remoteAddress,
path,
};
}
/**
* @inheritDoc
*/
public getResponse({
headers: responseHeaders,
body,
isBase64Encoded,
statusCode,
response,
}: GetResponseAdapterProps<APIGatewayProxyEventV2>): APIGatewayProxyStructuredResultV2 {
const headers = getFlattenedHeadersMap(responseHeaders);
const multiValueHeaders = getMultiValueHeadersMap(responseHeaders);
const transferEncodingHeader: string | undefined =
headers['transfer-encoding'];
const hasTransferEncodingChunked =
transferEncodingHeader && transferEncodingHeader.includes('chunked');
if (hasTransferEncodingChunked) {
throw new Error(
'chunked encoding in headers is not supported by API Gateway V1',
);
}
if (response?.chunkedEncoding) {
throw new Error(
'chunked encoding in response is not supported by API Gateway V1',
);
}
const cookies = multiValueHeaders['set-cookie'];
if (headers) delete headers['set-cookie'];
return {
statusCode,
body,
headers,
isBase64Encoded,
cookies,
};
}
/**
* @inheritDoc
*/
public onErrorWhileForwarding({
error,
delegatedResolver,
respondWithErrors,
event,
log,
}: OnErrorProps<
APIGatewayProxyEventV2,
APIGatewayProxyStructuredResultV2
>): void {
const body = respondWithErrors ? error.stack : '';
const errorResponse = this.getResponse({
event,
statusCode: 500,
body: body || '',
headers: {},
isBase64Encoded: false,
log,
});
delegatedResolver.succeed(errorResponse);
}
//#endregion
//#region Protected Methods
/**
* Get path from event with query strings
*
* @param event The event sent by serverless
*/
protected getPathFromEvent(event: APIGatewayProxyEventV2): string {
const stripBasePath = getDefaultIfUndefined(
this.options?.stripBasePath,
'',
);
const replaceRegex = new RegExp(`^${stripBasePath}`);
const path = event.rawPath.replace(replaceRegex, '');
const queryParams = event.rawQueryString;
return getPathWithQueryStringParams(path, queryParams || {});
}
//#endregion
}