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

Fix handling arrays in session data #709

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
76 changes: 76 additions & 0 deletions __tests__/spec/data-storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/* eslint-env jest */
const request = require('supertest')
const app = require('../../server.js')
const path = require('path')
const fs = require('fs')
const utils = require('../../lib/utils.js')

jest.setTimeout(30000)

function readFile (pathFromRoot) {
return fs.readFileSync(path.join(__dirname, '../../' + pathFromRoot), 'utf8')
}
/**
*
*/
describe('The data storage', () => {
// check session-data defaults file exists

it.skip('file should exist', (done) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not too familiar with Jest, but I think you're trying to access the session defaults file from an http request, which won't work. The file exists for the server to set up the default session data, not for access client-side.

const sessionDataDefaultsFile = readFile('app/data/session-data-defaults.js')

request(app)
.get(sessionDataDefaultsFile)
.expect('Content-Type', /application\/javascript; charset=UTF-8/)
// .expect(200)
.end(function (err, res) {
if (err) {
done(err)
} else {
done()
}
})
})

describe('storeData function', () => {
it('should add input data into session data', async () => {
let initialSessionData = {
'driver-name': 'Dr Emmett Brown'
}

const inputData = {
'vehicle-registration': 'OUTATIME'
}

utils.storeData(inputData, initialSessionData)

expect(initialSessionData).toEqual({
'driver-name': 'Dr Emmett Brown',
'vehicle-registration': 'OUTATIME'
})
})

it('should merge object into object', async () => {
let initialSessionData = {
vehicle: {
'driver-name': 'Dr Emmett Brown'
}
}

const inputData = {
vehicle: {
Copy link
Contributor

Choose a reason for hiding this comment

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

inputData comes from an http request, in which case I think it can only be key/value pairs, not objects. I think to test we need to use dot or square bracket notation in strings, like 'vehicle.registration=OUTATIME'

Copy link
Contributor

Choose a reason for hiding this comment

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

sorry I'm wrong, the strings get converted to objects by Express BodyParser here:
https://github.com/alphagov/govuk-prototype-kit/blob/master/server.js#L134-L138

registration: 'OUTATIME'
}
}

utils.storeData(inputData, initialSessionData)

expect(initialSessionData).toEqual({
vehicle: {
'driver-name': 'Dr Emmett Brown',
registration: 'OUTATIME'
}
})
})
})
})
46 changes: 42 additions & 4 deletions app/data/session-data-defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,47 @@ Example usage:
============================================================================

*/

module.exports = {

// Insert values here

// Example as used in current docs
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we need to leave this file blank for users to fill in if they need to? Can this test data be stored somewhere else?

Copy link
Contributor

@NickColley NickColley Nov 26, 2019

Choose a reason for hiding this comment

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

It's just test code for whoever picks this up next. "Delete this commit. Demo for testing"

Copy link
Contributor

Choose a reason for hiding this comment

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

ah thanks!

claimant: {
field1: 'Example 1',
field2: 'Example 2',
field3: 'Example 3'
},
partner: {
field1: 'Example 1',
field2: 'Example 2',
field3: 'Example 3'
},
myObject: {
// Array of objects within object
myArrayOfObjects: [
{
name: 'test1',
address: 'test2'
},
{
name: 'test3'
}
],
// Simple array within object
mySimpleArray: [
'test4',
'test5'
],
// Multi-level array within object
myMultiLevelArray: [
[
['test6', 'test7'],
'test8'
]
]
},
// Arrays within array
myArray: [
[
'test9',
['test10', 'test11']
]
]
}
47 changes: 47 additions & 0 deletions docs/views/examples/pass-data/test1.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{% extends "layout.html" %}

{% block pageTitle %}
Example - Passing data
{% endblock %}

{% block beforeContent %}
{% include "includes/breadcrumb_examples.html" %}
{% endblock %}

{% block content %}

<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">

<form action="/docs/examples/pass-data/test2" method="post" class="form">

<div class="govuk-form-group">
<h3 class="govuk-label-wrapper">
Example as used in current docs
</h3>
<input class="govuk-input" id="registration-number" name="[claimant][field1]" value="{{ data['claimant']['field1'] }}" type="text">
<h3 class="govuk-label-wrapper">
Array of objects within object
</h3>
<input class="govuk-input" id="registration-number" name="[myObject][myArrayOfObjects][0][name]" value="{{ data['myObject']['myArrayOfObjects'][0]['name'] }}" type="text">
<h3 class="govuk-label-wrapper">
Simple array within object
</h3>
<input class="govuk-input" id="registration-number" name="[myObject][mySimpleArray][0]" value="{{ data['myObject']['mySimpleArray'][0] }}" type="text">
<h3 class="govuk-label-wrapper">
Multi-level array within object
</h3>
<input class="govuk-input" id="registration-number" name="[myObject][myMultiLevelArray][0][0][0]" value="{{ data['myObject']['myMultiLevelArray'][0][0][0] }}" type="text">
<h3 class="govuk-label-wrapper">
Arrays within array
</h3>
<input class="govuk-input" id="registration-number" name="[myArray][0][0]" value="{{ data['myArray'][0][0] }}" type="text">
</div>

<button class="govuk-button">Continue</button>

</form>

</div>
</div>
{% endblock %}
42 changes: 42 additions & 0 deletions docs/views/examples/pass-data/test2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{% extends "layout.html" %}

{% block pageTitle %}
Check your answers
{% endblock %}

{% block content %}

<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">

<h3>Example as used in current docs</h3>
{{ data['claimant']['field1'] }}
{{ data['claimant']['field2'] }}
<br>
<br>
<h3>Array of objects within object</h3>
{{ data['myObject']['myArrayOfObjects'][0]['name'] }}
{{ data['myObject']['myArrayOfObjects'][0]['address'] }}
{{ data['myObject']['myArrayOfObjects'][1]['name'] }}
<br>
<br>
<h3>Simple array within object</h3>
{{ data['myObject']['mySimpleArray'][0] }}
{{ data['myObject']['mySimpleArray'][1] }}
<br>
<br>
<h3>Multi-level array within object</h3>
{{ data['myObject']['myMultiLevelArray'][0][0][0] }}
{{ data['myObject']['myMultiLevelArray'][0][0][1] }}
{{ data['myObject']['myMultiLevelArray'][0][1] }}
<br>
<br>
<h3>Arrays within array</h3>
{{ data['myArray'][0][0] }}
{{ data['myArray'][0][1][0] }}
{{ data['myArray'][0][1][1] }}
</div>

</div>

{% endblock %}
37 changes: 20 additions & 17 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,10 @@ exports.matchMdRoutes = function (req, res) {
}

// Store data from POST body or GET query in session
var storeData = function (input, data) {
function storeData (input, data) {
// Value we store to indicate unchecked checkboxes. See `auto-store-data.js`
var uncheckedValue = '_unchecked'

for (var i in input) {
// any input where the name starts with _ is ignored
if (i.indexOf('_') === 0) {
Expand All @@ -230,32 +233,32 @@ var storeData = function (input, data) {
var val = input[i]

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

// Remove _unchecked from arrays of checkboxes
if (Array.isArray(val)) {
var index = val.indexOf('_unchecked')
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] = {}
}
if (typeof val === 'object') {
// If array contains `uncheckedValue`, it's array of checkboxes
if (Array.isArray(val) && val.indexOf(uncheckedValue) !== -1) {
// Remove `uncheckedValue` from arrays of checkboxes
val.splice(val.indexOf(uncheckedValue), 1)
} else { // Store arrays that don't contain "_unchecked", and nested objects
if (typeof data[i] !== 'object') {
data[i] = {}
}

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

data[i] = val
}
}

exports.storeData = storeData

// Get session default data from file
let sessionDataDefaults = {}

Expand Down