Skip to content

Commit

Permalink
Move the htmlToPdf() function to a separate module
Browse files Browse the repository at this point in the history
  • Loading branch information
cedx committed Oct 22, 2024
1 parent e3d7da2 commit 63348cf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
11 changes: 2 additions & 9 deletions src/koa_eta/Eta.hx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import js.koa.Context;
import js.lib.Object;
import js.lib.Promise;
import js.node.Buffer;
import js.puppeteer.LifeCycleEvent;
import js.puppeteer.Page.PdfOptions;
import js.puppeteer.Puppeteer;
import js.puppeteer.Puppeteer.LaunchOptions;

/** Attaches a view renderer to the context of the specified `application`. **/
@:expose("eta")
Expand All @@ -35,7 +34,7 @@ function eta(application: Application, ?rendererOptions: RendererOptions): Eta {
final viewData = Object.assign({}, context.state, data ?? {});

final promise = (renderingOptions?.async ?? false) ? Promise.resolve(renderer.render(view, viewData)) : renderer.renderAsync(view, viewData);
return promise.then(html -> htmlToPdf(html, {browser: rendererOptions?.browser, pdf: renderingOptions})).then(pdf -> {
return promise.then(html -> Puppeteer.htmlToPdf(html, {browser: rendererOptions?.browser, pdf: renderingOptions})).then(pdf -> {
if (renderingOptions?.writeResponse ?? true) { context.body = pdf; context.type = "pdf"; }
pdf;
});
Expand All @@ -49,12 +48,6 @@ function eta(application: Application, ?rendererOptions: RendererOptions): Eta {
return renderer;
}

/** Converts the specified HTML code into a PDF document. **/
private function htmlToPdf(html: String, ?options: {?browser: LaunchOptions, ?pdf: PdfOptions}): Promise<Buffer>
return Puppeteer.launch(options?.browser ?? Lib.undefined).then(browser -> browser.newPage()
.then(page -> page.setContent(html, {waitUntil: LifeCycleEvent.Load}).then(_ -> page.pdf(options?.pdf ?? Lib.undefined)))
.then(pdf -> browser.close().then(_ -> Buffer.from(pdf))));

/** Defines the renderer options. **/
typedef RendererOptions = Config & {

Expand Down
14 changes: 14 additions & 0 deletions src/koa_eta/Puppeteer.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package koa_eta;

import js.Lib;
import js.lib.Promise;
import js.node.Buffer;
import js.puppeteer.LifeCycleEvent;
import js.puppeteer.Page.PdfOptions;
import js.puppeteer.Puppeteer;

/** Converts the specified HTML code into a PDF document. **/
function htmlToPdf(html: String, ?options: {?browser: LaunchOptions, ?pdf: PdfOptions}): Promise<Buffer>
return Puppeteer.launch(options?.browser ?? Lib.undefined).then(browser -> browser.newPage()
.then(page -> page.setContent(html, {waitUntil: LifeCycleEvent.Load}).then(_ -> page.pdf(options?.pdf ?? Lib.undefined)))
.then(pdf -> browser.close().then(_ -> Buffer.from(pdf))));

0 comments on commit 63348cf

Please sign in to comment.