Skip to content

Commit

Permalink
Merge pull request #1 from thetutlage/feature/lazily-stream
Browse files Browse the repository at this point in the history
Lazily stream
  • Loading branch information
bitkidd authored Oct 25, 2023
2 parents e02209a + 54b690d commit 718a914
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/JSX.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@ export default class JSX {
component: (props: T) => JSX.Element,
props?: T
) {
const ctx = this.#context
const shouldRenderFull =
!ctx?.response || (ctx?.response && ctx?.request && isBot(ctx?.request.header('user-agent')))
const shouldRenderStreaming =
ctx?.response && ctx?.request && !isBot(ctx?.request.header('user-agent'))
const ctx = this.#context!

ctx.response['writeJSX'] = async () => {
const shouldRenderFull =
!ctx?.response ||
(ctx?.response && ctx?.request && isBot(ctx?.request.header('user-agent')))
const shouldRenderStreaming =
ctx?.response && ctx?.request && !isBot(ctx?.request.header('user-agent'))

const response = new Promise(async (resolve, reject) => {
const Component = component
const sharedValuesPrepared = await this.processShared()
let streamHasErrors = false
Expand All @@ -73,7 +75,8 @@ export default class JSX {
pipe(writable)

writable.on('finish', () => {
resolve(content)
ctx.response.flushHeaders()
ctx.response.response.end(content)
})
}
},
Expand All @@ -94,18 +97,22 @@ export default class JSX {
// But flash messages work as expected
ctx.response.header('content-type', 'text/html')
ctx.response.status(streamHasErrors ? 500 : 200)
ctx.response.flushHeaders()
pipe(ctx.response.response)
resolve(ctx.response)
}
},
onError(error) {
streamHasErrors = true
reject(error)
ctx.response.flushHeaders()
ctx.response.response.end(error)
},
}
)
})
}

return response
ctx!.response['writerMethod'] = 'writeJSX'
ctx!.response.hasLazyBody = true
ctx!.response.lazyBody = [component, props]
return ctx!.response
}
}

0 comments on commit 718a914

Please sign in to comment.