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
+183 -41

No files matched your search

@@ -41,6 +41,7 @@ const Field = forwardRef(
placeholder,
value,
onChange,
onBlur,
onInput,
error,
disabled,
@@ -115,6 +116,7 @@ const Field = forwardRef(
value={value}
onInput={onInput}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
inputRef={ref}
inputProps={{
@@ -216,6 +218,7 @@ Field.propTypes = {
placeholder: PropTypes.string,
value: PropTypes.string.isRequired,
onChange: PropTypes.func,
onBlur: PropTypes.func,
onInput: PropTypes.func,
error: PropTypes.string,
disabled: PropTypes.bool,
@@ -46,6 +46,7 @@ const Select = ({
value,
items,
onChange,
onBlur,
sx,
name = "",
}) => {
@@ -76,6 +77,7 @@ const Select = ({
className="select-component"
value={value}
onChange={onChange}
onBlur={onBlur}
displayEmpty
name={name}
inputProps={{ id: id }}
@@ -140,6 +142,7 @@ Select.propTypes = {
})
).isRequired,
onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func,
sx: PropTypes.object,
};
+100 -15
View File
@@ -12,6 +12,8 @@ import { useNavigate } from "react-router";
import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select";
import { advancedSettingsValidation } from "../../Validation/validation";
import { buildErrors, hasValidationErrors } from "../../Validation/error";
const AdvancedSettings = ({ isAdmin }) => {
const navigate = useNavigate();
@@ -21,7 +23,7 @@ const AdvancedSettings = ({ isAdmin }) => {
navigate("/");
}
}, [navigate, isAdmin]);
const [errors, setErrors] = useState({});
const theme = useTheme();
const { authToken } = useSelector((state) => state.auth);
const dispatch = useDispatch();
@@ -33,17 +35,30 @@ const AdvancedSettings = ({ isAdmin }) => {
systemEmailPort: "",
systemEmailAddress: "",
systemEmailPassword: "",
jwtTTL: "",
jwtTTLNum: 99,
jwtTTLUnits: "days",
jwtTTL: "99d",
dbType: "",
redisHost: "",
redisPort: "",
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(() => {
const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken }));
if (action.payload.success) {
parseJWTTTL(action.payload.data);
setLocalSettings(action.payload.data);
} else {
createToast({ body: "Failed to get settings" });
@@ -66,24 +81,56 @@ const AdvancedSettings = ({ isAdmin }) => {
warn: 4,
};
const unitItemLookup = {
days: "d",
hours: "h",
};
const unitItems = Object.keys(unitItemLookup).map((key) => ({
_id: unitItemLookup[key],
name: key,
}));
const handleLogLevel = (e) => {
const id = e.target.value;
const newLogLevel = logItems.find((item) => item._id === id).name;
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 { value, id } = event.target;
setLocalSettings({ ...localSettings, [id]: value });
};
const handleSave = async () => {
localSettings.jwtTTL =
localSettings.jwtTTLNum + unitItemLookup[localSettings.jwtTTLUnits];
if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors)) {
return;
}
const action = await dispatch(
updateAppSettings({ settings: localSettings, authToken })
);
let body = "";
if (action.payload.success) {
console.log(action.payload.data);
parseJWTTTL(action.payload.data);
setLocalSettings(action.payload.data);
body = "Settings saved successfully";
} else {
@@ -118,6 +165,8 @@ const AdvancedSettings = ({ isAdmin }) => {
label="API URL Host"
value={localSettings.apiBaseUrl}
onChange={handleChange}
onBlur={handleBlur}
error={errors.apiBaseUrl}
/>
<Select
id="logLevel"
@@ -126,6 +175,8 @@ const AdvancedSettings = ({ isAdmin }) => {
items={logItems}
value={logItemLookup[localSettings.logLevel]}
onChange={handleLogLevel}
onBlur={handleBlur}
error={errors.logLevel}
/>
</Stack>
</ConfigBox>
@@ -141,18 +192,22 @@ const AdvancedSettings = ({ isAdmin }) => {
<Field
type="text"
id="systemEmailHost"
label="Email host"
label="System email host"
name="systemEmailHost"
value={localSettings.systemEmailHost}
onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailHost}
/>
<Field
type="number"
id="systemEmailPort"
label="System email address"
label="System email port"
name="systemEmailPort"
value={localSettings.systemEmailPort.toString()}
value={localSettings.systemEmailPort?.toString()}
onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailPort}
/>
<Field
type="email"
@@ -161,6 +216,7 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailAddress"
value={localSettings.systemEmailAddress}
onChange={handleChange}
error={errors.systemEmailAddress}
/>
<Field
type="text"
@@ -169,6 +225,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="systemEmailPassword"
value={localSettings.systemEmailPassword}
onChange={handleChange}
onBlur={handleBlur}
error={errors.systemEmailPassword}
/>
</Stack>
</ConfigBox>
@@ -180,14 +238,33 @@ const AdvancedSettings = ({ isAdmin }) => {
</Typography>
</Box>
<Stack gap={theme.spacing(20)}>
<Field
type="text"
id="jwtTTL"
label="JWT time to live"
name="jwtTTL"
value={localSettings.jwtTTL}
onChange={handleChange}
/>
<Stack
direction="row"
gap={theme.spacing(10)}
>
<Field
type="number"
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
type="text"
id="dbType"
@@ -195,6 +272,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="dbType"
value={localSettings.dbType}
onChange={handleChange}
onBlur={handleBlur}
error={errors.dbType}
/>
<Field
type="text"
@@ -203,14 +282,18 @@ const AdvancedSettings = ({ isAdmin }) => {
name="redisHost"
value={localSettings.redisHost}
onChange={handleChange}
onBlur={handleBlur}
error={errors.redisHost}
/>
<Field
type="number"
id="redisPort"
label="Redis port"
name="redisPort"
value={localSettings.redisPort.toString()}
value={localSettings.redisPort?.toString()}
onChange={handleChange}
onBlur={handleBlur}
error={errors.redisPort}
/>
<Field
type="text"
@@ -219,6 +302,8 @@ const AdvancedSettings = ({ isAdmin }) => {
name="pagespeedApiKey"
value={localSettings.pagespeedApiKey}
onChange={handleChange}
onBlur={handleBlur}
error={errors.pagespeedApiKey}
/>
</Stack>
</ConfigBox>
@@ -28,6 +28,7 @@ import {
MS_PER_WEEK,
} from "../../../Utils/timeUtils";
import { useNavigate, useParams } from "react-router-dom";
import { buildErrors, hasValidationErrors } from "../../../Validation/error";
const getDurationAndUnit = (durationInMs) => {
if (durationInMs % MS_PER_DAY === 0) {
@@ -176,16 +177,6 @@ const CreateMaintenance = () => {
fetchMonitors();
}, [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) => {
setSearch(value);
};
@@ -224,20 +215,8 @@ const CreateMaintenance = () => {
};
const handleSubmit = async () => {
const { error } = maintenanceWindowValidation.validate(form, {
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;
}
if (hasValidationErrors(form, maintenanceWindowValidation, setErrors))
return;
// Build timestamp for maintenance window from startDate and startTime
const start = dayjs(form.startDate)
.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),
});
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 {
credentials,
imageValidation,
monitorValidation,
settingsValidation,
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.
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
\