-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstate.ts
More file actions
182 lines (155 loc) · 4.97 KB
/
state.ts
File metadata and controls
182 lines (155 loc) · 4.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { ControllerType, getHiddenFields } from '@defra/forms-model'
import { getCacheService } from '~/src/server/plugins/engine/helpers.js'
import {
CURRENT_PAGE_PATH_KEY,
STATE_NOT_YET_VALIDATED
} from '~/src/server/plugins/engine/index.js'
import { type FormModel } from '~/src/server/plugins/engine/models/FormModel.js'
import { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'
import {
type AnyFormRequest,
type FormContext,
type FormStateValue,
type FormValue
} from '~/src/server/plugins/engine/types.js'
import { type FormQuery } from '~/src/server/routes/types.js'
import { type Services } from '~/src/server/types.js'
import { isValidUUID } from '~/src/server/utils/utils.js'
const GUID_LENGTH = 36
/**
* A series of functions that can transform a pre-fill input parameter e.g lookup a form title based on form id
*/
const paramLookupFunctions = {
formId: async (val: string, services: Services) => {
let formTitle
if (val) {
const meta = await services.formsService.getFormMetadataById(val)
formTitle = meta.title
}
return {
key: 'formName',
value: formTitle
}
}
} as Partial<
Record<
string,
(
val: string,
services: Services
) => Promise<{ key: string; value: string | undefined }>
>
>
export function stripParam(query: FormQuery, paramToRemove: string) {
const params = {} as Record<string, FormStateValue | undefined>
for (const [key, value = ''] of Object.entries(query)) {
if (key !== paramToRemove) {
params[key] = value
}
}
return Object.keys(params).length ? (params as FormQuery) : undefined
}
/**
* Any hidden parameters defined in the FormDefinition may be pre-filled by URL parameter values.
* Other parameters are ignored for security reasons.
* @param request
* @param model
*/
export async function prefillStateFromQueryParameters(
request: AnyFormRequest,
page: PageControllerClass
): Promise<boolean> {
const { model } = page
const hiddenFieldNames = new Set(
getHiddenFields(model.def).map((field) => field.name)
)
if (!hiddenFieldNames.size) {
return false
}
// Remove 'returnUrl' param
const query = stripParam(request.query, 'returnUrl')
if (!query) {
return false
}
const params = {} as Record<string, FormStateValue | undefined>
for (const [key, value = ''] of Object.entries(query)) {
if (hiddenFieldNames.has(key)) {
const lookupFunc = paramLookupFunctions[key]
if (lookupFunc) {
const res = await lookupFunc(value, model.services)
// Store original value and result
params[key] = value
params[res.key] = res.value
} else {
params[key] = value
}
}
}
const formData = await page.getState(request)
await page.mergeState(request, formData, params)
return true
}
/**
* Checks whether the save-and-exit finished on a repeater with partial state
* @param context - the form context
*/
export function checkSaveAndExitRepeater(
context: FormContext,
model: FormModel
) {
const potentiallyInvalidState = context.state[STATE_NOT_YET_VALIDATED] as
| Record<string, FormValue>
| undefined
if (!potentiallyInvalidState) {
return
}
const originalPath = potentiallyInvalidState[CURRENT_PAGE_PATH_KEY]
const repeaterPaths = model.def.pages
.filter((page) => page.controller === ControllerType.Repeat)
.map((p) => `/${model.basePath}${p.path}/`)
if (typeof originalPath !== 'string') {
return undefined
}
const segments = originalPath.split('/')
const lastSegment = segments.at(-1) ?? ''
if (!isValidUUID(lastSegment)) {
return undefined
}
const guidStartIndex = originalPath.length - GUID_LENGTH
const originalPathWithoutGuid = originalPath.substring(0, guidStartIndex)
if (!repeaterPaths.includes(originalPathWithoutGuid)) {
return undefined
}
return originalPath
}
/**
* Copies any potentially invalid state into the payload, and removes those values from state
* NOTE - this method has a side-effect on 'context.state' and 'context.payload'
* @param request - the form request
* @param context - the form context
*/
export async function copyNotYetValidatedState(
request: AnyFormRequest,
context: FormContext
) {
const potentiallyInvalidState = context.state[STATE_NOT_YET_VALIDATED] as
| Record<string, FormValue>
| undefined
if (!potentiallyInvalidState) {
return
}
const originalPath = potentiallyInvalidState[CURRENT_PAGE_PATH_KEY]
if (originalPath && originalPath === request.url.pathname) {
context.payload = {
...context.payload,
...potentiallyInvalidState,
[CURRENT_PAGE_PATH_KEY]: undefined
}
// Remove any temporary 'not yet validated' state now it's been copied to the payload
if (context.state[STATE_NOT_YET_VALIDATED]) {
context.state[STATE_NOT_YET_VALIDATED] = undefined
}
const cacheService = getCacheService(request.server)
await cacheService.setState(request, context.state)
}
}