feat: stream rendering, closed #361 fixes #360

This commit is contained in:
Harttle
2021-09-30 22:15:09 +08:00
committed by Jun Yang
parent abaf4af465
commit 9012133e07
18 changed files with 147 additions and 53 deletions
+15 -4
View File
@@ -1,23 +1,34 @@
import { RenderError } from '../util/error'
import { Context } from '../context/context'
import { Template } from '../template/template'
import { Emitter } from './emitter'
import { Emitter } from '../emitters/emitter'
import { SimpleEmitter } from '../emitters/simple-emitter'
import { StreamedEmitter } from '../emitters/streamed-emitter'
import { toThenable } from '../util/async'
import { KeepingTypeEmitter } from '../emitters/keeping-type-emitter'
export class Render {
public renderTemplatesToNodeStream (templates: Template[], ctx: Context): NodeJS.ReadableStream {
const emitter = new StreamedEmitter()
toThenable(this.renderTemplates(templates, ctx, emitter))
return emitter.stream
}
public * renderTemplates (templates: Template[], ctx: Context, emitter?: Emitter): IterableIterator<any> {
if (!emitter) {
emitter = new Emitter(ctx.opts.keepOutputType)
emitter = ctx.opts.keepOutputType ? new KeepingTypeEmitter() : new SimpleEmitter()
}
for (const tpl of templates) {
try {
// if tpl.render supports emitter, it'll return empty `html`
const html = yield tpl.render(ctx, emitter)
// if not, it'll return an `html`, write to the emitter for it
html && emitter.write(html)
if (emitter.break || emitter.continue) break
if (emitter['break'] || emitter['continue']) break
} catch (e) {
const err = RenderError.is(e) ? e : new RenderError(e, tpl)
throw err
}
}
return emitter.html
return emitter.end()
}
}