Skip to content

Commit b9eba7d

Browse files
committed
chore: fix custom err message fallback as suggested in review
1 parent 53da28d commit b9eba7d

File tree

1 file changed

+19
-6
lines changed
  • packages/large-response-middleware/src

1 file changed

+19
-6
lines changed

packages/large-response-middleware/src/index.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export type FileUploadContext = {
2626
fileName: string;
2727
};
2828

29+
export type CustomErrorMessage = string | ((event: APIGatewayProxyEventV2) => string);
30+
2931
export const withLargeResponseHandler = ({
3032
thresholdWarn,
3133
thresholdError,
@@ -38,7 +40,7 @@ export const withLargeResponseHandler = ({
3840
thresholdError: number;
3941
sizeLimitInMB: number;
4042
outputBucket: string;
41-
customErrorMessage?: string | ((event: APIGatewayProxyEventV2) => string);
43+
customErrorMessage?: CustomErrorMessage;
4244
groupRequestsBy?: (event: APIGatewayProxyEventV2) => string;
4345
}) => {
4446
return {
@@ -105,12 +107,8 @@ export const withLargeResponseHandler = ({
105107
});
106108
response.isBase64Encoded = false;
107109
response.statusCode = 413;
108-
const responseErrorMessage = customErrorMessage ?? LARGE_RESPONSE_USER_INFO;
109-
110110
response.body = JSON.stringify({
111-
message: typeof responseErrorMessage === 'string'
112-
? responseErrorMessage
113-
: customErrorMessage?.(event) || customErrorMessage,
111+
message: getCustomErrorMessage(customErrorMessage, event),
114112
});
115113
}
116114
} else if (contentLengthMB > thresholdWarnInMB) {
@@ -200,3 +198,18 @@ function getFormattedDate() {
200198

201199
return date.toISOString().split('T')[0];
202200
}
201+
202+
function getCustomErrorMessage(customErrorMessage: CustomErrorMessage | undefined, event: APIGatewayProxyEventV2) {
203+
let message;
204+
205+
if (typeof customErrorMessage === 'string') {
206+
message = customErrorMessage;
207+
} else if (typeof customErrorMessage === 'function') {
208+
message = customErrorMessage(event);
209+
} else {
210+
// If customErrorMessage is neither a string nor a function or is not defined, use a fallback.
211+
message = customErrorMessage ?? LARGE_RESPONSE_USER_INFO;
212+
}
213+
214+
return message;
215+
}

0 commit comments

Comments
 (0)