Skip to content

Commit

Permalink
refactor checked function
Browse files Browse the repository at this point in the history
  • Loading branch information
joelanman committed Apr 3, 2017
1 parent 1df56c6 commit 825b7a7
Showing 1 changed file with 22 additions and 32 deletions.
54 changes: 22 additions & 32 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,59 +118,49 @@ if (env === 'production' && useHttps === 'true') {
app.use(utils.forceHttps)
}

if (useAutoStoreData === 'true') {
app.use(utils.autoStoreData)
// add nunjucks function called 'checked' to populate radios and checkboxes,
// needs to be here as it needs access to req.session and nunjucks environment
var addCheckedFunction = function (app, nunjucksEnv) {
app.use(function (req, res, next) {
// add nunjucks function to get values, needs to be here as they need access to req.session

nunjucksAppEnv.addGlobal('checked', function (name, value) {
nunjucksEnv.addGlobal('checked', function (name, value) {
// check session data exists
if (req.session.data === undefined) {
return ''
}

var storedValue = req.session.data[name]

// check the requested data exists
if (storedValue === undefined) {
return ''
}

if (Array.isArray(storedValue)) {
var inArray = storedValue.indexOf(value) !== -1
return inArray ? 'checked' : ''
} else {
return value === storedValue ? 'checked' : ''
}
})

next()
})

documentationApp.use(function (req, res, next) {
// add nunjucks function to get values, needs to be here as they need access to req.session

nunjucksDocumentationEnv.addGlobal('checked', function (name, value) {
if (req.session.data === undefined) {
return ''
}

var storedValue = req.session.data[name]

if (storedValue === undefined) {
return ''
}
var checked = ''

// if data is an array, check it exists in the array
if (Array.isArray(storedValue)) {
var inArray = storedValue.indexOf(value) !== -1
return inArray ? 'checked' : ''
if (storedValue.indexOf(value) !== -1) {
checked = 'checked'
}
} else {
return value === storedValue ? 'checked' : ''
// the data is just a simple value, check it matches
if (storedValue === value) {
checked = 'checked'
}
}
return checked
})

next()
})
}

if (useAutoStoreData === 'true') {
app.use(utils.autoStoreData)
addCheckedFunction(app, nunjucksAppEnv)
addCheckedFunction(documentationApp, nunjucksDocumentationEnv)
}

// Disallow search index idexing
app.use(function (req, res, next) {
// Setting headers stops pages being indexed even if indexed pages link to them.
Expand Down

0 comments on commit 825b7a7

Please sign in to comment.