import * as plugins from './rendertron.plugins.js'; import { db } from './rendertron.db.js'; import { PrerenderManager } from './rendertron.classes.prerendermanager.js'; import { logger } from './rendertron.logging.js'; /** * allows for prerendering results */ @plugins.smartdata.Collection(() => { return db; }) export class PrerenderResult extends plugins.smartdata.SmartDataDbDoc< PrerenderResult, PrerenderResult > { // STATIC public static async getPrerenderResultForUrl( managerArg: PrerenderManager, urlArg: string, forceNew: boolean = false ): Promise { let prerenderResult = await PrerenderResult.getInstance({ url: urlArg, }); if (prerenderResult) { const prerenderResultDate = new plugins.smarttime.ExtendedDate(prerenderResult.timestamp); if ( prerenderResultDate.lessTimePassedToNow({ hours: 12, }) ) { logger.log('info', `Serving prerendered result for ${prerenderResult.url}`); return prerenderResult; } else { logger.log( 'info', `Outdated Prerender Result: Requesting newer result for ${prerenderResult.url}` ); prerenderResult.needsRerendering = true; } } if (!prerenderResult || prerenderResult.needsRerendering) { const newPrerenderResult: PrerenderResult = await PrerenderResult.createPrerenderResultForUrl( managerArg, urlArg ).catch((err) => { return prerenderResult; }); prerenderResult = newPrerenderResult; } return prerenderResult; } private static async createPrerenderResultForUrl( managerArg: PrerenderManager, urlArg: string ): Promise { const renderedResultPromise = managerArg.smartssrInstance.renderPage(urlArg).catch(() => { const errorMessage = `failed to render ${urlArg}`; logger.log('error', errorMessage); }); let prerenderResult = await PrerenderResult.getInstance({ url: urlArg, }); prerenderResult = prerenderResult || new PrerenderResult(); prerenderResult.url = urlArg; prerenderResult.timestamp = Date.now(); prerenderResult.renderResultString = (await renderedResultPromise) || 'error'; prerenderResult.needsRerendering = false; await prerenderResult.save(); return prerenderResult; } // INSTANCE @plugins.smartdata.unI() url: string; @plugins.smartdata.svDb() renderResultString: string; @plugins.smartdata.svDb() timestamp: number; @plugins.smartdata.svDb() needsRerendering: boolean = false; constructor() { super(); } }