rsnext/packages/next/server/render-result.ts

67 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { ServerResponse } from 'http'
2021-09-04 16:41:06 +02:00
export default class RenderResult {
_result: string | ReadableStream<Uint8Array>
2021-09-04 16:41:06 +02:00
constructor(response: string | ReadableStream<Uint8Array>) {
this._result = response
2021-09-04 16:41:06 +02:00
}
toUnchunkedString(): string {
if (typeof this._result !== 'string') {
throw new Error(
'invariant: dynamic responses cannot be unchunked. This is a bug in Next.js'
)
2021-09-04 16:41:06 +02:00
}
return this._result
2021-09-04 16:41:06 +02:00
}
pipe(res: ServerResponse): Promise<void> {
if (typeof this._result === 'string') {
throw new Error(
'invariant: static responses cannot be piped. This is a bug in Next.js'
)
2021-09-04 16:41:06 +02:00
}
const response = this._result
const flush =
typeof (res as any).flush === 'function'
? () => (res as any).flush()
: () => {}
return (async () => {
const reader = response.getReader()
let fatalError = false
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
res.end()
return
}
fatalError = true
res.write(value)
flush()
}
} catch (err) {
if (fatalError) {
res.destroy(err as any)
}
throw err
}
})()
2021-09-04 16:41:06 +02:00
}
isDynamic(): boolean {
return typeof this._result !== 'string'
2021-09-04 16:41:06 +02:00
}
static fromStatic(value: string): RenderResult {
return new RenderResult(value)
2021-09-04 16:41:06 +02:00
}
static empty = RenderResult.fromStatic('')
}