diff --git a/src/frontend/SvelteViewEngine.ts b/src/frontend/SvelteViewEngine.ts index d02322a..246f98d 100644 --- a/src/frontend/SvelteViewEngine.ts +++ b/src/frontend/SvelteViewEngine.ts @@ -72,9 +72,6 @@ export default class SvelteViewEngine extends ViewEngine { css, ] = view.split(SvelteViewEngine.getPreCompileSeparator(canonicalViewName)); - // Props (locals) - locals = Object.assign(this.getGlobals(), locals); - const localMap: Record = {}; backendLines.split('\n').forEach(line => { const key = line.substring(1, line.indexOf(',') >= 0 ? line.indexOf(',') - 1 : line.length - 1); @@ -140,16 +137,6 @@ export default class SvelteViewEngine extends ViewEngine { await this.stopRollup(); } - /** - * TODO: add a way to add globals from anywhere - */ - private getGlobals(): Record { - return { - route: (name: string) => 'unimplemented route ' + name, - direct: 'access', - }; - } - public async preCompile(canonicalName: string, alsoCompileDependents: boolean): Promise { const file = await this.resolveFileFromCanonicalName(canonicalName); const intermediateFile = path.join(this.getBuildDir(), canonicalName); @@ -345,15 +332,15 @@ export default class SvelteViewEngine extends ViewEngine { cssOutputFilename: file + '.css', }); - const locals = this.getGlobals(); + const globals = ViewEngine.getGlobals(); delete require.cache[path.resolve(file)]; return requireFromString(svelteSsr.js.code, file).default.render({ swaf: (key: string, args?: unknown[]) => { - if (!args) return locals[key]; + if (!args) return globals[key]; - const f = locals[key]; + const f = globals[key]; if (typeof f !== 'function') throw new Error(key + ' is not a function.'); - return f.call(locals, ...args); + return f.call(globals, ...args); }, }); } diff --git a/src/frontend/ViewEngine.ts b/src/frontend/ViewEngine.ts index bae684c..9e2ddc6 100644 --- a/src/frontend/ViewEngine.ts +++ b/src/frontend/ViewEngine.ts @@ -3,8 +3,20 @@ import fs from "fs"; import chokidar, {FSWatcher} from "chokidar"; import {logger} from "../Logger"; import {afs, readdirRecursively} from "../Utils"; +import {Express} from "express"; export default abstract class ViewEngine { + private static readonly globals: Record = {}; + + public static getGlobals(): Record { + return this.globals; + } + + public static setGlobal(key: string, value: unknown): void { + this.globals[key] = value; + } + + protected readonly viewPaths: string[]; private watcher?: FSWatcher; @@ -42,6 +54,16 @@ export default abstract class ViewEngine { callback: (err: Error | null, output?: string) => void, ): Promise; + public setup(app: Express): void { + app.engine(this.getExtension(), (path, options, callback) => { + // Props (locals) + const locals = Object.assign(ViewEngine.getGlobals(), options); + + this.render(path, locals, callback) + .catch(err => callback(err)); + }); + } + public getViewPaths(): string[] { return this.viewPaths; }