-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathform-context.ts
More file actions
245 lines (208 loc) · 6.21 KB
/
form-context.ts
File metadata and controls
245 lines (208 loc) · 6.21 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import Boom from '@hapi/boom'
import { type Request, type Server } from '@hapi/hapi'
import { isEqual } from 'date-fns'
import { PREVIEW_PATH_PREFIX } from '~/src/server/constants.js'
import {
checkEmailAddressForLiveFormSubmission,
getCacheService
} from '~/src/server/plugins/engine/helpers.js'
import { FormModel } from '~/src/server/plugins/engine/models/index.js'
import { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'
import { TerminalPageController } from '~/src/server/plugins/engine/pageControllers/index.js'
import * as defaultServices from '~/src/server/plugins/engine/services/index.js'
import {
type AnyRequest,
type FormContext,
type FormContextRequest,
type FormSubmissionError,
type FormSubmissionState
} from '~/src/server/plugins/engine/types.js'
import { FormStatus } from '~/src/server/routes/types.js'
import { type Services } from '~/src/server/types.js'
type JourneyState = FormStatus | 'preview'
export interface FormModelOptions {
services?: Services
controllers?: Record<string, typeof PageController>
basePath?: string
ordnanceSurveyApiKey?: string
formId?: string
routePrefix?: string
isPreview?: boolean
}
export interface FormContextOptions extends FormModelOptions {
errors?: FormSubmissionError[]
}
type SummaryRequest = FormContextRequest & {
yar: Request['yar']
}
export async function getFormModel(
slug: string,
state: JourneyState,
options: FormModelOptions = {}
) {
const services = options.services ?? defaultServices
const { formsService } = services
const isPreview = isPreviewState(state, options)
const formState = resolveState(state)
const metadata = await formsService.getFormMetadata(slug)
const definition = await formsService.getFormDefinition(
metadata.id,
formState
)
if (!definition) {
throw Boom.notFound(
`No definition found for form metadata ${metadata.id} (${slug}) ${state}`
)
}
return new FormModel(
definition,
{
basePath:
options.basePath ??
buildBasePath(options.routePrefix ?? '', slug, formState, isPreview),
ordnanceSurveyApiKey: options.ordnanceSurveyApiKey,
formId: options.formId ?? metadata.id
},
services,
options.controllers
)
}
export async function getFormContext(
{ server, yar }: Pick<Request, 'server' | 'yar'>,
slug: string,
state: JourneyState = FormStatus.Live,
options: FormContextOptions = {}
): Promise<FormContext> {
const formModel = await resolveFormModel(server, slug, state, options)
const cacheService = getCacheService(server)
const summaryRequest: SummaryRequest = {
app: {},
method: 'get',
params: {
path: 'summary',
slug,
...(isPreviewState(state, options) && {
state: resolveState(state)
})
},
path: `/${formModel.basePath}/summary`,
query: {},
url: new URL(
`/${formModel.basePath}/summary`,
'https://form-context.local'
),
server,
yar
}
const cachedState = await cacheService.getState(
summaryRequest as unknown as AnyRequest
)
const formState = {
...cachedState,
$$__referenceNumber: cachedState.$$__referenceNumber
} as unknown as FormSubmissionState
return formModel.getFormContext(
summaryRequest,
formState,
options.errors ?? []
)
}
export async function resolveFormModel(
server: Server,
slug: string,
state: JourneyState,
options: FormModelOptions = {}
) {
const services = options.services ?? defaultServices
const { formsService } = services
const metadata = await formsService.getFormMetadata(slug)
const formState = resolveState(state)
const isPreview = options.isPreview ?? isPreviewState(state, options)
const stateMetadata = metadata[formState]
if (!stateMetadata) {
throw Boom.notFound(
`No '${formState}' state for form metadata ${metadata.id}`
)
}
// The models cache is created lazily per server instance
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!server.app.models) {
server.app.models = new Map<string, { model: FormModel; updatedAt: Date }>()
}
const cache = server.app.models as Map<
string,
{ model: FormModel; updatedAt: Date }
>
const cacheKey = `${metadata.id}_${formState}_${isPreview}`
let entry = cache.get(cacheKey)
if (!entry || !isEqual(entry.updatedAt, stateMetadata.updatedAt)) {
const definition = await formsService.getFormDefinition(
metadata.id,
formState
)
if (!definition) {
throw Boom.notFound(
`No definition found for form metadata ${metadata.id} (${slug}) ${state}`
)
}
checkEmailAddressForLiveFormSubmission(
metadata.notificationEmail,
isPreview
)
const routePrefix =
options.routePrefix ?? server.realm.modifiers.route.prefix
const model = new FormModel(
definition,
{
basePath:
options.basePath ??
buildBasePath(routePrefix, slug, formState, isPreview),
ordnanceSurveyApiKey: options.ordnanceSurveyApiKey,
formId: options.formId ?? metadata.id
},
services,
options.controllers
)
entry = { model, updatedAt: stateMetadata.updatedAt }
cache.set(cacheKey, entry)
}
return entry.model
}
function buildBasePath(
routePrefix: string,
slug: string,
state: FormStatus,
isPreview: boolean
) {
const base = (
isPreview
? `${routePrefix}${PREVIEW_PATH_PREFIX}/${state}/${slug}`
: `${routePrefix}/${slug}`
).replace(/\/{2,}/g, '/')
return base.startsWith('/') ? base.slice(1) : base
}
export function getFirstJourneyPage(
context?: Pick<FormContext, 'relevantPages'>
) {
if (!context?.relevantPages) {
return undefined
}
const lastPageReached = context.relevantPages.at(-1)
const penultimatePageReached = context.relevantPages.at(-2)
if (
lastPageReached instanceof TerminalPageController &&
penultimatePageReached
) {
return penultimatePageReached
}
return lastPageReached
}
function resolveState(state: JourneyState): FormStatus {
return state === 'preview' ? FormStatus.Live : state
}
function isPreviewState(
state: JourneyState,
options: FormModelOptions = {}
): boolean {
return options.isPreview ?? state === 'preview'
}