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

Add defaults file for auto store #475

Closed
wants to merge 14 commits into from
24 changes: 24 additions & 0 deletions lib/template.session-defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*

Provide default values for user session data. These are automatically added
via the `autoStoreData` middleware. Values will only be added to the
session if a value doesn't already exist. This may be useful for testing
journeys where users are returning or logging in to an existing application.

============================================================================

Example usage:

"full-name": "Sarah Philips",

"options-chosen": [ "foo", "bar" ]

============================================================================

*/

module.exports = {

// Insert values here

}
13 changes: 13 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,19 @@ exports.autoStoreData = function (req, res, next) {
req.session.data = {}
}

try {
let defaultsFilePath = path.join(__dirname, '/../app/data/session-defaults.js')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requiring the file can come out of the middleware, it only needs to happen once right?


if (fs.existsSync(defaultsFilePath)) {
let defaults = require(defaultsFilePath)
defaults = Object.assign(defaults, req.session.data)

storeData(defaults, req.session)
}
} catch (e) {
console.error('Could not load the session defaults. Looked in app/data/session-defaults.js. Might be a syntax error?')
}

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

Expand Down
8 changes: 8 additions & 0 deletions start.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ if (!envExists) {
.pipe(fs.createWriteStream(path.join(__dirname, '/.env')))
}

// Create template session data defaults file if it doesn't exist
const sessionDefaultsExists = fs.existsSync(path.join(__dirname, '/app/data/session-defaults.js'))
if (!sessionDefaultsExists) {
console.log('Creating template session data defaults file')
fs.createReadStream(path.join(__dirname, '/lib/template.session-defaults.js'))
.pipe(fs.createWriteStream(path.join(__dirname, '/app/data/session-defaults.js')))
}

// Run gulp
const spawn = require('cross-spawn')

Expand Down