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

47 lines
1.1 KiB
TypeScript
Raw Normal View History

import type { ServerResponse } from 'http'
import type { Writable } from 'stream'
export type NodeWritablePiper = (
res: Writable,
next: (err?: Error) => void
) => void
2021-09-04 16:41:06 +02:00
export default class RenderResult {
_result: string | NodeWritablePiper
2021-09-04 16:41:06 +02:00
constructor(response: string | NodeWritablePiper) {
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
return new Promise((resolve, reject) => {
response(res, (err) => (err ? reject(err) : resolve()))
})
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('')
}