import { middlewareCreator } from '../../utils/index.js'; import type { HTMLGenerator, SendFile } from '../../services/index.js'; import type { AsyncExpressMiddleware, Response, NextFunction, } from '../../types/index.js'; /** * The options to customize the behavior of the middleware. * * @group Middlewares/ShowHTML */ export type ShowHTMLOptions = { /** * The name of the file the middleware will serve. If the {@link HTMLGenerator} service * is available, it will be overridden by the service. * * @default 'index.html' */ file: string; }; /** * The options to construct a {@link ShowHTML}. * * @group Middlewares/ShowHTML */ export type ShowHTMLConstructorOptions = Partial & { /** * A dictionary with the dependencies to inject. */ inject: { sendFile: SendFile; /** * A function to get a possible {@link HTMLGenerator}. This is injected as a "getter" * to not interrupt the DIC "lifecycle": middlewares are initialized right when the * app starts, and injecting a reference would force the service to be initialized * too, even if a request is not being made. */ getHTMLGenerator?: () => HTMLGenerator | undefined; }; }; /** * The options for the middleware creator that will mount an instance of {@link ShowHTML}. * * @group Middlewares/ShowHTML */ export type ShowHTMLMiddlewareOptions = Partial & { /** * The name of an {@link HTMLGenerator} service already available in the application. * * @default 'htmlGenerator' */ htmlGeneratorServiceName?: string; }; /** * A very simple middleware service to send an HTML on a server response. The special * _'feature'_ of this service is that it can be hooked up to an {@link HTMLGenerator} * service and it will automatically server the file generated by it. * * @group Middleware Classes * @group Middlewares/ShowHTML * @prettierignore */ export class ShowHTML { /** * The service that serves a file. */ protected readonly _sendFile: SendFile; /** * A function to get a possible {@link HTMLGenerator}. This is injected as a "getter" * to not interrupt the DIC "lifecycle": middlewares are initialized right when the * app starts, and injecting a reference would force the service to be initialized * too, even if a request is not being made. */ protected readonly _getHTMLGenerator: () => HTMLGenerator | undefined; /** * The customization options for the middleware. */ protected _options: ShowHTMLOptions; /** * Whether or not the file is ready to be served. In case the middleware uses an * {@link HTMLGenerator} service, the file needs to be generated before being available, * and that's why this flag exists. */ protected _fileReady: boolean = false; /** * @param options The options to construct the class. */ constructor({ inject, ...options }: ShowHTMLConstructorOptions) { this._sendFile = inject.sendFile; this._getHTMLGenerator = inject.getHTMLGenerator || (() => undefined); this._options = { file: 'index.html', ...options, }; } /** * Generates the middleware that serves the HTML file. */ getMiddleware(): AsyncExpressMiddleware { return async (_, res, next) => { // If the file is ready to be served, serve it. if (this._fileReady) { this._sendResponse(res, next); return; } const htmlGenerator = this._getHTMLGenerator(); // If there's no generator, switch the flag and just serve the file. if (!htmlGenerator) { this._fileReady = true; this._sendResponse(res, next); return; } try { // Wait for the HTML to be generated. await htmlGenerator.whenReady(); // Update the local option. this._options.file = htmlGenerator.options.file; // Switch the flag and serve the file. this._fileReady = true; this._sendResponse(res, next); } catch (error) { next(error); } }; } /** * The customization options. */ get options(): Readonly { return { ...this._options }; } /** * Serves the HTML file to the response. * * @param res The response object generated by the application. * @param next The function to call the next middleware. */ protected _sendResponse(res: Response, next: NextFunction): void { res.setHeader('Content-Type', 'text/html'); this._sendFile({ res, next, filepath: this._options.file, }); } } /** * Creates the middleware that serves an HTML file in the response. * * @group Middlewares * @group Middlewares/ShowHTML */ export const showHTMLMiddleware = middlewareCreator( (options: ShowHTMLMiddlewareOptions = {}) => (app) => { const { htmlGeneratorServiceName = 'htmlGenerator', ...rest } = options; return new ShowHTML({ inject: { sendFile: app.get('sendFile'), getHTMLGenerator: () => app.try(htmlGeneratorServiceName), }, ...rest, }).getMiddleware(); }, );