mirror of
https://github.com/matt-fidd/stratos.git
synced 2026-01-01 15:59:25 +00:00
Refactored sanitisation function to allow more expandability and removed the need to clone the body
This commit is contained in:
@@ -118,6 +118,24 @@ describe('validate', () => {
|
||||
}).toThrow('missing');
|
||||
});
|
||||
|
||||
test('Unrequired fields added to map', () => {
|
||||
const body = {
|
||||
name: 'Bob',
|
||||
message: 'Hi Jim! '
|
||||
};
|
||||
|
||||
const fields = [
|
||||
'name',
|
||||
];
|
||||
|
||||
const result = validator.validate(body, fields);
|
||||
|
||||
expect(result).toBeObject();
|
||||
expect(result).toContainKey('fields');
|
||||
expect(result.fields.get('name')).toBe('Bob');
|
||||
expect(result.fields.get('message')).toBe('Hi Jim!');
|
||||
});
|
||||
|
||||
test('Valid email validation', () => {
|
||||
const body = {
|
||||
name: 'Bob',
|
||||
|
||||
@@ -30,6 +30,21 @@ function passwordsMatch(password1, password2) {
|
||||
return password1 === password2;
|
||||
}
|
||||
|
||||
/*
|
||||
* sanitiseField() Return a clean version of a given string
|
||||
*
|
||||
* @param {string} field - The field to be sanitised
|
||||
*
|
||||
* @return {string} - The sanitisied field
|
||||
*/
|
||||
function sanitiseField(field) {
|
||||
let cleanField;
|
||||
|
||||
cleanField = field.trim();
|
||||
|
||||
return cleanField;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate() Main validation wrapper function to validate full POST form body
|
||||
*
|
||||
@@ -40,25 +55,21 @@ function passwordsMatch(password1, password2) {
|
||||
* @return {Object} results
|
||||
* @return {Map<string, string>} results.fields - Sanitised and validated fields
|
||||
*/
|
||||
function validate(originalBody, fields, validation = {}) {
|
||||
const body = { ...originalBody };
|
||||
function validate(body, fields, validation = {}) {
|
||||
const fieldsMap = new Map();
|
||||
|
||||
// Check all required fields are not empty, and sanitise them
|
||||
// Sanitise all fields
|
||||
for (const [ field, content ] of Object.entries(body))
|
||||
fieldsMap.set(field, sanitiseField(content));
|
||||
|
||||
// Check all required fields are not empty
|
||||
for (const field of fields) {
|
||||
const cleanField = body[field]?.trim() ?? false;
|
||||
const cleanField = fieldsMap.get(field) ?? false;
|
||||
|
||||
if (cleanField === false || cleanField.length < 1)
|
||||
throw new Error(`${field} is missing`);
|
||||
|
||||
fieldsMap.set(field, cleanField);
|
||||
|
||||
delete body[field];
|
||||
}
|
||||
|
||||
for (const [ field, content ] of Object.entries(body))
|
||||
fieldsMap.set(field, content);
|
||||
|
||||
// Handle validation as required in options
|
||||
for (const [ check, checkOpts ] of Object.entries(validation)) {
|
||||
let valid;
|
||||
|
||||
Reference in New Issue
Block a user