Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optionally set session data with a url parameter, and reference data with dot notation #705

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const fs = require('fs')

// NPM dependencies
const getKeypath = require('keypather/get')
const setKeypath = require('keypather/set')
const delKeypath = require('keypather/del')
const marked = require('marked')
const path = require('path')
const portScanner = require('portscanner')
Expand Down Expand Up @@ -231,7 +233,7 @@ var storeData = function (input, data) {

// Delete values when users unselect checkboxes
if (val === '_unchecked' || val === ['_unchecked']) {
delete data[i]
delKeypath(data, i) // should preserve the object structure but empty the contents of the value
continue
}

Expand All @@ -252,7 +254,17 @@ var storeData = function (input, data) {
continue
}

data[i] = val
// check it's a string - we're specifically looking for strings sent in the query parameters which are surrounded in squeare brackets denoting an array.
// console.log(val);
if (typeof val === 'string') {
if (val.match(/\[.+\]/g)) { // is the string surrounded in square brackets?
val = val.replace(/^\[/, '') // remove leading square bracket
val = val.replace(/\]+$/, '') // remove trailing square bracket
var arr = val.split(',') // Turn it into an array proper using a comma as the delimiter
val = arr // replace val with new array.
}
}
setKeypath(data, i, val)
}
}

Expand All @@ -276,7 +288,11 @@ exports.autoStoreData = function (req, res, next) {
req.session.data = Object.assign({}, sessionDataDefaults, req.session.data)

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

// merge query parameters into the session data unless specifically requested otherwise.
if (req.query.persist !== 'No') {
storeData(req.query, req.session.data)
}

// Send session data to all views

Expand All @@ -286,6 +302,12 @@ exports.autoStoreData = function (req, res, next) {
res.locals.data[j] = req.session.data[j]
}

// Query parameters will usually be merged with the session data, but you may additionally want to use them independently.
res.locals.query = res.locals.query || {}
for (var item in req.query) {
res.locals.query[item] = req.query[item]
}

next()
}

Expand Down