Skip to content

Commit 7ed90a7

Browse files
authored
[Docs] AS Integrations AWS Lambda 2.0.0 Update (#7329)
With the v2.0.0 release of `@as-integrations/aws-lambda`, the docs needed updates to reflect the new syntax and requirements. This PR also describes more of the added functionality in the 2.0 release. There was also an issue with the local event type that slipped through the cracks the first time around due to our runtime type-parsing. The local event we were using for testing was a `ProxyV1` event type, while the `httpApi` spun up by `serverless` was of the `ProxyV2` type. I normalized the example event and integration example to both be the new `V2` event type (as its now necessary to be explicit with v2.0.0). Fixes #7327 as `requestContext.http.method` was missing from the event as it was not required in `ProxyV1`, but is in `ProxyV2`
1 parent b35581d commit 7ed90a7

File tree

1 file changed

+221
-76
lines changed

1 file changed

+221
-76
lines changed

docs/source/deployment/lambda.mdx

Lines changed: 221 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -60,64 +60,20 @@ const server = new ApolloServer({
6060
});
6161
```
6262

63-
```js title="server.js"
64-
import { ApolloServer } from '@apollo/server';
65-
66-
// The GraphQL schema
67-
const typeDefs = `#graphql
68-
type Query {
69-
hello: String
70-
}
71-
`;
72-
73-
// A map of functions which return data for the schema.
74-
const resolvers = {
75-
Query: {
76-
hello: () => 'world',
77-
},
78-
};
79-
80-
// Set up Apollo Server
81-
const server = new ApolloServer({
82-
typeDefs,
83-
resolvers,
84-
});
85-
```
86-
8763
</MultiCodeBlock>
8864

89-
Now we can import the `startServerAndCreateLambdaHandler` function from [`@as-integrations/aws-lambda`](https://www.npmjs.com/package/@as-integrations/aws-lambda), passing in our `ApolloServer` instance:
65+
Now we can import the `startServerAndCreateLambdaHandler` function and `handlers` object from [`@as-integrations/aws-lambda`](https://www.npmjs.com/package/@as-integrations/aws-lambda), passing in our `ApolloServer` instance:
9066

9167
<MultiCodeBlock>
9268

9369
```ts title="src/server.ts"
9470
import { ApolloServer } from '@apollo/server';
95-
import { startServerAndCreateLambdaHandler } from '@as-integrations/aws-lambda'; //highlight-line
96-
97-
const typeDefs = `#graphql
98-
type Query {
99-
hello: String
100-
}
101-
`;
102-
103-
const resolvers = {
104-
Query: {
105-
hello: () => 'world',
106-
},
107-
};
108-
109-
const server = new ApolloServer({
110-
typeDefs,
111-
resolvers,
112-
});
113-
114-
// This final export is important!
115-
export const graphqlHandler = startServerAndCreateLambdaHandler(server); //highlight-line
116-
```
117-
118-
```js title="server.js"
119-
import { ApolloServer } from '@apollo/server';
120-
import { startServerAndCreateLambdaHandler } from '@as-integrations/aws-lambda'; //highlight-line
71+
// highlight-start
72+
import {
73+
startServerAndCreateLambdaHandler,
74+
handlers,
75+
} from '@as-integrations/aws-lambda';
76+
// highlight-end
12177

12278
const typeDefs = `#graphql
12379
type Query {
@@ -137,7 +93,13 @@ const server = new ApolloServer({
13793
});
13894

13995
// This final export is important!
140-
export const graphqlHandler = startServerAndCreateLambdaHandler(server); //highlight-line
96+
// highlight-start
97+
export const graphqlHandler = startServerAndCreateLambdaHandler(
98+
server,
99+
// We will be using the Proxy V2 handler
100+
handlers.createAPIGatewayProxyEventV2RequestHandler()
101+
);
102+
// highlight-end
141103
```
142104

143105
</MultiCodeBlock>
@@ -206,13 +168,19 @@ You can store a mock HTTP requests locally by creating a `query.json` file, like
206168
```json title="query.json"
207169
{
208170
"version": "2",
209-
"httpMethod": "POST",
210-
"path": "/",
211171
"headers": {
212-
"content-type": "application/json"
172+
"content-type": "application/json",
213173
},
214-
"requestContext": {},
174+
"isBase64Encoded": false,
215175
"rawQueryString": "",
176+
"requestContext": {
177+
"http": {
178+
"method": "POST",
179+
},
180+
// Other requestContext properties omitted for brevity
181+
},
182+
"rawPath": "/",
183+
"routeKey": "/",
216184
"body": "{\"operationName\": null, \"variables\": null, \"query\": \"{ hello }\"}"
217185
}
218186
```
@@ -284,42 +252,184 @@ If you ever want to remove the S3 bucket or Lambda functions that Serverless cre
284252
serverless remove
285253
```
286254

287-
## Customizing HTTP behavior
255+
## Middleware
288256

289-
The `@as-integrations/aws-lambda` package is compatible with the following event types `APIGatewayProxyEvent`, `APIGatewayProxyEventV2`, `ALBEvent`. This supports a wide range of services like API Gateway HTTP Proxy APIs, API Gateway REST Proxy APIs, Lambda Function URLs, and Application Load Balancers. However, it does not let you customize HTTP behavior directly or support other AWS products that invoke Lambda functions (e.g., S3 or DynamoDB).
257+
In order to implement event and result mutations, type-safe middleware can be passed to the `startServerAndCreateLambdaHandler` call. The API is as follows:
290258

291-
If you want to customize your HTTP behavior, you can couple Apollo Server's Express integration (i.e., [`expressMiddleware`](../api/express-middleware)) with the [`@vendia/serverless-express`](https://github.com/vendia/serverless-express) package. The `@vendia/serverless-express` library translates between Lambda events and Express requests. Despite their similar names, the Serverless CLI and the `@vendia/serverless-express` package are unrelated.
259+
<MultiCodeBlock>
292260

293-
You can update your Apollo Server setup to the following to have a fully functioning Lambda server that works in a variety of AWS features:
261+
```ts
294262
295-
<MultiCodeBlock>
263+
import { middleware, startServerAndCreateLambdaHandler, handlers } from "@as-integrations/aws-lambda";
264+
import { server } from "./server";
265+
266+
const requestHandler = handlers.createAPIGatewayProxyEventV2RequestHandler();
267+
268+
// Middleware is an async function whose type is based on your request handler. Middleware
269+
// can read and mutate the incoming event. Additionally, returning an async function from your
270+
// middleware allows you to read and mutate the result before it's sent.
271+
const middlewareFn: middleware.MiddlewareFn<typeof requestHandler> = async (event) => {
272+
// read or update the event here
273+
// optionally return a callback to access the result
274+
return async (result) => {
275+
// read or update the result here
276+
}
277+
}
278+
279+
startServerAndCreateLambdaHandler(server, requestHandler, {
280+
middleware: [middlewareFn],
281+
});
282+
```
283+
284+
</MultiCodeBlock>
285+
286+
One use case for middleware is cookie modification. The `APIGatewayProxyStructuredResultV2` type contains a property `cookies` which can be pushed to. This allows you to set multiple `set-cookie` headers in the response.
296287

297288
```ts
298-
const { ApolloServer } = require('@apollo/server');
299-
const { expressMiddleware } = require('@apollo/server/express4');
300-
const serverlessExpress = require('@vendia/serverless-express');
301-
const express = require('express');
302-
const { json } = require('body-parser');
303-
const cors = require('cors');
289+
import {
290+
startServerAndCreateLambdaHandler,
291+
middleware,
292+
handlers,
293+
} from '@as-integrations/aws-lambda';
294+
import { server } from './server';
295+
import { refreshCookie } from './cookies';
296+
297+
const requestHandler = handlers.createAPIGatewayProxyEventV2RequestHandler();
298+
299+
// Utilizing typeof
300+
const cookieMiddleware: middleware.MiddlewareFn<typeof requestHandler> = async (
301+
event,
302+
) => {
303+
// Access existing cookies and produce a refreshed one
304+
const cookie = refreshCookie(event.cookies);
305+
return async (result) => {
306+
// Ensure proper initialization of the cookies property on the result
307+
result.cookies = result.cookies ?? [];
308+
// Result is mutable so it can be updated here
309+
result.cookies.push(cookie);
310+
};
311+
};
304312
305-
const server = new ApolloServer({
306-
typeDefs: 'type Query { x: ID }',
307-
resolvers: { Query: { x: () => 'hi!' } },
313+
314+
export default startServerAndCreateLambdaHandler(server, requestHandler, {
315+
middleware: [
316+
cookieMiddleware,
317+
],
308318
});
319+
```
309320

310-
server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
321+
More use-cases and API information can be found in the [library's README](https://github.com/apollo-server-integrations/apollo-server-integration-aws-lambda#middleware).
311322

312-
const app = express();
313-
app.use(cors(), json(), expressMiddleware(server));
314323

315-
exports.graphqlHandler = serverlessExpress({ app });
324+
## Event extensions
325+
326+
In many cases, API Gateway events will have an authorizer in front of them that contains custom state that will be used for authorization during GraphQL resolution. All of the handlers that are packaged with the library contain a generic type which allows you to explicitly extend the base event type. By passing an event with authorization information, that event type will be used during the creation of `contextValue` and for `middleware`. Below is an example, and more information can be found in the [library's README](https://github.com/apollo-server-integrations/apollo-server-integration-aws-lambda/blob/main/README.md#event-extensions).
327+
328+
<MultiCodeBlock>
329+
330+
```ts
331+
import {
332+
startServerAndCreateLambdaHandler,
333+
middleware,
334+
handlers,
335+
} from '@as-integrations/aws-lambda';
336+
import type { APIGatewayProxyEventV2WithLambdaAuthorizer } from 'aws-lambda';
337+
import { server } from './server';
338+
339+
export default startServerAndCreateLambdaHandler(
340+
server,
341+
handlers.createAPIGatewayProxyEventV2RequestHandler<
342+
APIGatewayProxyEventV2WithLambdaAuthorizer<{
343+
myAuthorizerContext: string;
344+
}>
345+
>(),
346+
);
316347
```
317348

318349
</MultiCodeBlock>
319350

320-
The setup enables you to customize your HTTP behavior as needed.
351+
## Custom request handling
352+
353+
In order to support all event types from AWS Lambda (including custom ones), a request handler creation utility is exposed as `handlers.createHandler(eventParser, resultGenerator)`. This function returns a fully typed request handler that can be passed as the second argument to the `startServerAndCreateLambdaHandler` call. Below is an example and the exact API is documented in the [library's README](https://github.com/apollo-server-integrations/apollo-server-integration-aws-lambda/blob/main/README.md#custom-request-handlers).
354+
355+
<MultiCodeBlock>
356+
357+
```ts
358+
import {
359+
startServerAndCreateLambdaHandler,
360+
handlers,
361+
} from '@as-integrations/aws-lambda';
362+
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
363+
import { HeaderMap } from '@apollo/server';
364+
import { server } from './server';
365+
366+
type CustomInvokeEvent = {
367+
httpMethod: string;
368+
queryParams: string;
369+
headers: Record<string, string>;
370+
body: string;
371+
};
372+
373+
type CustomInvokeResult =
374+
| {
375+
success: true;
376+
body: string;
377+
}
378+
| {
379+
success: false;
380+
error: string;
381+
};
382+
383+
const requestHandler = handlers.createRequestHandler<
384+
CustomInvokeEvent,
385+
CustomInvokeResult
386+
>(
387+
{
388+
parseHttpMethod(event) {
389+
return event.httpMethod;
390+
},
391+
parseHeaders(event) {
392+
const headerMap = new HeaderMap();
393+
for (const [key, value] of Object.entries(event.headers)) {
394+
headerMap.set(key, value);
395+
}
396+
return headerMap;
397+
},
398+
parseQueryParams(event) {
399+
return event.queryParams;
400+
},
401+
parseBody(event) {
402+
return event.body;
403+
},
404+
},
405+
{
406+
success({ body }) {
407+
return {
408+
success: true,
409+
body: body.string,
410+
};
411+
},
412+
error(e) {
413+
if (e instanceof Error) {
414+
return {
415+
success: false,
416+
error: e.toString(),
417+
};
418+
}
419+
console.error('Unknown error type encountered!', e);
420+
throw e;
421+
},
422+
},
423+
);
424+
425+
export default startServerAndCreateLambdaHandler(server, requestHandler);
426+
```
427+
428+
</MultiCodeBlock>
429+
430+
321431

322-
## Using request information
432+
## Using event information
323433

324434
You can use the [`context` function](../data/context/#the-context-function) to get information about the current operation from the original Lambda data structures.
325435

@@ -394,3 +504,38 @@ exports.handler = serverlessExpress({ app });
394504
```
395505

396506
</MultiCodeBlock>
507+
508+
509+
## Customizing HTTP routing behavior
510+
511+
If you want to customize your HTTP routing behavior, you can couple Apollo Server's Express integration (i.e., [`expressMiddleware`](../api/express-middleware)) with the [`@vendia/serverless-express`](https://github.com/vendia/serverless-express) package. The `@vendia/serverless-express` library translates between Lambda events and Express requests. Despite their similar names, the Serverless CLI and the `@vendia/serverless-express` package are unrelated.
512+
513+
You can update your Apollo Server setup to the following to have a fully functioning Lambda server that works in a variety of AWS features:
514+
515+
<MultiCodeBlock>
516+
517+
```ts
518+
const { ApolloServer } = require('@apollo/server');
519+
const { expressMiddleware } = require('@apollo/server/express4');
520+
const serverlessExpress = require('@vendia/serverless-express');
521+
const express = require('express');
522+
const { json } = require('body-parser');
523+
const cors = require('cors');
524+
525+
const server = new ApolloServer({
526+
typeDefs: 'type Query { x: ID }',
527+
resolvers: { Query: { x: () => 'hi!' } },
528+
});
529+
530+
server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
531+
532+
const app = express();
533+
app.use(cors(), json(), expressMiddleware(server));
534+
535+
exports.graphqlHandler = serverlessExpress({ app });
536+
```
537+
538+
</MultiCodeBlock>
539+
540+
The setup enables you to customize your HTTP behavior as needed.
541+

0 commit comments

Comments
 (0)