swaf/src/components/FormHelperComponent.ts

42 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import {Router} from "express";
2020-04-22 15:52:17 +02:00
export default class FormHelperComponent extends ApplicationComponent {
public async init(router: Router): Promise<void> {
2020-04-22 15:52:17 +02:00
router.use((req, res, next) => {
if (!req.session) {
throw new Error('Session is unavailable.');
}
let _validation: any = null;
res.locals.validation = () => {
if (!_validation) {
const v = req.flash('validation');
_validation = v.length > 0 ? v[0] : null;
}
return _validation;
}
let _previousFormData: any = null;
res.locals.previousFormData = () => {
if (!_previousFormData) {
const v = req.flash('previousFormData');
_previousFormData = v.length > 0 ? v [0] : null;
}
return _previousFormData;
};
next();
});
router.use((req, res, next) => {
if (['GET', 'POST'].find(m => m === req.method)) {
if (typeof req.body === 'object') {
req.flash('previousFormData', req.body);
}
}
next();
});
}
}