2020-07-11 11:46:16 +02:00
|
|
|
import {Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2021-05-03 19:29:22 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent.js";
|
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default class FormHelperComponent extends ApplicationComponent {
|
2020-07-11 11:46:16 +02:00
|
|
|
public async init(router: Router): Promise<void> {
|
2020-04-22 15:52:17 +02:00
|
|
|
router.use((req, res, next) => {
|
2020-09-25 23:42:15 +02:00
|
|
|
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-09-25 23:42:15 +02:00
|
|
|
};
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 23:42:15 +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;
|
|
|
|
}
|
|
|
|
|
|
|
|
return _previousFormData;
|
|
|
|
};
|
2021-01-25 17:26:14 +01:00
|
|
|
|
|
|
|
let _formPrefix: string | null;
|
|
|
|
res.locals.getFormPrefix = () => {
|
|
|
|
return _formPrefix;
|
|
|
|
};
|
|
|
|
res.locals.setFormPrefix = (formPrefix: string) => {
|
|
|
|
_formPrefix = formPrefix;
|
|
|
|
return '';
|
|
|
|
};
|
2020-04-22 15:52:17 +02:00
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
router.use((req, res, next) => {
|
|
|
|
if (['GET', 'POST'].find(m => m === req.method)) {
|
2021-01-25 17:26:29 +01:00
|
|
|
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();
|
|
|
|
});
|
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
}
|