Skip to content

Commit

Permalink
Allow nested objects in session
Browse files Browse the repository at this point in the history
E.g.

<input name="example1[name]" value="Hello 123">
<input name="example2[name]" value="Hello 456">
<input name="example3[name]" value="Hello 789">
  • Loading branch information
colinrotherham committed Aug 2, 2018
1 parent df28524 commit a3c3d93
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
22 changes: 16 additions & 6 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const fs = require('fs')
// NPM dependencies
const basicAuth = require('basic-auth')
const marked = require('marked')
const Notation = require('notation')
const path = require('path')
const portScanner = require('portscanner')
const prompt = require('prompt')
Expand Down Expand Up @@ -34,7 +35,8 @@ exports.addCheckedFunction = function (env) {
return ''
}

var storedValue = this.ctx.data[name]
var storedData = new Notation(this.ctx.data)
var storedValue = storedData.get(name)

// Check the requested data exists
if (storedValue === undefined) {
Expand Down Expand Up @@ -243,7 +245,7 @@ exports.matchMdRoutes = function (req, res) {
}

// Store data from POST body or GET query in session
var storeData = function (input, store) {
var storeData = function (input, data) {
for (var i in input) {
// any input where the name starts with _ is ignored
if (i.indexOf('_') === 0) {
Expand All @@ -254,7 +256,7 @@ var storeData = function (input, store) {

// Delete values when users unselect checkboxes
if (val === '_unchecked' || val === ['_unchecked']) {
delete store.data[i]
delete data[i]
continue
}

Expand All @@ -264,9 +266,17 @@ var storeData = function (input, store) {
if (index !== -1) {
val.splice(index, 1)
}
} else if (typeof val === 'object') {
// Store nested objects that aren't arrays
if (typeof data[i] !== 'object') {
data[i] = {}
}

// Add nested values
return storeData(val, data[i])
}

store.data[i] = val
data[i] = val
}
}

Expand All @@ -289,8 +299,8 @@ exports.autoStoreData = function (req, res, next) {

req.session.data = Object.assign({}, sessionDataDefaults, req.session.data)

storeData(req.body, req.session)
storeData(req.query, req.session)
storeData(req.body, req.session.data)
storeData(req.query, req.session.data)

// Send session data to all views

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"gulp-util": "^3.0.7",
"marked": "^0.4.0",
"minimist": "1.2.0",
"notation": "^1.3.6",
"notifications-node-client": "^4.1.0",
"nunjucks": "^3.1.3",
"portscanner": "^2.1.1",
Expand Down

0 comments on commit a3c3d93

Please sign in to comment.