Introduce async local storage for request access, more view globals, and improved welcome view
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2021-11-27 10:30:49 -06:00
parent b5eb407b55
commit 463076d182
8 changed files with 148 additions and 32 deletions

View File

@@ -1,8 +1,10 @@
import {AppClass} from '../lifecycle/AppClass'
import {Config} from '../service/Config'
import {Container} from '../di'
import {ErrorWithContext, UniversalPath} from '../util'
import {ErrorWithContext, hasOwnProperty, Maybe, UniversalPath} from '../util'
import {Routing} from '../service/Routing'
import {RequestLocalStorage} from '../http/RequestLocalStorage'
import {Request} from '../http/lifecycle/Request'
/**
* Abstract base class for rendering views via different view engines.
@@ -12,14 +14,19 @@ export abstract class ViewEngine extends AppClass {
protected readonly routing: Routing
protected readonly request: RequestLocalStorage
protected readonly debug: boolean
protected readonly namespaces: {[key: string]: UniversalPath} = {}
protected readonly globals: {[key: string]: (req: Maybe<Request>) => any} = {}
constructor() {
super()
this.config = Container.getContainer().make(Config)
this.routing = Container.getContainer().make(Routing)
this.request = Container.getContainer().make(RequestLocalStorage)
this.debug = (this.config.get('server.mode', 'production') === 'development'
|| this.config.get('server.debug', false))
}
@@ -56,7 +63,7 @@ export abstract class ViewEngine extends AppClass {
* @protected
*/
protected getGlobals(): {[key: string]: any} {
return {
const globals: {[key: string]: any} = {
app: this.app(),
config: (key: string, fallback?: any) => this.config.get(key, fallback),
asset: (...parts: string[]) => this.routing.getAssetPath(...parts).toRemote,
@@ -65,6 +72,31 @@ export abstract class ViewEngine extends AppClass {
route: (...parts: string[]) => this.routing.getAppUrl().concat(...parts).toRemote,
hasRoute: (name: string) => this.routing.hasNamedRoute(name),
}
const req = this.request.get()
if ( req ) {
globals.request = () => req
}
for ( const key in this.globals ) {
if ( !hasOwnProperty(this.globals, key) ) {
continue
}
globals[key] = this.globals[key](req)
}
return globals
}
/**
* Register a new factory that produces a global available in the templates by default.
* @param name
* @param factory
*/
public registerGlobalFactory(name: string, factory: (req: Maybe<Request>) => any): this {
this.globals[name] = factory
return this
}
/**