Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support Web API ReadableStream when streamifyResponse:true #1280

Merged
merged 2 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions packages/core/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -932,11 +932,35 @@ test('Should return with streamifyResponse:true using empty body string and prel
equal(content(), input)
})

test('Should return with streamifyResponse:true using ReadableStream', async (t) => {
// https://nodejs.org/api/stream.html#readable-streams
test('Should return with streamifyResponse:true using Node Readable stream', async (t) => {
const input = 'x'.repeat(1024 * 1024)
const handler = middy(
async (event, context, { signal }) => {
return createReadableStream(input)
return createReadableStream(input) // returns Readable stream
},
{
streamifyResponse: true
}
)

const { responseStream, chunkResponse } = createResponseStreamMockAndCapture()
const response = await handler(event, responseStream, context)
equal(response, undefined)
equal(chunkResponse(), input)
})

// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
test('Should return with streamifyResponse:true using Web API ReadableStream', async (t) => {
const input = 'x'.repeat(1024 * 1024)
const handler = middy(
async (event, context, { signal }) => {
return new ReadableStream({
async start (controller) {
controller.enqueue(input)
controller.close()
}
})
},
{
streamifyResponse: true
Expand Down
3 changes: 2 additions & 1 deletion packages/core/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* global awslambda */
import { Readable } from 'node:stream'
import { ReadableStream } from 'node:stream/web'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oooh, it's using web streams. That's why.

import { pipeline } from 'node:stream/promises'
import { setTimeout } from 'node:timers'

Expand Down Expand Up @@ -64,7 +65,7 @@ const middy = (lambdaHandler = defaultLambdaHandler, plugin = {}) => {
}

let handlerStream
if (handlerBody._readableState) {
if (handlerBody._readableState || handlerBody instanceof ReadableStream) {
handlerStream = handlerBody
} else if (typeof handlerBody === 'string') {
// #1189
Expand Down
Loading