swaf/src/components/FormHelperComponent.ts

50 lines
1.6 KiB
TypeScript
Raw Normal View History

import {Router} from "express";
2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent.js";
import FrontendToolsComponent from "./FrontendToolsComponent.js";
export default class FormHelperComponent extends ApplicationComponent {
public async init(): Promise<void> {
const globals = this.getApp().asOptional(FrontendToolsComponent)?.getGlobals();
if (globals) {
globals.set('validation', () => ({}));
globals.set('previousFormData', () => ({}));
}
}
public async initRoutes(router: Router): Promise<void> {
2020-04-22 15:52:17 +02:00
router.use((req, res, next) => {
let _validation: unknown | null;
2020-04-22 15:52:17 +02:00
res.locals.validation = () => {
if (!_validation) {
const v = req.flash('validation');
_validation = v.length > 0 ? v[0] : null;
}
return _validation;
};
2020-04-22 15:52:17 +02:00
let _previousFormData: unknown | null = null;
2020-04-22 15:52:17 +02:00
res.locals.previousFormData = () => {
if (!_previousFormData) {
const v = req.flash('previousFormData');
_previousFormData = v.length > 0 ? v[0] : null;
2020-04-22 15:52:17 +02:00
}
return _previousFormData;
};
next();
});
router.use((req, res, next) => {
if (['GET', 'POST'].find(m => m === req.method)) {
if (typeof req.body === 'object' && Object.keys(req.body).length > 0) {
2020-04-22 15:52:17 +02:00
req.flash('previousFormData', req.body);
}
}
next();
});
}
}