swaf/src/components/core/LazyLocalsCoreComponent.ts

31 lines
1.1 KiB
TypeScript

import {Router} from "express";
import ApplicationComponent from "../../ApplicationComponent.js";
export default class LazyLocalsCoreComponent extends ApplicationComponent {
public async initRoutes(router: Router): Promise<void> {
router.use((req, res, next) => {
res.locals._lazyLocals = {};
res.setLazyLocal = (key: string, valueProvider: () => unknown) => {
res.locals._lazyLocals[key] = valueProvider;
};
next();
});
}
public setupLazyLocals(localsObject: Record<string, unknown>): void {
const lazyLocals = localsObject._lazyLocals as Record<string, () => unknown> | undefined;
if (!lazyLocals) throw new Error('No _lazyLocals field found on referenced object.');
for (const lazyLocal of Object.keys(lazyLocals)) {
Object.defineProperty(localsObject, lazyLocal, {
get: function () {
delete this[lazyLocal];
return this[lazyLocal] = lazyLocals[lazyLocal]();
},
configurable: true,
});
}
}
}