refactor: Align EJS engine with Handlebars.

This commit is contained in:
Ruben Verborgh
2021-07-20 19:39:28 +02:00
committed by Joachim Van Herwegen
parent 19624dc729
commit 9628fe98b8
40 changed files with 215 additions and 266 deletions

View File

@@ -1,26 +0,0 @@
import { renderFile } from 'ejs';
import { joinFilePath } from '../../util/PathUtil';
import type { HttpResponse } from '../HttpResponse';
import { RenderHandler } from './RenderHandler';
/**
* A Render Handler that uses EJS templates to render a response.
*/
export class RenderEjsHandler<T> extends RenderHandler<T> {
private readonly templatePath: string;
private readonly templateFile: string;
public constructor(templatePath: string, templateFile: string) {
super();
this.templatePath = templatePath;
this.templateFile = templateFile;
}
public async handle(input: { response: HttpResponse; props: T }): Promise<void> {
const { props, response } = input;
const renderedHtml = await renderFile(joinFilePath(this.templatePath, this.templateFile), props || {});
// eslint-disable-next-line @typescript-eslint/naming-convention
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(renderedHtml);
}
}

View File

@@ -1,9 +0,0 @@
import { AsyncHandler } from '../../util/handlers/AsyncHandler';
import type { HttpResponse } from '../HttpResponse';
export interface RenderHandlerInput {}
/**
* Renders a result with the given props and sends it to the HttpResponse.
*/
export abstract class RenderHandler<T> extends AsyncHandler<{ response: HttpResponse; props: T }> {}

View File

@@ -0,0 +1,26 @@
import { AsyncHandler } from '../../util/handlers/AsyncHandler';
import type { TemplateEngine } from '../../util/templates/TemplateEngine';
import type { HttpResponse } from '../HttpResponse';
import Dict = NodeJS.Dict;
/**
* A Render Handler that uses a template engine to render a response.
*/
export class TemplateHandler<T extends Dict<any> = Dict<any>>
extends AsyncHandler<{ response: HttpResponse; contents: T }> {
private readonly templateEngine: TemplateEngine;
private readonly contentType: string;
public constructor(templateEngine: TemplateEngine, contentType = 'text/html') {
super();
this.templateEngine = templateEngine;
this.contentType = contentType;
}
public async handle({ response, contents }: { response: HttpResponse; contents: T }): Promise<void> {
const rendered = await this.templateEngine.render(contents);
// eslint-disable-next-line @typescript-eslint/naming-convention
response.writeHead(200, { 'Content-Type': this.contentType });
response.end(rendered);
}
}