流式传输
使用可读流进行响应。
提供 ReadableStream
实例作为模拟响应主体以启动数据流。
¥Provide a ReadableStream
instance as the mocked response body to initate a stream of data.
基本示例
¥Basic example
在这个基本示例中,我们将以三个块的形式将字符串 BrandNewWorld
流式传输到客户端。
¥In this basic example we will stream a string BrandNewWorld
to the client in three chunks.
import { http, HttpResponse } from 'msw'
const encoder = new TextEncoder()
export const handlers = [
http.get('/video', () => {
const stream = new ReadableStream({
start(controller) {
// Encode the string chunks using "TextEncoder".
controller.enqueue(encoder.encode('Brand'))
controller.enqueue(encoder.encode('New'))
controller.enqueue(encoder.encode('World'))
controller.close()
},
})
// Send the mocked response immediately.
return new HttpResponse(stream, {
headers: {
'Content-Type': 'text/plain',
},
})
}),
]
请注意,客户端还必须将响应作为流读取才能查看传入的块。使用
response.text()
或response.json()
等方法读取响应将等待流完成,然后再返回响应主体。¥Note that the client must also read the response as a stream to see the incoming chunks. Reading the response with methods like
response.text()
orresponse.json()
will await the stream completion before returning the response body.
转换流示例
¥Transform stream example
使用 TransformStream
API,我们可以描述更复杂的流式传输场景。
¥Using the TransformStream
API, we can describe more complex streaming scenarios.
在下面的例子中,我们将描述一个视频端点,它从原始视频资源建立可读流,并通过自定义转换流将其传输,在每个视频流块之间插入延迟。当我们希望测试我们的 UI 如何处理流期间的延迟时,这很方便。
¥In the example below, we will describe a video endpoint that establishes a readable stream from the original video resource and pipes it through a custom transform stream that inserts latency between each video stream chunk. This is handy when we wish to test how our UI handles latency during streams.
import { http, HttpResponse, delay } from 'msw'
export const handlers = [
http.get('/video', async () => {
// Request the original video stream.
const videoResponse = await fetch(
'https://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4'
)
const videoStream = videoResponse.body
// Implement a custom transform stream that
// takes any stream and inserts a random latency
// between its chunks.
const latencyStream = new TransformStream({
start() {},
async transform(chunk, controller) {
await delay()
controller.enqueue(chunk)
},
})
return new HttpResponse(
// Respond with the original video stream
// piped through the latency transform stream.
videoStream.pipeThrough(latencyStream),
// Inherit the rest of the original video
// response data, like "headers".
videoResponse
)
}),
]