@dwp/govuk-casa
Version:
A framework for building GOVUK Collect-And-Submit-Applications
74 lines • 2.82 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// Validate the data captured in the journey context
const JourneyContext_js_1 = __importDefault(require("../lib/JourneyContext.js"));
const constants_js_1 = require("../lib/constants.js");
const updateContext = ({ waypoint, errors = null, journeyContext, session, }) => {
// Set validation state
if (errors === null) {
journeyContext.clearValidationErrorsForPage(waypoint);
}
else {
journeyContext.setValidationErrorsForPage(waypoint, errors);
}
// Save to session
JourneyContext_js_1.default.putContext(session, journeyContext, {
userInfo: {
casaRequestPhase: constants_js_1.REQUEST_PHASE_VALIDATE,
},
});
};
exports.default = ({ waypoint, fields = [], plan }) => [
(req, res, next) => {
const mountUrl = `${req.baseUrl}/`;
// Run validators for every field to build up a complete list of errors
// currently associated with this waypoint.
let errors = [];
for (let i = 0, l = fields.length; i < l; i++) {
/* eslint-disable security/detect-object-injection */
// Dynamic object keys are only used on known entities (fields, waypoint)
const field = fields[i];
const fieldName = field.name;
const fieldValue = req.casa.journeyContext.data?.[waypoint]?.[fieldName];
// (type = ValidateContext)
const context = {
fieldName,
fieldValue,
waypoint,
journeyContext: req.casa.journeyContext,
};
/* eslint-enable security/detect-object-injection */
errors = [...errors, ...field.runValidators(context)];
}
// Validation passed with no errors
if (!errors.length) {
updateContext({
waypoint,
session: req.session,
mountUrl,
plan,
journeyContext: req.casa.journeyContext,
});
return next();
}
// If there are any native errors in the list, we need to bail the request
const nativeError = errors.find((e) => e instanceof Error);
if (nativeError) {
return next(nativeError);
}
// Make the errors available to downstream middleware
updateContext({
errors,
waypoint,
session: req.session,
mountUrl,
plan,
journeyContext: req.casa.journeyContext,
});
return next();
},
];
//# sourceMappingURL=validate-fields.js.map