swaf/src/components/FormHelperComponent.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import {Express, Router} from "express";
export default class FormHelperComponent extends ApplicationComponent<void> {
public async start(app: Express, router: Router): Promise<void> {
router.use((req, res, next) => {
if (!req.session) {
throw new Error('Session is unavailable.');
}
res.locals.query = req.query;
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();
});
}
public async stop(): Promise<void> {
}
}