-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
84 lines (71 loc) · 1.62 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// ============================================================================
//
// old-input
//
// Middleware to recall previously submitted
// form values in Node.js and Express.
//
// https://github.com/andreybutov/old-input
//
// (c) 2017, Andrey Butov
// http://andreybutov.com
//
// ============================================================================
const sanitizer = require('sanitizer');
function initOldInputInSession(req, name) {
if ( !req.session.oldInput.hasOwnProperty(name) ) {
req.session.oldInput[name] = {
value : '',
error : ''
};
}
}
module.exports = function(req, res, next)
{
if ( !req.session ) {
return;
}
if ( req.method === 'POST' )
{
req.session.oldInput = {};
for ( var name in req.body ) {
if ( req.body.hasOwnProperty(name) ) {
initOldInputInSession(req, name);
req.session.oldInput[name].value = sanitizer.sanitize(req.body[name]);
}
}
req.oldInput = {
setError: function(name, error) {
if ( name ) {
initOldInputInSession(req, name);
req.session.oldInput[name].error = error;
}
}
};
}
else if ( req.method === 'GET' )
{
req.oldInput = {
value : function(name) {
if ( this.hasOwnProperty(name) ) {
return this[name].value || '';
}
},
error : function(name) {
if ( this.hasOwnProperty(name) ) {
return this[name].error || '';
}
}
};
if ( req.session.oldInput ) {
for ( var name in req.session.oldInput ) {
req.oldInput[name] = {
value : req.session.oldInput[name].value,
error : req.session.oldInput[name].error
}
}
}
req.session.oldInput = {};
}
next();
}