Skip to content

Commit 0e96e58

Browse files
committed
enable response streaming
1 parent 201040f commit 0e96e58

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

cloudformation/main.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ Resources:
221221
Type: AWS::Lambda::Url
222222
Properties:
223223
AuthType: NONE
224-
InvokeMode: BUFFERED
224+
InvokeMode: RESPONSE_STREAM
225225
TargetFunctionArn: !GetAtt AppApiLambdaFunction.Arn
226226

227227

src/api/lambda.ts

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@ import init from "./index.js";
44
import warmer from "lambda-warmer";
55
import { type APIGatewayEvent, type Context } from "aws-lambda";
66
import { InternalServerError, ValidationError } from "common/errors/index.js";
7+
import { promisify } from "node:util";
8+
import stream from "node:stream";
79

10+
const pipeline = promisify(stream.pipeline);
811
const app = await init();
912
const realHandler = awsLambdaFastify(app, {
1013
decorateRequest: false,
1114
serializeLambdaArguments: true,
1215
callbackWaitsForEmptyEventLoop: false,
16+
payloadAsStream: true,
1317
});
1418
const handler = async (event: APIGatewayEvent, context: Context) => {
1519
// if a warming event
@@ -36,21 +40,13 @@ const handler = async (event: APIGatewayEvent, context: Context) => {
3640
};
3741
}
3842
}
39-
// else proceed with handler logic
40-
return await realHandler(event, context).catch((e) => {
41-
console.error(e);
42-
const newError = new InternalServerError({
43-
message: "Failed to initialize application.",
44-
});
45-
const json = JSON.stringify(newError.toJson());
46-
return {
47-
statusCode: newError.httpStatusCode,
48-
body: json,
49-
headers: {
50-
"Content-Type": "application/json",
51-
},
52-
isBase64Encoded: false,
53-
};
43+
awslambda.streamifyResponse(async (event, responseStream, context) => {
44+
const { meta, stream } = await realHandler(event, context);
45+
responseStream = awslambda.HttpResponseStream.from(
46+
responseStream,
47+
meta as unknown as Record<string, unknown>,
48+
); // weird typing bug
49+
await pipeline(stream, responseStream);
5450
});
5551
};
5652

0 commit comments

Comments
 (0)