Merge pull request #1020 from bluewave-labs/913-fe-advanced-settings-page-validation-and-error-handling

913 fe advanced settings page validation and error handling
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-26 09:36:59 +08:00
commit 788b02b6f3
7 files changed
+182 -40

No files matched your search

@@ -41,6 +41,7 @@ const Field = forwardRef(
placeholder, placeholder,
value, value,
onChange, onChange,
onBlur,
onInput, onInput,
error, error,
disabled, disabled,
@@ -115,6 +116,7 @@ const Field = forwardRef(
value={value} value={value}
onInput={onInput} onInput={onInput}
onChange={onChange} onChange={onChange}
onBlur={onBlur}
disabled={disabled} disabled={disabled}
inputRef={ref} inputRef={ref}
inputProps={{ inputProps={{
@@ -216,6 +218,7 @@ Field.propTypes = {
placeholder: PropTypes.string, placeholder: PropTypes.string,
value: PropTypes.string.isRequired, value: PropTypes.string.isRequired,
onChange: PropTypes.func, onChange: PropTypes.func,
onBlur: PropTypes.func,
onInput: PropTypes.func, onInput: PropTypes.func,
error: PropTypes.string, error: PropTypes.string,
disabled: PropTypes.bool, disabled: PropTypes.bool,
@@ -46,6 +46,7 @@ const Select = ({
value, value,
items, items,
onChange, onChange,
onBlur,
sx, sx,
name = "", name = "",
}) => { }) => {
@@ -76,6 +77,7 @@ const Select = ({
className="select-component" className="select-component"
value={value} value={value}
onChange={onChange} onChange={onChange}
onBlur={onBlur}
displayEmpty displayEmpty
name={name} name={name}
inputProps={{ id: id }} inputProps={{ id: id }}
@@ -140,6 +142,7 @@ Select.propTypes = {
}) })
).isRequired, ).isRequired,
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func,
sx: PropTypes.object, sx: PropTypes.object,
}; };
+100 -15
View File
@@ -12,6 +12,8 @@ import { useNavigate } from "react-router";
import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice"; import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
import { advancedSettingsValidation } from "../../Validation/validation";
import { buildErrors, hasValidationErrors } from "../../Validation/error";
const AdvancedSettings = ({ isAdmin }) => { const AdvancedSettings = ({ isAdmin }) => {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -21,7 +23,7 @@ const AdvancedSettings = ({ isAdmin }) => {
navigate("/"); navigate("/");
} }
}, [navigate, isAdmin]); }, [navigate, isAdmin]);
const [errors, setErrors] = useState({});
const theme = useTheme(); const theme = useTheme();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const dispatch = useDispatch(); const dispatch = useDispatch();
@@ -33,17 +35,30 @@ const AdvancedSettings = ({ isAdmin }) => {
systemEmailPort: "", systemEmailPort: "",
systemEmailAddress: "", systemEmailAddress: "",
systemEmailPassword: "", systemEmailPassword: "",
jwtTTL: "", jwtTTLNum: 99,
jwtTTLUnits: "days",
jwtTTL: "99d",
dbType: "", dbType: "",
redisHost: "", redisHost: "",
redisPort: "", redisPort: "",
pagespeedApiKey: "", pagespeedApiKey: "",
}); });
const parseJWTTTL = (data) => {
if (data.jwtTTL) {
const len = data.jwtTTL.length;
data.jwtTTLNum = data.jwtTTL.substring(0, len - 1);
data.jwtTTLUnits = unitItems.filter(
(itm) => itm._id == data.jwtTTL.substring(len - 1)
)[0].name;
}
};
useEffect(() => { useEffect(() => {
const getSettings = async () => { const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken })); const action = await dispatch(getAppSettings({ authToken }));
if (action.payload.success) { if (action.payload.success) {
parseJWTTTL(action.payload.data);
setLocalSettings(action.payload.data); setLocalSettings(action.payload.data);
} else { } else {
createToast({ body: "Failed to get settings" }); createToast({ body: "Failed to get settings" });
@@ -66,24 +81,56 @@ const AdvancedSettings = ({ isAdmin }) => {
warn: 4, warn: 4,
}; };
const unitItemLookup = {
days: "d",
hours: "h",
};
const unitItems = Object.keys(unitItemLookup).map((key) => ({
_id: unitItemLookup[key],
name: key,
}));
const handleLogLevel = (e) => { const handleLogLevel = (e) => {
const id = e.target.value; const id = e.target.value;
const newLogLevel = logItems.find((item) => item._id === id).name; const newLogLevel = logItems.find((item) => item._id === id).name;
setLocalSettings({ ...localSettings, logLevel: newLogLevel }); setLocalSettings({ ...localSettings, logLevel: newLogLevel });
}; };
const handleJWTTTLUnits = (e) => {
const id = e.target.value;
const newUnits = unitItems.find((item) => item._id === id).name;
setLocalSettings({ ...localSettings, jwtTTLUnits: newUnits });
};
const handleBlur = (event) => {
const { value, id } = event.target;
const { error } = advancedSettingsValidation.validate(
{ [id]: value },
{
abortEarly: false,
}
);
setErrors((prev) => {
return buildErrors(prev, id, error);
});
};
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
setLocalSettings({ ...localSettings, [id]: value }); setLocalSettings({ ...localSettings, [id]: value });
}; };
const handleSave = async () => { const handleSave = async () => {
localSettings.jwtTTL =
localSettings.jwtTTLNum + unitItemLookup[localSettings.jwtTTLUnits];
if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors)) {
return;
}
const action = await dispatch( const action = await dispatch(
updateAppSettings({ settings: localSettings, authToken }) updateAppSettings({ settings: localSettings, authToken })
); );
let body = ""; let body = "";
if (action.payload.success) { if (action.payload.success) {
console.log(action.payload.data); parseJWTTTL(action.payload.data);
setLocalSettings(action.payload.data); setLocalSettings(action.payload.data);
body = "Settings saved successfully"; body = "Settings saved successfully";
} else { } else {
@@ -118,6 +165,8 @@ const AdvancedSettings = ({ isAdmin }) => {
label="API URL Host" label="API URL Host"
value={localSettings.apiBaseUrl} value={localSettings.apiBaseUrl}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.apiBaseUrl}
/> />
<Select <Select
id="logLevel" id="logLevel"
@@ -126,6 +175,8 @@ const AdvancedSettings = ({ isAdmin }) => {
items={logItems} items={logItems}
value={logItemLookup[localSettings.logLevel]} value={logItemLookup[localSettings.logLevel]}
onChange={handleLogLevel} onChange={handleLogLevel}
onBlur={handleBlur}
error={errors.logLevel}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -141,18 +192,22 @@ const AdvancedSettings = ({ isAdmin }) => {
<Field <Field
type="text" type="text"
id="systemEmailHost" id="systemEmailHost"
label="Email host" label="System email host"
name="systemEmailHost" name="systemEmailHost"
value={localSettings.systemEmailHost} value={localSettings.systemEmailHost}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailHost}
/> />
<Field <Field
type="number" type="number"
id="systemEmailPort" id="systemEmailPort"
label="System email address" label="System email port"
name="systemEmailPort" name="systemEmailPort"
value={localSettings.systemEmailPort.toString()} value={localSettings.systemEmailPort?.toString()}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailPort}
/> />
<Field <Field
type="email" type="email"
@@ -161,6 +216,7 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailAddress" name="systemEmailAddress"
value={localSettings.systemEmailAddress} value={localSettings.systemEmailAddress}
onChange={handleChange} onChange={handleChange}
error={errors.systemEmailAddress}
/> />
<Field <Field
type="text" type="text"
@@ -169,6 +225,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailPassword" name="systemEmailPassword"
value={localSettings.systemEmailPassword} value={localSettings.systemEmailPassword}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailPassword}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -180,14 +238,33 @@ const AdvancedSettings = ({ isAdmin }) => {
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Stack
type="text" direction="row"
id="jwtTTL" gap={theme.spacing(10)}
label="JWT time to live" >
name="jwtTTL" <Field
value={localSettings.jwtTTL} type="number"
onChange={handleChange} id="jwtTTLNum"
/> label="JWT time to live"
name="jwtTTLNum"
value={localSettings.jwtTTLNum.toString()}
onChange={handleChange}
onBlur={handleBlur}
error={errors.jwtTTLNum}
/>
<Select
id="jwtTTLUnits"
label="JWT TTL Units"
name="jwtTTLUnits"
placeholder="Select time"
isHidden={true}
items={unitItems}
value={unitItemLookup[localSettings.jwtTTLUnits]}
onChange={handleJWTTTLUnits}
onBlur={handleBlur}
error={errors.jwtTTLUnits}
/>
</Stack>
<Field <Field
type="text" type="text"
id="dbType" id="dbType"
@@ -195,6 +272,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="dbType" name="dbType"
value={localSettings.dbType} value={localSettings.dbType}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.dbType}
/> />
<Field <Field
type="text" type="text"
@@ -203,14 +282,18 @@ const AdvancedSettings = ({ isAdmin }) => {
name="redisHost" name="redisHost"
value={localSettings.redisHost} value={localSettings.redisHost}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.redisHost}
/> />
<Field <Field
type="number" type="number"
id="redisPort" id="redisPort"
label="Redis port" label="Redis port"
name="redisPort" name="redisPort"
value={localSettings.redisPort.toString()} value={localSettings.redisPort?.toString()}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.redisPort}
/> />
<Field <Field
type="text" type="text"
@@ -219,6 +302,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="pagespeedApiKey" name="pagespeedApiKey"
value={localSettings.pagespeedApiKey} value={localSettings.pagespeedApiKey}
onChange={handleChange} onChange={handleChange}
onBlur={handleBlur}
error={errors.pagespeedApiKey}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -28,6 +28,7 @@ import {
MS_PER_WEEK, MS_PER_WEEK,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
const getDurationAndUnit = (durationInMs) => { const getDurationAndUnit = (durationInMs) => {
if (durationInMs % MS_PER_DAY === 0) { if (durationInMs % MS_PER_DAY === 0) {
@@ -176,16 +177,6 @@ const CreateMaintenance = () => {
fetchMonitors(); fetchMonitors();
}, [authToken, user]); }, [authToken, user]);
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message;
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const handleSearch = (value) => { const handleSearch = (value) => {
setSearch(value); setSearch(value);
}; };
@@ -224,20 +215,8 @@ const CreateMaintenance = () => {
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
const { error } = maintenanceWindowValidation.validate(form, { if (hasValidationErrors(form, maintenanceWindowValidation, setErrors))
abortEarly: false,
});
// If errors, return early
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
logger.error(error);
return; return;
}
// Build timestamp for maintenance window from startDate and startTime // Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate) const start = dayjs(form.startDate)
.set("hour", form.startTime.hour()) .set("hour", form.startTime.hour())
+37
View File
@@ -0,0 +1,37 @@
const buildErrors = (prev, id, error) => {
const updatedErrors = { ...prev };
if (error) {
updatedErrors[id] = error.details[0].message?? "Validation error";
} else {
delete updatedErrors[id];
}
return updatedErrors;
};
const hasValidationErrors = (form, validation, setErrors) => {
const { error } = validation.validate(form, {
abortEarly: false,
});
if (error) {
const newErrors = {};
error.details.forEach((err) => {
if (
![
"clientHost",
"refreshTokenSecret",
"dbConnectionString",
"refreshTokenTTL",
"jwtTTL",
].includes(err.path[0])
) {
newErrors[err.path[0]] = err.message ?? "Validation error";
}
});
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return true;
} else return false;
}
return false;
};
export { buildErrors, hasValidationErrors };
+33
View File
@@ -128,10 +128,43 @@ const maintenanceWindowValidation = joi.object({
monitors: joi.array().min(1), monitors: joi.array().min(1),
}); });
const advancedSettingsValidation = joi.object({
apiBaseUrl: joi.string().uri({ allowRelative: true }).trim().messages({
"string.empty": "API base url is required.",
"string.uri": "The URL you provided is not valid.",
}),
logLevel: joi.string().valid("debug", "none", "error", "warn").allow(""),
systemEmailHost: joi.string().allow(""),
systemEmailPort: joi.number().allow(null, ""),
systemEmailAddress: joi.string().allow(""),
systemEmailPassword: joi.string().allow(""),
jwtTTLNum: joi.number().messages({
"number.base": "JWT TTL is required.",
}),
jwtTTLUnits: joi
.string()
.trim()
.custom((value, helpers) => {
if (!["days", "hours"].includes(value)) {
return helpers.message("JWT TTL unit is required.");
}
return value;
}),
dbType: joi.string().trim().messages({
"string.empty": "DB type is required.",
}),
redisHost: joi.string().trim().messages({
"string.empty": "Redis host is required.",
}),
redisPort: joi.number().allow(null, ""),
pagespeedApiKey: joi.string().allow(""),
});
export { export {
credentials, credentials,
imageValidation, imageValidation,
monitorValidation, monitorValidation,
settingsValidation, settingsValidation,
maintenanceWindowValidation, maintenanceWindowValidation,
advancedSettingsValidation
}; };
+4 -2
View File
@@ -26,10 +26,12 @@ Here you can setup the following:&#x20;
**Email settings:** Set your host email settings here. These settings are used for sending system emails. **Email settings:** Set your host email settings here. These settings are used for sending system emails.
Server settings: Several server settings can be done here. Alternatively, you can add a pagespeed API key to bypass Google's limitations (albeit they are generous about it) **Server settings:** Several server settings can be done here. Alternatively, you can add a pagespeed API key to bypass Google's limitations (albeit they are generous about it)
Select a number for jwt TTL and a unit for it (days or hours), the combined result
would be in vercel/ms time format, e.g "99d", this will be sent to server to persist
\