Move request context locals definition to FrontendToolsComponent

This commit is contained in:
Alice Gaudon 2021-04-28 14:10:29 +02:00
parent c93ea7691e
commit a7f421d2f8
2 changed files with 10 additions and 23 deletions

View File

@ -46,6 +46,16 @@ export default class FrontendToolsComponent extends ApplicationComponent {
next(); next();
}); });
// Add request context locals
router.use((req, res, next) => {
res.locals.url = req.url;
res.locals.params = req.params;
res.locals.query = req.query;
res.locals.body = req.body;
next();
});
} }
public async preCompileViews(watch: boolean): Promise<void> { public async preCompileViews(watch: boolean): Promise<void> {

View File

@ -56,31 +56,8 @@ export default class NunjucksComponent extends ApplicationComponent {
}); });
} }
public async init(_router: Router): Promise<void> {
this.use(NunjucksMiddleware);
}
public getEnvironment(): Environment { public getEnvironment(): Environment {
if (!this.environment) throw new Error('Environment not initialized.'); if (!this.environment) throw new Error('Environment not initialized.');
return this.environment; return this.environment;
} }
} }
export class NunjucksMiddleware extends Middleware {
private env?: Environment;
protected async handle(req: Request, res: Response, next: NextFunction): Promise<void> {
this.env = this.app.as(NunjucksComponent).getEnvironment();
res.locals.url = req.url;
res.locals.params = req.params;
res.locals.query = req.query;
res.locals.body = req.body;
next();
}
public getEnvironment(): Environment {
if (!this.env) throw new Error('Environment not initialized.');
return this.env;
}
}