54 files changed
+1838
-1079
No files matched your search
@@ -72,14 +72,20 @@ You can see the memory footprint of MongoDB and Redis on the same server (398Mb
|
|||||||
|
|
||||||
## 💚 Questions & Ideas
|
## 💚 Questions & Ideas
|
||||||
|
|
||||||
If you have any questions, suggestions or comments, please use our [Discord channel](https://discord.gg/NAb6H3UTjK). We've also launched our [Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions) page! Feel free to ask questions or share your ideas—we'd love to hear from you!
|
If you have any questions, suggestions or comments, you have several options:
|
||||||
|
|
||||||
|
- [Discord channel](https://discord.gg/NAb6H3UTjK)
|
||||||
|
- [GitHub Discussions](https://github.com/bluewave-labs/bluewave-uptime/discussions)
|
||||||
|
- [Reddit group](https://www.reddit.com/r/CheckmateMonitoring/)
|
||||||
|
|
||||||
|
Feel free to ask questions or share your ideas - we'd love to hear from you!
|
||||||
|
|
||||||
## 🧩 Features
|
## 🧩 Features
|
||||||
|
|
||||||
- Completely open source, deployable on your servers or home devices (e.g Raspberry Pi 4 or 5)
|
- Completely open source, deployable on your servers or home devices (e.g Raspberry Pi 4 or 5)
|
||||||
- Website monitoring
|
- Website monitoring
|
||||||
- Page speed monitoring
|
- Page speed monitoring
|
||||||
- Infrastructure monitoring (memory, disk usage, CPU performance etc) - requires [Capture](https://github.com/bluewave-labs/capture)
|
- Infrastructure monitoring (memory, disk usage, CPU performance etc) - requires [Capture](https://github.com/bluewave-labs/capture) agent
|
||||||
- Docker monitoring
|
- Docker monitoring
|
||||||
- Ping monitoring
|
- Ping monitoring
|
||||||
- SSL monitoring
|
- SSL monitoring
|
||||||
@@ -134,7 +140,7 @@ If you have any questions, suggestions or comments, please use our [Discord chan
|
|||||||
|
|
||||||
We are [Alex](http://github.com/ajhollid) (team lead), [Vishnu](http://github.com/vishnusn77), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer) and [Mert](https://github.com/mertssmnoglu) helping individuals and businesses monitor their infra and servers.
|
We are [Alex](http://github.com/ajhollid) (team lead), [Vishnu](http://github.com/vishnusn77), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer) and [Mert](https://github.com/mertssmnoglu) helping individuals and businesses monitor their infra and servers.
|
||||||
|
|
||||||
We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 6000+ stars and attracted 80+ contributors from around the globe.
|
We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 7000+ stars and attracted 90+ contributors from around the globe.
|
||||||
|
|
||||||
Our repo is starred by employees from **Google, Microsoft, Intel, Cisco, Tencent, Electronic Arts, ByteDance, JP Morgan Chase, Deloitte, Accenture, Foxconn, Broadcom, China Telecom, Barclays, Capgemini, Wipro, Cloudflare, Dassault Systèmes and NEC**, so don’t hold back — jump in, contribute and learn with us!
|
Our repo is starred by employees from **Google, Microsoft, Intel, Cisco, Tencent, Electronic Arts, ByteDance, JP Morgan Chase, Deloitte, Accenture, Foxconn, Broadcom, China Telecom, Barclays, Capgemini, Wipro, Cloudflare, Dassault Systèmes and NEC**, so don’t hold back — jump in, contribute and learn with us!
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,6 @@ metadata:
|
|||||||
name: checkmate-secrets
|
name: checkmate-secrets
|
||||||
type: Opaque
|
type: Opaque
|
||||||
stringData:
|
stringData:
|
||||||
{{- range $key, $value := := $secrets }}
|
{{- range $key, $value := $secrets }}
|
||||||
{{ $key }}: {{ $value | quote }}
|
{{ $key }}: {{ $value | quote }}
|
||||||
{{- end }}
|
{{- end }}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { useEffect, useState, useMemo } from "react";
|
import { useEffect, useState, useMemo } from "react";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
import { Box, Typography } from "@mui/material";
|
import { Box, Typography } from "@mui/material";
|
||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
|
||||||
const MINIMUM_VALUE = 0;
|
const MINIMUM_VALUE = 0;
|
||||||
const MAXIMUM_VALUE = 100;
|
const MAXIMUM_VALUE = 100;
|
||||||
@@ -16,6 +18,8 @@ const MAXIMUM_VALUE = 100;
|
|||||||
* @param {number} [props.radius=60] - Radius of the gauge circle
|
* @param {number} [props.radius=60] - Radius of the gauge circle
|
||||||
* @param {number} [props.strokeWidth=15] - Width of the gauge stroke
|
* @param {number} [props.strokeWidth=15] - Width of the gauge stroke
|
||||||
* @param {number} [props.threshold=50] - Threshold for color change
|
* @param {number} [props.threshold=50] - Threshold for color change
|
||||||
|
* @param {number} [props.precision=1] - Precision of the progress percentage
|
||||||
|
* @param {string} [props.unit="%"] - Unit of progress
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* <CustomGauge
|
* <CustomGauge
|
||||||
@@ -27,7 +31,15 @@ const MAXIMUM_VALUE = 100;
|
|||||||
*
|
*
|
||||||
* @returns {React.ReactElement} Rendered CustomGauge component
|
* @returns {React.ReactElement} Rendered CustomGauge component
|
||||||
*/
|
*/
|
||||||
const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold = 50 }) => {
|
const CustomGauge = ({
|
||||||
|
isLoading = false,
|
||||||
|
progress = 0,
|
||||||
|
radius = 70,
|
||||||
|
strokeWidth = 15,
|
||||||
|
threshold = 50,
|
||||||
|
precision = 1,
|
||||||
|
unit = "%",
|
||||||
|
}) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
// Calculate the length of the stroke for the circle
|
// Calculate the length of the stroke for the circle
|
||||||
const { circumference, totalSize, strokeLength } = useMemo(
|
const { circumference, totalSize, strokeLength } = useMemo(
|
||||||
@@ -54,8 +66,22 @@ const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold =
|
|||||||
|
|
||||||
const fillColor =
|
const fillColor =
|
||||||
progressWithinRange > threshold
|
progressWithinRange > threshold
|
||||||
? theme.palette.error.lowContrast // CAIO_REVIEW
|
? theme.palette.error.lowContrast
|
||||||
: theme.palette.accent.main; // CAIO_REVIEW
|
: theme.palette.accent.main;
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
className="radial-chart"
|
||||||
|
width={radius}
|
||||||
|
height={radius}
|
||||||
|
alignItems="center"
|
||||||
|
justifyContent="center"
|
||||||
|
>
|
||||||
|
<CircularProgress color="accent" />
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
@@ -71,7 +97,7 @@ const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold =
|
|||||||
>
|
>
|
||||||
<circle
|
<circle
|
||||||
className="radial-chart-base"
|
className="radial-chart-base"
|
||||||
stroke={theme.palette.secondary.light} // CAIO_REVIEW
|
stroke={theme.palette.secondary.light}
|
||||||
strokeWidth={strokeWidth}
|
strokeWidth={strokeWidth}
|
||||||
fill="none"
|
fill="none"
|
||||||
cx={totalSize / 2} // Center the circle
|
cx={totalSize / 2} // Center the circle
|
||||||
@@ -103,7 +129,7 @@ const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold =
|
|||||||
fill: theme.typography.h2.color,
|
fill: theme.typography.h2.color,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{`${progressWithinRange.toFixed(1)}%`}
|
{`${progressWithinRange.toFixed(precision)}${unit}`}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
@@ -112,8 +138,11 @@ const CustomGauge = ({ progress = 0, radius = 70, strokeWidth = 15, threshold =
|
|||||||
export default CustomGauge;
|
export default CustomGauge;
|
||||||
|
|
||||||
CustomGauge.propTypes = {
|
CustomGauge.propTypes = {
|
||||||
|
isLoading: PropTypes.bool,
|
||||||
progress: PropTypes.number,
|
progress: PropTypes.number,
|
||||||
radius: PropTypes.number,
|
radius: PropTypes.number,
|
||||||
strokeWidth: PropTypes.number,
|
strokeWidth: PropTypes.number,
|
||||||
threshold: PropTypes.number,
|
threshold: PropTypes.number,
|
||||||
|
precision: PropTypes.number,
|
||||||
|
unit: PropTypes.string,
|
||||||
};
|
};
|
||||||
@@ -4,15 +4,14 @@ const ConfigBox = styled(Stack)(({ theme }) => ({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
justifyContent: "space-between",
|
justifyContent: "space-between",
|
||||||
gap: theme.spacing(20),
|
|
||||||
backgroundColor: theme.palette.primary.main,
|
backgroundColor: theme.palette.primary.main,
|
||||||
border: 1,
|
border: 1,
|
||||||
borderStyle: "solid",
|
borderStyle: "solid",
|
||||||
borderColor: theme.palette.primary.lowContrast,
|
borderColor: theme.palette.primary.lowContrast,
|
||||||
borderRadius: theme.spacing(2),
|
borderRadius: theme.spacing(2),
|
||||||
"& > *": {
|
"& > *": {
|
||||||
paddingTop: theme.spacing(12),
|
paddingTop: theme.spacing(15),
|
||||||
paddingBottom: theme.spacing(18),
|
paddingBottom: theme.spacing(15),
|
||||||
},
|
},
|
||||||
"& > div:first-of-type": {
|
"& > div:first-of-type": {
|
||||||
flex: 0.7,
|
flex: 0.7,
|
||||||
@@ -25,7 +24,7 @@ const ConfigBox = styled(Stack)(({ theme }) => ({
|
|||||||
"& > div:last-of-type": {
|
"& > div:last-of-type": {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
paddingRight: theme.spacing(20),
|
paddingRight: theme.spacing(20),
|
||||||
paddingLeft: theme.spacing(18),
|
paddingLeft: theme.spacing(20),
|
||||||
},
|
},
|
||||||
"& h1, & h2": {
|
"& h1, & h2": {
|
||||||
color: theme.palette.primary.contrastTextSecondary,
|
color: theme.palette.primary.contrastTextSecondary,
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { Stack, Typography } from "@mui/material";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
|
||||||
|
const DEFAULT_GAP = 6;
|
||||||
|
const FieldWrapper = ({
|
||||||
|
label,
|
||||||
|
children,
|
||||||
|
gap,
|
||||||
|
labelMb,
|
||||||
|
labelFontWeight = 500,
|
||||||
|
labelVariant = "h3",
|
||||||
|
labelSx = {},
|
||||||
|
sx = {},
|
||||||
|
}) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
gap={gap ?? theme.spacing(DEFAULT_GAP)}
|
||||||
|
sx={sx}
|
||||||
|
>
|
||||||
|
{label && (
|
||||||
|
<Typography
|
||||||
|
component={labelVariant}
|
||||||
|
color={theme.palette.primary.contrastTextSecondary}
|
||||||
|
fontWeight={labelFontWeight}
|
||||||
|
sx={{
|
||||||
|
...(labelMb !== undefined && { mb: theme.spacing(labelMb) }),
|
||||||
|
...labelSx,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
FieldWrapper.propTypes = {
|
||||||
|
label: PropTypes.node,
|
||||||
|
children: PropTypes.node.isRequired,
|
||||||
|
gap: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
|
||||||
|
labelMb: PropTypes.number,
|
||||||
|
labelFontWeight: PropTypes.number,
|
||||||
|
labelVariant: PropTypes.string,
|
||||||
|
labelSx: PropTypes.object,
|
||||||
|
sx: PropTypes.object,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default FieldWrapper;
|
||||||
@@ -24,7 +24,17 @@ import "./index.css";
|
|||||||
* @returns {JSX.Element} - The rendered Radio component.
|
* @returns {JSX.Element} - The rendered Radio component.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const Radio = ({ name, checked, value, id, size, title, desc, onChange }) => {
|
const Radio = ({
|
||||||
|
name,
|
||||||
|
checked,
|
||||||
|
value,
|
||||||
|
id,
|
||||||
|
size,
|
||||||
|
title,
|
||||||
|
desc,
|
||||||
|
onChange,
|
||||||
|
labelSpacing,
|
||||||
|
}) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -53,7 +63,14 @@ const Radio = ({ name, checked, value, id, size, title, desc, onChange }) => {
|
|||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
label={
|
label={
|
||||||
<>
|
<>
|
||||||
<Typography component="p">{title}</Typography>
|
<Typography
|
||||||
|
component="p"
|
||||||
|
mb={
|
||||||
|
labelSpacing !== undefined ? theme.spacing(labelSpacing) : theme.spacing(2)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
<Typography
|
<Typography
|
||||||
component="h6"
|
component="h6"
|
||||||
mt={theme.spacing(1)}
|
mt={theme.spacing(1)}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { useTheme } from "@emotion/react";
|
|||||||
import SearchIcon from "../../../assets/icons/search.svg?react";
|
import SearchIcon from "../../../assets/icons/search.svg?react";
|
||||||
import React, { useEffect } from "react";
|
import React, { useEffect } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import FieldWrapper from "../FieldWrapper";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Search component using Material UI's Autocomplete.
|
* Search component using Material UI's Autocomplete.
|
||||||
@@ -24,6 +25,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
* @param {Function} props.handleChange - Function to call when the input changes
|
* @param {Function} props.handleChange - Function to call when the input changes
|
||||||
* @param {Function} Prop.onBlur - Function to call when the input is blured
|
* @param {Function} Prop.onBlur - Function to call when the input is blured
|
||||||
* @param {Object} props.sx - Additional styles to apply to the component
|
* @param {Object} props.sx - Additional styles to apply to the component
|
||||||
|
* @param {string} props.unit - Label to identify type of options
|
||||||
* @returns {JSX.Element} The rendered Search component
|
* @returns {JSX.Element} The rendered Search component
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -49,7 +51,7 @@ const SearchAdornment = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
//TODO keep search state inside of component
|
//TODO keep search state inside of component.
|
||||||
const Search = ({
|
const Search = ({
|
||||||
label,
|
label,
|
||||||
id,
|
id,
|
||||||
@@ -68,6 +70,13 @@ const Search = ({
|
|||||||
startAdornment,
|
startAdornment,
|
||||||
endAdornment,
|
endAdornment,
|
||||||
onBlur,
|
onBlur,
|
||||||
|
//FieldWrapper's props
|
||||||
|
gap,
|
||||||
|
labelMb,
|
||||||
|
labelFontWeight,
|
||||||
|
labelVariant,
|
||||||
|
labelSx = {},
|
||||||
|
unit = "option",
|
||||||
}) => {
|
}) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -139,15 +148,17 @@ const Search = ({
|
|||||||
getOptionLabel={(option) => option[filteredBy]}
|
getOptionLabel={(option) => option[filteredBy]}
|
||||||
isOptionEqualToValue={(option, value) => option._id === value._id} // Compare by unique identifier
|
isOptionEqualToValue={(option, value) => option._id === value._id} // Compare by unique identifier
|
||||||
renderInput={(params) => (
|
renderInput={(params) => (
|
||||||
<Stack>
|
<FieldWrapper
|
||||||
<Typography
|
label={label}
|
||||||
component="h3"
|
labelMb={labelMb}
|
||||||
fontSize={"var(--env-var-font-size-medium)"}
|
labelVariant={labelVariant}
|
||||||
color={theme.palette.primary.contrastTextSecondary}
|
labelFontWeight={labelFontWeight}
|
||||||
fontWeight={500}
|
labelSx={labelSx}
|
||||||
>
|
gap={gap}
|
||||||
{label}
|
sx={{
|
||||||
</Typography>
|
...sx,
|
||||||
|
}}
|
||||||
|
>
|
||||||
<TextField
|
<TextField
|
||||||
{...params}
|
{...params}
|
||||||
error={Boolean(error)}
|
error={Boolean(error)}
|
||||||
@@ -175,7 +186,7 @@ const Search = ({
|
|||||||
{error}
|
{error}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Stack>
|
</FieldWrapper>
|
||||||
)}
|
)}
|
||||||
filterOptions={(options, { inputValue }) => {
|
filterOptions={(options, { inputValue }) => {
|
||||||
if (inputValue.trim() === "" && multiple && isAdorned) {
|
if (inputValue.trim() === "" && multiple && isAdorned) {
|
||||||
@@ -186,7 +197,12 @@ const Search = ({
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (filtered.length === 0) {
|
if (filtered.length === 0) {
|
||||||
return [{ [filteredBy]: "No monitors found", noOptions: true }];
|
return [
|
||||||
|
{
|
||||||
|
[filteredBy]: t("general.noOptionsFound", { unit: unit }),
|
||||||
|
noOptions: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
}
|
}
|
||||||
return filtered;
|
return filtered;
|
||||||
}}
|
}}
|
||||||
@@ -281,7 +297,7 @@ Search.propTypes = {
|
|||||||
options: PropTypes.array.isRequired,
|
options: PropTypes.array.isRequired,
|
||||||
filteredBy: PropTypes.string.isRequired,
|
filteredBy: PropTypes.string.isRequired,
|
||||||
secondaryLabel: PropTypes.string,
|
secondaryLabel: PropTypes.string,
|
||||||
value: PropTypes.array,
|
value: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
|
||||||
inputValue: PropTypes.string.isRequired,
|
inputValue: PropTypes.string.isRequired,
|
||||||
handleInputChange: PropTypes.func.isRequired,
|
handleInputChange: PropTypes.func.isRequired,
|
||||||
handleChange: PropTypes.func,
|
handleChange: PropTypes.func,
|
||||||
@@ -292,6 +308,7 @@ Search.propTypes = {
|
|||||||
startAdornment: PropTypes.object,
|
startAdornment: PropTypes.object,
|
||||||
endAdornment: PropTypes.object,
|
endAdornment: PropTypes.object,
|
||||||
onBlur: PropTypes.func,
|
onBlur: PropTypes.func,
|
||||||
|
unit: PropTypes.string,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Search;
|
export default Search;
|
||||||
@@ -2,6 +2,7 @@ import PropTypes from "prop-types";
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { MenuItem, Select as MuiSelect, Stack, Typography } from "@mui/material";
|
import { MenuItem, Select as MuiSelect, Stack, Typography } from "@mui/material";
|
||||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||||
|
import FieldWrapper from "../FieldWrapper";
|
||||||
|
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
@@ -50,8 +51,14 @@ const Select = ({
|
|||||||
onBlur,
|
onBlur,
|
||||||
sx,
|
sx,
|
||||||
name = "",
|
name = "",
|
||||||
labelControlSpacing = 2,
|
labelControlSpacing = 6,
|
||||||
maxWidth,
|
maxWidth,
|
||||||
|
//FieldWrapper's props
|
||||||
|
labelMb,
|
||||||
|
labelFontWeight,
|
||||||
|
labelVariant,
|
||||||
|
labelSx = {},
|
||||||
|
fieldWrapperSx = {},
|
||||||
}) => {
|
}) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const itemStyles = {
|
const itemStyles = {
|
||||||
@@ -69,20 +76,17 @@ const Select = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack
|
<FieldWrapper
|
||||||
gap={theme.spacing(labelControlSpacing)}
|
label={label}
|
||||||
className="select-wrapper"
|
labelMb={labelMb}
|
||||||
|
labelVariant={labelVariant}
|
||||||
|
labelFontWeight={labelFontWeight}
|
||||||
|
labelSx={labelSx}
|
||||||
|
gap={labelControlSpacing}
|
||||||
|
sx={{
|
||||||
|
...fieldWrapperSx,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{label && (
|
|
||||||
<Typography
|
|
||||||
component="h3"
|
|
||||||
color={theme.palette.primary.contrastTextSecondary}
|
|
||||||
fontWeight={500}
|
|
||||||
fontSize={13}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
<MuiSelect
|
<MuiSelect
|
||||||
className="select-component"
|
className="select-component"
|
||||||
value={value}
|
value={value}
|
||||||
@@ -107,6 +111,13 @@ const Select = ({
|
|||||||
"& svg path": {
|
"& svg path": {
|
||||||
fill: theme.palette.primary.contrastTextTertiary,
|
fill: theme.palette.primary.contrastTextTertiary,
|
||||||
},
|
},
|
||||||
|
"& .MuiSelect-select": {
|
||||||
|
padding: "0 13px",
|
||||||
|
minHeight: "34px",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
lineHeight: 1,
|
||||||
|
},
|
||||||
...sx,
|
...sx,
|
||||||
}}
|
}}
|
||||||
renderValue={(selected) => {
|
renderValue={(selected) => {
|
||||||
@@ -151,7 +162,7 @@ const Select = ({
|
|||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
</MuiSelect>
|
</MuiSelect>
|
||||||
</Stack>
|
</FieldWrapper>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Stack, TextField, Typography } from "@mui/material";
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { forwardRef, useState, cloneElement } from "react";
|
import { forwardRef, useState, cloneElement } from "react";
|
||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
|
import FieldWrapper from "../FieldWrapper";
|
||||||
|
|
||||||
const getSx = (theme, type, maxWidth) => {
|
const getSx = (theme, type, maxWidth) => {
|
||||||
const sx = {
|
const sx = {
|
||||||
@@ -85,31 +86,43 @@ const TextInput = forwardRef(
|
|||||||
marginLeft,
|
marginLeft,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
hidden = false,
|
hidden = false,
|
||||||
|
//FieldWrapper's props
|
||||||
|
gap,
|
||||||
|
labelMb,
|
||||||
|
labelFontWeight,
|
||||||
|
labelVariant,
|
||||||
|
labelSx = {},
|
||||||
|
sx = {},
|
||||||
},
|
},
|
||||||
ref
|
ref
|
||||||
) => {
|
) => {
|
||||||
const [fieldType, setFieldType] = useState(type);
|
const [fieldType, setFieldType] = useState(type);
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
const labelContent = label && (
|
||||||
|
<>
|
||||||
|
{label}
|
||||||
|
{isRequired && <Required />}
|
||||||
|
{isOptional && <Optional optionalLabel={optionalLabel} />}
|
||||||
|
</>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<Stack
|
<FieldWrapper
|
||||||
flex={flex}
|
label={labelContent}
|
||||||
display={hidden ? "none" : ""}
|
labelMb={labelMb}
|
||||||
marginTop={marginTop}
|
labelVariant={labelVariant}
|
||||||
marginRight={marginRight}
|
labelFontWeight={labelFontWeight}
|
||||||
marginBottom={marginBottom}
|
labelSx={labelSx}
|
||||||
marginLeft={marginLeft}
|
gap={gap}
|
||||||
|
sx={{
|
||||||
|
flex,
|
||||||
|
display: hidden ? "none" : "",
|
||||||
|
mt: marginTop,
|
||||||
|
mr: marginRight,
|
||||||
|
mb: marginBottom,
|
||||||
|
ml: marginLeft,
|
||||||
|
...sx,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Typography
|
|
||||||
component="h3"
|
|
||||||
fontSize={"var(--env-var-font-size-medium)"}
|
|
||||||
color={theme.palette.primary.contrastTextSecondary}
|
|
||||||
fontWeight={500}
|
|
||||||
mb={theme.spacing(2)}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
{isRequired && <Required />}
|
|
||||||
{isOptional && <Optional optionalLabel={optionalLabel} />}
|
|
||||||
</Typography>
|
|
||||||
<TextField
|
<TextField
|
||||||
id={id}
|
id={id}
|
||||||
name={name}
|
name={name}
|
||||||
@@ -132,7 +145,7 @@ const TextInput = forwardRef(
|
|||||||
}}
|
}}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</FieldWrapper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,7 +10,18 @@ import { useState, useEffect } from "react";
|
|||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme } from "@mui/material/styles";
|
||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
const NotificationConfig = ({ notifications, setMonitor, setNotifications }) => {
|
const NotificationConfig = ({
|
||||||
|
notifications,
|
||||||
|
setMonitor,
|
||||||
|
setNotifications,
|
||||||
|
//FieldWrapper's props
|
||||||
|
gap,
|
||||||
|
labelMb,
|
||||||
|
labelFontWeight,
|
||||||
|
labelVariant,
|
||||||
|
labelSx = {},
|
||||||
|
sx = {},
|
||||||
|
}) => {
|
||||||
// Local state
|
// Local state
|
||||||
const [notificationsSearch, setNotificationsSearch] = useState("");
|
const [notificationsSearch, setNotificationsSearch] = useState("");
|
||||||
const [selectedNotifications, setSelectedNotifications] = useState([]);
|
const [selectedNotifications, setSelectedNotifications] = useState([]);
|
||||||
@@ -66,6 +77,14 @@ const NotificationConfig = ({ notifications, setMonitor, setNotifications }) =>
|
|||||||
handleChange={(value) => {
|
handleChange={(value) => {
|
||||||
handleSearch(value);
|
handleSearch(value);
|
||||||
}}
|
}}
|
||||||
|
labelMb={labelMb}
|
||||||
|
labelVariant={labelVariant}
|
||||||
|
labelFontWeight={labelFontWeight}
|
||||||
|
labelSx={labelSx}
|
||||||
|
gap={gap}
|
||||||
|
sx={{
|
||||||
|
...sx,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<Stack
|
<Stack
|
||||||
flex={1}
|
flex={1}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
|
const ToastBody = ({ body }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
|
||||||
|
if (Array.isArray(body)) {
|
||||||
|
return (
|
||||||
|
<Stack gap={theme.spacing(2)}>
|
||||||
|
{body.map((item, idx) => (
|
||||||
|
<Typography
|
||||||
|
key={`item-${idx}`}
|
||||||
|
color={theme.palette.secondary.contrastText}
|
||||||
|
>
|
||||||
|
{item}
|
||||||
|
</Typography>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
} else if (typeof body === "string") {
|
||||||
|
return <Typography color={theme.palette.secondary.contrastText}>{body}</Typography>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
ToastBody.propTypes = {
|
||||||
|
body: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ToastBody;
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
import ToastBody from "./body";
|
||||||
|
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
|
||||||
|
import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined";
|
||||||
|
import WarningAmberOutlinedIcon from "@mui/icons-material/WarningAmberOutlined";
|
||||||
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
|
|
||||||
|
// Utils
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
|
const icons = {
|
||||||
|
info: <InfoOutlinedIcon />,
|
||||||
|
error: <ErrorOutlineOutlinedIcon />,
|
||||||
|
warning: <WarningAmberOutlinedIcon />,
|
||||||
|
};
|
||||||
|
|
||||||
|
const Toast = ({ variant, title, body, onClick, hasDismiss, hasIcon }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const icon = icons[variant];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
gap={theme.spacing(2)}
|
||||||
|
paddingTop={theme.spacing(4)}
|
||||||
|
paddingRight={theme.spacing(8)}
|
||||||
|
paddingBottom={theme.spacing(4)}
|
||||||
|
paddingLeft={theme.spacing(8)}
|
||||||
|
backgroundColor={theme.palette.alert.main}
|
||||||
|
border={`solid 1px ${theme.palette.alert.contrastText}`}
|
||||||
|
borderRadius={theme.shape.borderRadius}
|
||||||
|
>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
gap={theme.spacing(8)}
|
||||||
|
justifyContent="space-between"
|
||||||
|
alignItems="center"
|
||||||
|
>
|
||||||
|
{hasIcon && icon}
|
||||||
|
{title && (
|
||||||
|
<Typography
|
||||||
|
fontWeight="700"
|
||||||
|
color={theme.palette.secondary.contrastText}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{title && (
|
||||||
|
<IconButton onClick={onClick}>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
gap={theme.spacing(2)}
|
||||||
|
alignItems="center"
|
||||||
|
>
|
||||||
|
<ToastBody body={body} />
|
||||||
|
{!title && (
|
||||||
|
<IconButton onClick={onClick}>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
{hasDismiss && (
|
||||||
|
<Button
|
||||||
|
variant="text"
|
||||||
|
color="info"
|
||||||
|
onClick={onClick}
|
||||||
|
sx={{
|
||||||
|
fontWeight: "600",
|
||||||
|
width: "fit-content",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Toast;
|
||||||
|
|
||||||
|
Toast.propTypes = {
|
||||||
|
variant: PropTypes.string.isRequired,
|
||||||
|
title: PropTypes.string,
|
||||||
|
body: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
|
||||||
|
hasDismiss: PropTypes.bool,
|
||||||
|
hasIcon: PropTypes.bool,
|
||||||
|
onClick: PropTypes.func,
|
||||||
|
};
|
||||||
@@ -32,4 +32,83 @@ const useFetchLogs = () => {
|
|||||||
return [logs, isLoading, error];
|
return [logs, isLoading, error];
|
||||||
};
|
};
|
||||||
|
|
||||||
export { useFetchLogs };
|
const useFetchQueueData = (trigger) => {
|
||||||
|
const [jobs, setJobs] = useState(undefined);
|
||||||
|
const [metrics, setMetrics] = useState(undefined);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(undefined);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchJobs = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const response = await networkService.getQueueData();
|
||||||
|
if (response.status === 200) {
|
||||||
|
setJobs(response.data.data.jobs);
|
||||||
|
setMetrics(response.data.data.metrics);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setError(error);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchJobs();
|
||||||
|
}, [trigger]);
|
||||||
|
|
||||||
|
return [jobs, metrics, isLoading, error];
|
||||||
|
};
|
||||||
|
|
||||||
|
const useFlushQueue = () => {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(undefined);
|
||||||
|
|
||||||
|
const flushQueue = async (trigger, setTrigger) => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
await networkService.flushQueue();
|
||||||
|
createToast({
|
||||||
|
body: "Queue flushed",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
setError(error);
|
||||||
|
createToast({
|
||||||
|
body: error.message,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
setTrigger(!trigger);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return [flushQueue, isLoading, error];
|
||||||
|
};
|
||||||
|
|
||||||
|
const useFetchDiagnostics = () => {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(undefined);
|
||||||
|
const [diagnostics, setDiagnostics] = useState(undefined);
|
||||||
|
|
||||||
|
const fetchDiagnostics = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
const response = await networkService.getDiagnostics();
|
||||||
|
setDiagnostics(response.data.data);
|
||||||
|
} catch (error) {
|
||||||
|
createToast({
|
||||||
|
body: error.message,
|
||||||
|
});
|
||||||
|
setError(error);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchDiagnostics();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return [diagnostics, fetchDiagnostics, isLoading, error];
|
||||||
|
};
|
||||||
|
|
||||||
|
export { useFetchLogs, useFetchQueueData, useFlushQueue, useFetchDiagnostics };
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import { useState, useEffect } from "react";
|
|
||||||
import { networkService } from "../main";
|
|
||||||
import { createToast } from "../Utils/toastUtils";
|
|
||||||
|
|
||||||
const useFetchQueueData = (trigger) => {
|
|
||||||
const [jobs, setJobs] = useState(undefined);
|
|
||||||
const [metrics, setMetrics] = useState(undefined);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState(undefined);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchJobs = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
const response = await networkService.getQueueData();
|
|
||||||
if (response.status === 200) {
|
|
||||||
setJobs(response.data.data.jobs);
|
|
||||||
setMetrics(response.data.data.metrics);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
setError(error);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchJobs();
|
|
||||||
}, [trigger]);
|
|
||||||
|
|
||||||
return [jobs, metrics, isLoading, error];
|
|
||||||
};
|
|
||||||
|
|
||||||
const useFlushQueue = () => {
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState(undefined);
|
|
||||||
|
|
||||||
const flushQueue = async (trigger, setTrigger) => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
await networkService.flushQueue();
|
|
||||||
createToast({
|
|
||||||
body: "Queue flushed",
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
setError(error);
|
|
||||||
createToast({
|
|
||||||
body: error.message,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
setTrigger(!trigger);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return [flushQueue, isLoading, error];
|
|
||||||
};
|
|
||||||
|
|
||||||
export { useFetchQueueData, useFlushQueue };
|
|
||||||
@@ -62,14 +62,15 @@ export const CustomThreshold = ({
|
|||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
return (
|
return (
|
||||||
<Stack
|
<Stack
|
||||||
direction={"row"}
|
direction={{ sm: "column", md: "row" }}
|
||||||
sx={{
|
spacing={theme.spacing(2)}
|
||||||
width: "50%",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Box>
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: { md: "45%", lg: "25%", xl: "20%" },
|
||||||
|
}}
|
||||||
|
justifyContent="flex-start"
|
||||||
|
>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
id={checkboxId}
|
id={checkboxId}
|
||||||
name={checkboxName}
|
name={checkboxName}
|
||||||
@@ -81,8 +82,10 @@ export const CustomThreshold = ({
|
|||||||
<Stack
|
<Stack
|
||||||
direction={"row"}
|
direction={"row"}
|
||||||
sx={{
|
sx={{
|
||||||
justifyContent: "flex-end",
|
justifyContent: "flex-start",
|
||||||
}}
|
}}
|
||||||
|
alignItems="center"
|
||||||
|
spacing={theme.spacing(4)}
|
||||||
>
|
>
|
||||||
<TextInput
|
<TextInput
|
||||||
maxWidth="var(--env-var-width-4)"
|
maxWidth="var(--env-var-width-4)"
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
|
|||||||
import { createToast } from "../../../Utils/toastUtils";
|
import { createToast } from "../../../Utils/toastUtils";
|
||||||
import Select from "../../../Components/Inputs/Select";
|
import Select from "../../../Components/Inputs/Select";
|
||||||
import { CustomThreshold } from "./Components/CustomThreshold";
|
import { CustomThreshold } from "./Components/CustomThreshold";
|
||||||
|
import FieldWrapper from "../../../Components/Inputs/FieldWrapper";
|
||||||
|
|
||||||
const SELECT_VALUES = [
|
const SELECT_VALUES = [
|
||||||
{ _id: 0.25, name: "15 seconds" },
|
{ _id: 0.25, name: "15 seconds" },
|
||||||
@@ -283,7 +284,7 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
/>
|
/>
|
||||||
</Typography>
|
</Typography>
|
||||||
</Stack>
|
</Stack>
|
||||||
<Stack gap={theme.spacing(15)}>
|
<Stack gap={theme.spacing(8)}>
|
||||||
<TextInput
|
<TextInput
|
||||||
type="url"
|
type="url"
|
||||||
id="url"
|
id="url"
|
||||||
@@ -299,8 +300,10 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
disabled={!isCreate}
|
disabled={!isCreate}
|
||||||
/>
|
/>
|
||||||
{isCreate && (
|
{isCreate && (
|
||||||
<Box>
|
<FieldWrapper
|
||||||
<Typography component="p">{t("infrastructureProtocol")}</Typography>
|
label={t("infrastructureProtocol")}
|
||||||
|
labelVariant="p"
|
||||||
|
>
|
||||||
<ButtonGroup>
|
<ButtonGroup>
|
||||||
<Button
|
<Button
|
||||||
variant="group"
|
variant="group"
|
||||||
@@ -317,7 +320,7 @@ const CreateInfrastructureMonitor = () => {
|
|||||||
{t("http")}
|
{t("http")}
|
||||||
</Button>
|
</Button>
|
||||||
</ButtonGroup>
|
</ButtonGroup>
|
||||||
</Box>
|
</FieldWrapper>
|
||||||
)}
|
)}
|
||||||
<TextInput
|
<TextInput
|
||||||
type="text"
|
type="text"
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import Filter from "./Components/Filters";
|
|||||||
import SearchComponent from "../../Uptime/Monitors/Components/SearchComponent";
|
import SearchComponent from "../../Uptime/Monitors/Components/SearchComponent";
|
||||||
// Utils
|
// Utils
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useIsAdmin } from "../../../Hooks/useIsAdmin";
|
import { useIsAdmin } from "../../../Hooks/useIsAdmin";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useFetchMonitorsByTeamId } from "../../../Hooks/monitorHooks";
|
import { useFetchMonitorsByTeamId } from "../../../Hooks/monitorHooks";
|
||||||
@@ -58,6 +58,12 @@ const InfrastructureMonitors = () => {
|
|||||||
setPage(0);
|
setPage(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isSearching) {
|
||||||
|
setPage(0);
|
||||||
|
}
|
||||||
|
}, [isSearching]);
|
||||||
|
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
setSelectedStatus(undefined);
|
setSelectedStatus(undefined);
|
||||||
setToFilterStatus(undefined);
|
setToFilterStatus(undefined);
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Gauge from "../../../../../Components/Charts/CustomGauge";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
|
||||||
|
// Utils
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
import { getPercentage } from "../../utils/utils";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
const GaugeBox = ({ title, subtitle, children }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
alignItems="center"
|
||||||
|
p={theme.spacing(2)}
|
||||||
|
maxWidth={150}
|
||||||
|
width={150}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
|
||||||
|
<Typography variant="h2">{title}</Typography>
|
||||||
|
<Typography variant="body2">{subtitle}</Typography>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
GaugeBox.propTypes = {
|
||||||
|
title: PropTypes.string.isRequired,
|
||||||
|
subtitle: PropTypes.string.isRequired,
|
||||||
|
children: PropTypes.node.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
const Gauges = ({ diagnostics, isLoading }) => {
|
||||||
|
const heapTotalSize = getPercentage(
|
||||||
|
diagnostics?.v8HeapStats?.totalHeapSizeBytes,
|
||||||
|
diagnostics?.v8HeapStats?.heapSizeLimitBytes
|
||||||
|
);
|
||||||
|
|
||||||
|
const heapUsedSize = getPercentage(
|
||||||
|
diagnostics?.v8HeapStats?.usedHeapSizeBytes,
|
||||||
|
diagnostics?.v8HeapStats?.heapSizeLimitBytes
|
||||||
|
);
|
||||||
|
|
||||||
|
const actualHeapUsed = getPercentage(
|
||||||
|
diagnostics?.v8HeapStats?.usedHeapSizeBytes,
|
||||||
|
diagnostics?.v8HeapStats?.totalHeapSizeBytes
|
||||||
|
);
|
||||||
|
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
spacing={theme.spacing(4)}
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<GaugeBox
|
||||||
|
title={t("diagnosticsPage.gauges.heapAllocationTitle")}
|
||||||
|
subtitle={t("diagnosticsPage.gauges.heapAllocationSubtitle")}
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
isLoading={isLoading}
|
||||||
|
radius={100}
|
||||||
|
progress={heapTotalSize}
|
||||||
|
/>
|
||||||
|
</GaugeBox>
|
||||||
|
<GaugeBox
|
||||||
|
title={t("diagnosticsPage.gauges.heapUsageTitle")}
|
||||||
|
subtitle={t("diagnosticsPage.gauges.heapUsageSubtitle")}
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
isLoading={isLoading}
|
||||||
|
radius={100}
|
||||||
|
progress={heapUsedSize}
|
||||||
|
/>
|
||||||
|
</GaugeBox>
|
||||||
|
<GaugeBox
|
||||||
|
title={t("diagnosticsPage.gauges.heapUtilizationTitle")}
|
||||||
|
subtitle={t("diagnosticsPage.gauges.heapUtilizationSubtitle")}
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
isLoading={isLoading}
|
||||||
|
radius={100}
|
||||||
|
progress={actualHeapUsed}
|
||||||
|
/>
|
||||||
|
</GaugeBox>
|
||||||
|
<GaugeBox
|
||||||
|
title={t("diagnosticsPage.gauges.instantCpuUsageTitle")}
|
||||||
|
subtitle={t("diagnosticsPage.gauges.instantCpuUsageSubtitle")}
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
isLoading={isLoading}
|
||||||
|
radius={100}
|
||||||
|
progress={diagnostics?.cpuUsage?.usagePercentage}
|
||||||
|
precision={2}
|
||||||
|
/>
|
||||||
|
</GaugeBox>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
Gauges.propTypes = {
|
||||||
|
diagnostics: PropTypes.object,
|
||||||
|
isLoading: PropTypes.bool,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Gauges;
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Card from "@mui/material/Card";
|
||||||
|
import CardContent from "@mui/material/CardContent";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
|
import { getHumanReadableDuration } from "../../../../../Utils/timeUtils";
|
||||||
|
import { formatBytes } from "../../utils/utils";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
const StatsCard = ({ title, value, unit = "", isLoading }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Card sx={{ width: 150, maxWidth: 150, height: 80, maxHeight: 80 }}>
|
||||||
|
{isLoading ? (
|
||||||
|
<Stack
|
||||||
|
alignItems="center"
|
||||||
|
justifyContent="center"
|
||||||
|
height={80}
|
||||||
|
maxHeight={80}
|
||||||
|
>
|
||||||
|
<CircularProgress color="accent" />
|
||||||
|
</Stack>
|
||||||
|
) : (
|
||||||
|
<CardContent>
|
||||||
|
<Typography
|
||||||
|
variant="body1"
|
||||||
|
color={theme.palette.primary.contrastText}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body1">
|
||||||
|
{value} {unit}
|
||||||
|
</Typography>
|
||||||
|
</CardContent>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
StatsCard.propTypes = {
|
||||||
|
title: PropTypes.string,
|
||||||
|
value: PropTypes.string,
|
||||||
|
unit: PropTypes.string,
|
||||||
|
isLoading: PropTypes.bool,
|
||||||
|
};
|
||||||
|
|
||||||
|
const Stats = ({ diagnostics, isLoading }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
gap={theme.spacing(4)}
|
||||||
|
flexWrap="wrap"
|
||||||
|
>
|
||||||
|
<StatsCard
|
||||||
|
title={t("diagnosticsPage.stats.eventLoopDelayTitle")}
|
||||||
|
value={getHumanReadableDuration(diagnostics?.eventLoopDelayMs)}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
<StatsCard
|
||||||
|
title={t("diagnosticsPage.stats.uptimeTitle")}
|
||||||
|
value={getHumanReadableDuration(diagnostics?.uptimeMs)}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StatsCard
|
||||||
|
title={t("diagnosticsPage.stats.usedHeapSizeTitle")}
|
||||||
|
value={formatBytes(diagnostics?.v8HeapStats?.usedHeapSizeBytes)}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StatsCard
|
||||||
|
title={t("diagnosticsPage.stats.totalHeapSizeTitle")}
|
||||||
|
value={formatBytes(diagnostics?.v8HeapStats?.totalHeapSizeBytes)}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StatsCard
|
||||||
|
title={t("diagnosticsPage.stats.osMemoryLimitTitle")}
|
||||||
|
value={formatBytes(diagnostics?.osStats?.totalMemoryBytes)}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
Stats.propTypes = {
|
||||||
|
diagnostics: PropTypes.object,
|
||||||
|
isLoading: PropTypes.bool,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Stats;
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Gauges from "./components/gauges";
|
||||||
|
import Stats from "./components/stats";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
import Button from "@mui/material/Button";
|
||||||
|
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useFetchDiagnostics } from "../../../Hooks/logHooks";
|
||||||
|
|
||||||
|
const Diagnostics = () => {
|
||||||
|
// Local state
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [diagnostics, fetchDiagnostics, isLoading, error] = useFetchDiagnostics();
|
||||||
|
// Setup
|
||||||
|
return (
|
||||||
|
<Stack gap={theme.spacing(4)}>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="h2">{t("diagnosticsPage.diagnosticDescription")}</Typography>
|
||||||
|
</Box>
|
||||||
|
<Divider color={theme.palette.accent.main} />
|
||||||
|
<Stack
|
||||||
|
gap={theme.spacing(20)}
|
||||||
|
mt={theme.spacing(10)}
|
||||||
|
>
|
||||||
|
<Gauges
|
||||||
|
diagnostics={diagnostics}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
<Stats
|
||||||
|
diagnostics={diagnostics}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
<Box>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="accent"
|
||||||
|
onClick={fetchDiagnostics}
|
||||||
|
loading={isLoading}
|
||||||
|
>
|
||||||
|
Fetch Diagnostics
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Diagnostics;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
export const getPercentage = (value, total) => {
|
||||||
|
if (!value || !total) return 0;
|
||||||
|
return (value / total) * 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const formatBytes = (bytes) => {
|
||||||
|
if (!bytes) return "N/A";
|
||||||
|
|
||||||
|
if (bytes === 0) return "0 Bytes";
|
||||||
|
|
||||||
|
if (bytes >= 1024 * 1024 * 1024) {
|
||||||
|
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||||
|
};
|
||||||
@@ -2,6 +2,7 @@ import Stack from "@mui/material/Stack";
|
|||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Select from "../../../Components/Inputs/Select";
|
import Select from "../../../Components/Inputs/Select";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
|
||||||
import { useFetchLogs } from "../../../Hooks/logHooks";
|
import { useFetchLogs } from "../../../Hooks/logHooks";
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
@@ -51,12 +52,15 @@ const Logs = () => {
|
|||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(4)}>
|
<Stack gap={theme.spacing(4)}>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography variant="body">{t("logsPage.description")}</Typography>
|
<Typography variant="h2">{t("logsPage.description")}</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
|
<Divider color={theme.palette.accent.main} />
|
||||||
|
|
||||||
<Stack
|
<Stack
|
||||||
direction="row"
|
direction="row"
|
||||||
alignItems="center"
|
alignItems="center"
|
||||||
gap={theme.spacing(4)}
|
gap={theme.spacing(4)}
|
||||||
|
mt={theme.spacing(10)}
|
||||||
>
|
>
|
||||||
<Typography>{t("logsPage.logLevelSelect.title")}</Typography>
|
<Typography>{t("logsPage.logLevelSelect.title")}</Typography>
|
||||||
<Select
|
<Select
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import Stack from "@mui/material/Stack";
|
import Stack from "@mui/material/Stack";
|
||||||
import Typography from "@mui/material/Typography";
|
|
||||||
import StatBox from "../../../../../Components/StatBox";
|
import StatBox from "../../../../../Components/StatBox";
|
||||||
import StatusBoxes from "../../../../../Components/StatusBoxes";
|
import StatusBoxes from "../../../../../Components/StatusBoxes";
|
||||||
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
|
|
||||||
@@ -24,20 +22,17 @@ const Metrics = ({ metrics = {} }) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(2)}>
|
<StatusBoxes flexWrap="wrap">
|
||||||
<Typography variant="h2">{t("queuePage.metricsTable.title")}</Typography>
|
{data.map((metric) => {
|
||||||
<StatusBoxes flexWrap="wrap">
|
return (
|
||||||
{data.map((metric) => {
|
<StatBox
|
||||||
return (
|
key={metric.key}
|
||||||
<StatBox
|
heading={metric.title}
|
||||||
key={metric.key}
|
subHeading={metric.value}
|
||||||
heading={metric.title}
|
/>
|
||||||
subHeading={metric.value}
|
);
|
||||||
/>
|
})}
|
||||||
);
|
</StatusBoxes>
|
||||||
})}
|
|
||||||
</StatusBoxes>
|
|
||||||
</Stack>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export default Metrics;
|
export default Metrics;
|
||||||
@@ -5,10 +5,12 @@ import Metrics from "./components/Metrics";
|
|||||||
import FailedJobTable from "./components/FailedJobTable";
|
import FailedJobTable from "./components/FailedJobTable";
|
||||||
import ButtonGroup from "@mui/material/ButtonGroup";
|
import ButtonGroup from "@mui/material/ButtonGroup";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
|
||||||
// Utils
|
// Utils
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useFetchQueueData, useFlushQueue } from "../../../Hooks/queueHooks";
|
import { useFetchQueueData, useFlushQueue } from "../../../Hooks/logHooks";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
|
|
||||||
@@ -26,39 +28,46 @@ const QueueDetails = () => {
|
|||||||
if (error || flushError) return <div>Error: {error.message}</div>;
|
if (error || flushError) return <div>Error: {error.message}</div>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(20)}>
|
<Stack gap={theme.spacing(4)}>
|
||||||
<Metrics metrics={metrics} />
|
<Typography variant="h2">{t("queuePage.metricsTable.title")}</Typography>
|
||||||
<JobTable jobs={jobs} />
|
<Divider color={theme.palette.accent.main} />
|
||||||
<FailedJobTable metrics={metrics} />
|
<Stack
|
||||||
|
gap={theme.spacing(20)}
|
||||||
<ButtonGroup
|
mt={theme.spacing(10)}
|
||||||
variant="contained"
|
|
||||||
color="accent"
|
|
||||||
sx={{
|
|
||||||
position: "sticky",
|
|
||||||
bottom: 0,
|
|
||||||
zIndex: 1000,
|
|
||||||
backgroundColor: theme.palette.primary.main,
|
|
||||||
p: theme.spacing(4),
|
|
||||||
border: `1px solid ${theme.palette.primary.lowContrast}`,
|
|
||||||
borderRadius: theme.spacing(2),
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Button
|
<Metrics metrics={metrics} />
|
||||||
onClick={() => {
|
<JobTable jobs={jobs} />
|
||||||
setTrigger(!trigger);
|
<FailedJobTable metrics={metrics} />
|
||||||
|
|
||||||
|
<ButtonGroup
|
||||||
|
variant="contained"
|
||||||
|
color="accent"
|
||||||
|
sx={{
|
||||||
|
position: "sticky",
|
||||||
|
bottom: 0,
|
||||||
|
zIndex: 1000,
|
||||||
|
backgroundColor: theme.palette.primary.main,
|
||||||
|
p: theme.spacing(4),
|
||||||
|
border: `1px solid ${theme.palette.primary.lowContrast}`,
|
||||||
|
borderRadius: theme.spacing(2),
|
||||||
}}
|
}}
|
||||||
loading={isLoading}
|
|
||||||
>
|
>
|
||||||
{t("queuePage.refreshButton")}
|
<Button
|
||||||
</Button>
|
onClick={() => {
|
||||||
<Button
|
setTrigger(!trigger);
|
||||||
onClick={() => flushQueue(trigger, setTrigger)}
|
}}
|
||||||
loading={isFlushing}
|
loading={isLoading}
|
||||||
>
|
>
|
||||||
{t("queuePage.flushButton")}
|
{t("queuePage.refreshButton")}
|
||||||
</Button>
|
</Button>
|
||||||
</ButtonGroup>
|
<Button
|
||||||
|
onClick={() => flushQueue(trigger, setTrigger)}
|
||||||
|
loading={isFlushing}
|
||||||
|
>
|
||||||
|
{t("queuePage.flushButton")}
|
||||||
|
</Button>
|
||||||
|
</ButtonGroup>
|
||||||
|
</Stack>
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import Tabs from "@mui/material/Tabs";
|
|||||||
import Tab from "@mui/material/Tab";
|
import Tab from "@mui/material/Tab";
|
||||||
import Queue from "./Queue";
|
import Queue from "./Queue";
|
||||||
import LogsComponent from "./Logs";
|
import LogsComponent from "./Logs";
|
||||||
|
import Diagnostics from "./Diagnostics";
|
||||||
|
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -14,7 +15,7 @@ const Logs = () => {
|
|||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
// Local state
|
// Local state
|
||||||
const [value, setValue] = useState(0);
|
const [value, setValue] = useState(2);
|
||||||
|
|
||||||
// Handlers
|
// Handlers
|
||||||
const handleChange = (event, newValue) => {
|
const handleChange = (event, newValue) => {
|
||||||
@@ -31,9 +32,11 @@ const Logs = () => {
|
|||||||
>
|
>
|
||||||
<Tab label={t("logsPage.tabs.logs")} />
|
<Tab label={t("logsPage.tabs.logs")} />
|
||||||
<Tab label={t("logsPage.tabs.queue")} />
|
<Tab label={t("logsPage.tabs.queue")} />
|
||||||
|
<Tab label={t("logsPage.tabs.diagnostics")} />
|
||||||
</Tabs>
|
</Tabs>
|
||||||
{value === 0 && <LogsComponent />}
|
{value === 0 && <LogsComponent />}
|
||||||
{value === 1 && <Queue />}
|
{value === 1 && <Queue />}
|
||||||
|
{value === 2 && <Diagnostics />}
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// Components
|
||||||
|
import { Stack, Typography } from "@mui/material";
|
||||||
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
import { useTheme } from "@emotion/react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
|
const MonitorListItem = ({ monitor, onDelete }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
direction={"row"}
|
||||||
|
alignItems={"center"}
|
||||||
|
gap={theme.spacing(4)}
|
||||||
|
width="100%"
|
||||||
|
>
|
||||||
|
<Typography flexGrow={1}>{monitor.name}</Typography>
|
||||||
|
<DeleteIcon
|
||||||
|
sx={{ cursor: "pointer" }}
|
||||||
|
onClick={() => onDelete(monitor)}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
MonitorListItem.propTypes = {
|
||||||
|
monitor: PropTypes.shape({
|
||||||
|
_id: PropTypes.string.isRequired,
|
||||||
|
name: PropTypes.string.isRequired,
|
||||||
|
}).isRequired,
|
||||||
|
onDelete: PropTypes.func.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
const MonitorList = ({ selectedMonitors, setSelectedMonitors }) => {
|
||||||
|
const onDelete = (monitorToDelete) => {
|
||||||
|
const newMonitors = selectedMonitors.filter(
|
||||||
|
(monitor) => monitor._id !== monitorToDelete._id
|
||||||
|
);
|
||||||
|
setSelectedMonitors(newMonitors);
|
||||||
|
};
|
||||||
|
|
||||||
|
const theme = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
gap={theme.spacing(6)}
|
||||||
|
width="100%"
|
||||||
|
>
|
||||||
|
{selectedMonitors?.map((monitor) => (
|
||||||
|
<MonitorListItem
|
||||||
|
key={monitor._id}
|
||||||
|
monitor={monitor}
|
||||||
|
onDelete={onDelete}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
MonitorList.propTypes = {
|
||||||
|
selectedMonitors: PropTypes.arrayOf(
|
||||||
|
PropTypes.shape({
|
||||||
|
_id: PropTypes.string.isRequired,
|
||||||
|
name: PropTypes.string.isRequired,
|
||||||
|
})
|
||||||
|
).isRequired,
|
||||||
|
setSelectedMonitors: PropTypes.func.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MonitorList;
|
||||||
@@ -9,6 +9,8 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
|||||||
import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker";
|
import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker";
|
||||||
import { maintenanceWindowValidation } from "../../../Validation/validation";
|
import { maintenanceWindowValidation } from "../../../Validation/validation";
|
||||||
import { createToast } from "../../../Utils/toastUtils";
|
import { createToast } from "../../../Utils/toastUtils";
|
||||||
|
import MonitorList from "./Components/MonitorList";
|
||||||
|
import Checkbox from "../../../Components/Inputs/Checkbox";
|
||||||
|
|
||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import Select from "../../../Components/Inputs/Select";
|
import Select from "../../../Components/Inputs/Select";
|
||||||
@@ -212,6 +214,17 @@ const CreateMaintenance = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleMonitorsChange = (selected) => {
|
||||||
|
setForm((prev) => ({ ...prev, monitors: selected }));
|
||||||
|
const { error } = maintenanceWindowValidation.validate(
|
||||||
|
{ monitors: selected },
|
||||||
|
{ abortEarly: false }
|
||||||
|
);
|
||||||
|
setErrors((prev) => {
|
||||||
|
return buildErrors(prev, "monitors", error);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
if (hasValidationErrors(form, maintenanceWindowValidation, setErrors)) return;
|
if (hasValidationErrors(form, maintenanceWindowValidation, setErrors)) return;
|
||||||
// Build timestamp for maintenance window from startDate and startTime
|
// Build timestamp for maintenance window from startDate and startTime
|
||||||
@@ -525,19 +538,25 @@ const CreateMaintenance = () => {
|
|||||||
id={"monitors"}
|
id={"monitors"}
|
||||||
label={t("addMonitors")}
|
label={t("addMonitors")}
|
||||||
multiple={true}
|
multiple={true}
|
||||||
isAdorned={false}
|
isAdorned={true}
|
||||||
options={monitors ? monitors : []}
|
options={monitors}
|
||||||
filteredBy="name"
|
filteredBy="name"
|
||||||
secondaryLabel={"type"}
|
secondaryLabel={"type"}
|
||||||
inputValue={search}
|
inputValue={search}
|
||||||
value={form.monitors}
|
value={form.monitors}
|
||||||
handleInputChange={handleSearch}
|
handleInputChange={setSearch}
|
||||||
handleChange={handleSelectMonitors}
|
handleChange={handleMonitorsChange}
|
||||||
error={errors["monitors"]}
|
error={errors["monitors"]}
|
||||||
disabled={maintenanceWindowId !== undefined}
|
/>
|
||||||
|
<MonitorList
|
||||||
|
selectedMonitors={form.monitors}
|
||||||
|
setSelectedMonitors={(monitors) =>
|
||||||
|
setForm((prev) => ({ ...prev, monitors }))
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
|
|
||||||
<Box
|
<Box
|
||||||
ml="auto"
|
ml="auto"
|
||||||
display="inline-block"
|
display="inline-block"
|
||||||
|
|||||||
@@ -65,12 +65,19 @@ const CreateNotifications = () => {
|
|||||||
|
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
|
const getNotificationTypeValue = (typeId) => {
|
||||||
|
return NOTIFICATION_TYPES.find((type) => type._id === typeId)?.value || "email";
|
||||||
|
};
|
||||||
|
|
||||||
|
const extractError = (error, field) =>
|
||||||
|
error?.details.find((d) => d.path.includes(field))?.message;
|
||||||
|
|
||||||
// handlers
|
// handlers
|
||||||
const onSubmit = (e) => {
|
const onSubmit = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const form = {
|
const form = {
|
||||||
...notification,
|
...notification,
|
||||||
type: NOTIFICATION_TYPES.find((type) => type._id === notification.type).value,
|
type: getNotificationTypeValue(notification.type),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = null;
|
let error = null;
|
||||||
@@ -84,7 +91,7 @@ const CreateNotifications = () => {
|
|||||||
});
|
});
|
||||||
console.log(JSON.stringify(newErrors));
|
console.log(JSON.stringify(newErrors));
|
||||||
console.log(JSON.stringify(form, null, 2));
|
console.log(JSON.stringify(form, null, 2));
|
||||||
createToast({ body: "Please check the form for errors." });
|
createToast({ body: Object.values(newErrors)[0] });
|
||||||
setErrors(newErrors);
|
setErrors(newErrors);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -98,22 +105,32 @@ const CreateNotifications = () => {
|
|||||||
|
|
||||||
const onChange = (e) => {
|
const onChange = (e) => {
|
||||||
const { name, value } = e.target;
|
const { name, value } = e.target;
|
||||||
|
let rawNotification = { ...notification, [name]: value };
|
||||||
|
let newNotification = {
|
||||||
|
...rawNotification,
|
||||||
|
type: getNotificationTypeValue(rawNotification.type),
|
||||||
|
};
|
||||||
|
|
||||||
const newNotification = { ...notification, [name]: value };
|
const { error } = notificationValidation.validate(newNotification, {
|
||||||
|
abortEarly: false,
|
||||||
|
});
|
||||||
|
let validationError = { ...errors };
|
||||||
|
|
||||||
const { error } = notificationValidation.extract(name).validate(value);
|
if (name === "type") {
|
||||||
setErrors((prev) => ({
|
validationError["type"] = extractError(error, "type");
|
||||||
...prev,
|
validationError["address"] = extractError(error, "address");
|
||||||
[name]: error?.message,
|
} else {
|
||||||
}));
|
validationError[name] = extractError(error, name);
|
||||||
|
}
|
||||||
|
|
||||||
setNotification(newNotification);
|
setNotification(rawNotification);
|
||||||
|
setErrors(validationError);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onTestNotification = () => {
|
const onTestNotification = () => {
|
||||||
const form = {
|
const form = {
|
||||||
...notification,
|
...notification,
|
||||||
type: NOTIFICATION_TYPES.find((type) => type._id === notification.type).value,
|
type: getNotificationTypeValue(notification.type),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = null;
|
let error = null;
|
||||||
@@ -125,7 +142,7 @@ const CreateNotifications = () => {
|
|||||||
error.details.forEach((err) => {
|
error.details.forEach((err) => {
|
||||||
newErrors[err.path[0]] = err.message;
|
newErrors[err.path[0]] = err.message;
|
||||||
});
|
});
|
||||||
createToast({ body: "Please check the form for errors." });
|
createToast({ body: Object.values(newErrors)[0] });
|
||||||
setErrors(newErrors);
|
setErrors(newErrors);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -139,7 +156,7 @@ const CreateNotifications = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const type = NOTIFICATION_TYPES.find((type) => type._id === notification.type).value;
|
const type = getNotificationTypeValue(notification.type);
|
||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(10)}>
|
<Stack gap={theme.spacing(10)}>
|
||||||
<Breadcrumbs list={BREADCRUMBS} />
|
<Breadcrumbs list={BREADCRUMBS} />
|
||||||
|
|||||||
@@ -117,8 +117,8 @@ const SettingsEmail = ({
|
|||||||
<Box>
|
<Box>
|
||||||
<Stack gap={theme.spacing(10)}>
|
<Stack gap={theme.spacing(10)}>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelHost")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelHost")}
|
||||||
name="systemEmailHost"
|
name="systemEmailHost"
|
||||||
placeholder="smtp.gmail.com"
|
placeholder="smtp.gmail.com"
|
||||||
value={systemEmailHost}
|
value={systemEmailHost}
|
||||||
@@ -126,8 +126,8 @@ const SettingsEmail = ({
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelPort")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelPort")}
|
||||||
name="systemEmailPort"
|
name="systemEmailPort"
|
||||||
placeholder="425"
|
placeholder="425"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -136,8 +136,8 @@ const SettingsEmail = ({
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelUser")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelUser")}
|
||||||
name="systemEmailUser"
|
name="systemEmailUser"
|
||||||
placeholder={t("settingsPage.emailSettings.placeholderUser")}
|
placeholder={t("settingsPage.emailSettings.placeholderUser")}
|
||||||
value={systemEmailUser}
|
value={systemEmailUser}
|
||||||
@@ -145,8 +145,8 @@ const SettingsEmail = ({
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelAddress")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelAddress")}
|
||||||
name="systemEmailAddress"
|
name="systemEmailAddress"
|
||||||
placeholder="uptime@bluewavelabs.ca"
|
placeholder="uptime@bluewavelabs.ca"
|
||||||
value={systemEmailAddress}
|
value={systemEmailAddress}
|
||||||
@@ -155,8 +155,8 @@ const SettingsEmail = ({
|
|||||||
</Box>
|
</Box>
|
||||||
{(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && (
|
{(isEmailPasswordSet === false || emailPasswordHasBeenReset === true) && (
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelPassword")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelPassword")}
|
||||||
name="systemEmailPassword"
|
name="systemEmailPassword"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="123 456 789 101112"
|
placeholder="123 456 789 101112"
|
||||||
@@ -188,8 +188,8 @@ const SettingsEmail = ({
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelTLSServername")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelTLSServername")}
|
||||||
name="systemEmailTLSServername"
|
name="systemEmailTLSServername"
|
||||||
placeholder="bluewavelabs.ca"
|
placeholder="bluewavelabs.ca"
|
||||||
value={systemEmailTLSServername}
|
value={systemEmailTLSServername}
|
||||||
@@ -197,8 +197,8 @@ const SettingsEmail = ({
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography>{t("settingsPage.emailSettings.labelConnectionHost")}</Typography>
|
|
||||||
<TextInput
|
<TextInput
|
||||||
|
label={t("settingsPage.emailSettings.labelConnectionHost")}
|
||||||
name="systemEmailConnectionHost"
|
name="systemEmailConnectionHost"
|
||||||
placeholder="bluewavelabs.ca"
|
placeholder="bluewavelabs.ca"
|
||||||
value={systemEmailConnectionHost}
|
value={systemEmailConnectionHost}
|
||||||
|
|||||||
@@ -2,16 +2,37 @@ import Box from "@mui/material/Box";
|
|||||||
import Stack from "@mui/material/Stack";
|
import Stack from "@mui/material/Stack";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import ConfigBox from "../../Components/ConfigBox";
|
import ConfigBox from "../../Components/ConfigBox";
|
||||||
import Select from "../../Components/Inputs/Select";
|
import Search from "../../Components/Inputs/Search";
|
||||||
import timezones from "../../Utils/timezones.json";
|
import timezones from "../../Utils/timezones.json";
|
||||||
|
|
||||||
// Utils
|
// Utils
|
||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { PropTypes } from "prop-types";
|
import { PropTypes } from "prop-types";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
|
const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [rawInput, setRawInput] = useState("");
|
||||||
|
|
||||||
|
const selectedTimezone = useMemo(
|
||||||
|
() => timezones.find((tz) => tz._id === timezone) ?? null,
|
||||||
|
[timezone]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleTimezoneChange = useCallback(
|
||||||
|
(newValue) => {
|
||||||
|
setRawInput("");
|
||||||
|
handleChange({
|
||||||
|
target: {
|
||||||
|
name: "timezone",
|
||||||
|
value: newValue?._id ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[handleChange]
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ConfigBox>
|
<ConfigBox>
|
||||||
<Box>
|
<Box>
|
||||||
@@ -28,12 +49,17 @@ const SettingsTimeZone = ({ HEADING_SX, handleChange, timezone }) => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
<Stack gap={theme.spacing(20)}>
|
<Stack gap={theme.spacing(20)}>
|
||||||
<Select
|
<Search
|
||||||
label={t("settingsPage.timezoneSettings.label")}
|
id="timezone"
|
||||||
name="timezone"
|
label={t("settingsDisplayTimezone")}
|
||||||
value={timezone}
|
options={timezones}
|
||||||
onChange={handleChange}
|
filteredBy="name"
|
||||||
items={timezones}
|
value={selectedTimezone}
|
||||||
|
inputValue={rawInput}
|
||||||
|
handleInputChange={(val) => setRawInput(val)}
|
||||||
|
handleChange={handleTimezoneChange}
|
||||||
|
isAdorned={false}
|
||||||
|
unit="timezone"
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { TabPanel } from "@mui/lab";
|
|||||||
import ConfigBox from "../../../../../Components/ConfigBox";
|
import ConfigBox from "../../../../../Components/ConfigBox";
|
||||||
import Checkbox from "../../../../../Components/Inputs/Checkbox";
|
import Checkbox from "../../../../../Components/Inputs/Checkbox";
|
||||||
import TextInput from "../../../../../Components/Inputs/TextInput";
|
import TextInput from "../../../../../Components/Inputs/TextInput";
|
||||||
import Select from "../../../../../Components/Inputs/Select";
|
import Search from "../../../../../Components/Inputs/Search";
|
||||||
import ImageUpload from "../../../../../Components/Inputs/ImageUpload";
|
import ImageUpload from "../../../../../Components/Inputs/ImageUpload";
|
||||||
import ColorPicker from "../../../../../Components/Inputs/ColorPicker";
|
import ColorPicker from "../../../../../Components/Inputs/ColorPicker";
|
||||||
import Progress from "../Progress";
|
import Progress from "../Progress";
|
||||||
@@ -14,6 +14,7 @@ import { useTheme } from "@emotion/react";
|
|||||||
import timezones from "../../../../../Utils/timezones.json";
|
import timezones from "../../../../../Utils/timezones.json";
|
||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useMemo, useState, useCallback } from "react";
|
||||||
|
|
||||||
const TabSettings = ({
|
const TabSettings = ({
|
||||||
isCreate,
|
isCreate,
|
||||||
@@ -28,6 +29,25 @@ const TabSettings = ({
|
|||||||
// Utils
|
// Utils
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [rawInput, setRawInput] = useState("");
|
||||||
|
|
||||||
|
const selectedTimezone = useMemo(
|
||||||
|
() => timezones.find((tz) => tz._id === form.timezone) ?? null,
|
||||||
|
[form.timezone]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleTimezoneChange = useCallback(
|
||||||
|
(newValue) => {
|
||||||
|
setRawInput("");
|
||||||
|
handleFormChange({
|
||||||
|
target: {
|
||||||
|
name: "timezone",
|
||||||
|
value: newValue?._id ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[handleFormChange]
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TabPanel value={tabValue}>
|
<TabPanel value={tabValue}>
|
||||||
@@ -101,13 +121,17 @@ const TabSettings = ({
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Stack>
|
</Stack>
|
||||||
<Stack gap={theme.spacing(6)}>
|
<Stack gap={theme.spacing(6)}>
|
||||||
<Select
|
<Search
|
||||||
id="timezone"
|
id="timezone"
|
||||||
name="timezone"
|
|
||||||
label={t("settingsDisplayTimezone")}
|
label={t("settingsDisplayTimezone")}
|
||||||
items={timezones}
|
options={timezones}
|
||||||
value={form.timezone}
|
filteredBy="name"
|
||||||
onChange={handleFormChange}
|
value={selectedTimezone}
|
||||||
|
inputValue={rawInput}
|
||||||
|
handleInputChange={(newVal) => setRawInput(newVal)}
|
||||||
|
handleChange={handleTimezoneChange}
|
||||||
|
isAdorned={false}
|
||||||
|
unit="timezone"
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
|
|||||||
@@ -1091,6 +1091,14 @@ class NetworkService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getDiagnostics() {
|
||||||
|
return this.axiosInstance.get(`/diagnostic/system`, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default NetworkService;
|
export default NetworkService;
|
||||||
|
|||||||
@@ -553,6 +553,11 @@ const baseTheme = (palette) => ({
|
|||||||
"&:hover .MuiOutlinedInput-notchedOutline": {
|
"&:hover .MuiOutlinedInput-notchedOutline": {
|
||||||
borderColor: theme.palette.primary.lowContrast,
|
borderColor: theme.palette.primary.lowContrast,
|
||||||
},
|
},
|
||||||
|
padding: "0 13px",
|
||||||
|
minHeight: "34px",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
lineHeight: 1,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export const getHumanReadableDuration = (ms) => {
|
|||||||
hours: durationObj.hours(),
|
hours: durationObj.hours(),
|
||||||
minutes: durationObj.minutes(),
|
minutes: durationObj.minutes(),
|
||||||
seconds: durationObj.seconds(),
|
seconds: durationObj.seconds(),
|
||||||
|
milliseconds: durationObj.milliseconds(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = [];
|
const result = [];
|
||||||
@@ -101,6 +102,9 @@ export const getHumanReadableDuration = (ms) => {
|
|||||||
if (result.length < 2 && parts.seconds > 0) {
|
if (result.length < 2 && parts.seconds > 0) {
|
||||||
result.push(`${parts.seconds}s`);
|
result.push(`${parts.seconds}s`);
|
||||||
}
|
}
|
||||||
|
if (result.length < 2 && parts.milliseconds > 0 && parts.seconds < 1) {
|
||||||
|
result.push(`${parts.milliseconds.toFixed(2)}ms`);
|
||||||
|
}
|
||||||
|
|
||||||
if (result.length === 0) {
|
if (result.length === 0) {
|
||||||
// fallback for durations < 1s
|
// fallback for durations < 1s
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
import { toast, Slide } from "react-toastify";
|
import { toast, Slide } from "react-toastify";
|
||||||
import Alert from "../Components/Alert";
|
import Toast from "../Components/Toast";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {object} props
|
* @param {object} props
|
||||||
* @param {'info' | 'error' | 'warning'} - The variant of the alert (e.g., "info", "error").
|
* @param {'info' | 'error' | 'warning'} - The variant of the alert (e.g., "info", "error").
|
||||||
@@ -15,6 +14,7 @@ export const createToast = ({
|
|||||||
variant = "info",
|
variant = "info",
|
||||||
title,
|
title,
|
||||||
body,
|
body,
|
||||||
|
hasDismiss = false,
|
||||||
hasIcon = false,
|
hasIcon = false,
|
||||||
config = {},
|
config = {},
|
||||||
}) => {
|
}) => {
|
||||||
@@ -29,13 +29,14 @@ export const createToast = ({
|
|||||||
|
|
||||||
toast(
|
toast(
|
||||||
({ closeToast }) => (
|
({ closeToast }) => (
|
||||||
<Alert
|
<Toast
|
||||||
variant={variant}
|
variant={variant}
|
||||||
title={title}
|
title={title}
|
||||||
body={body}
|
body={body}
|
||||||
isToast={true}
|
isToast={true}
|
||||||
hasIcon={hasIcon}
|
|
||||||
onClick={closeToast}
|
onClick={closeToast}
|
||||||
|
hasDismiss={hasDismiss}
|
||||||
|
hasIcon={hasIcon}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
toastConfig
|
toastConfig
|
||||||
@@ -47,5 +48,6 @@ createToast.propTypes = {
|
|||||||
title: PropTypes.string,
|
title: PropTypes.string,
|
||||||
body: PropTypes.string.isRequired,
|
body: PropTypes.string.isRequired,
|
||||||
hasIcon: PropTypes.bool,
|
hasIcon: PropTypes.bool,
|
||||||
|
hasDismiss: PropTypes.bool,
|
||||||
config: PropTypes.object,
|
config: PropTypes.object,
|
||||||
};
|
};
|
||||||
@@ -410,14 +410,33 @@ const notificationValidation = joi.object({
|
|||||||
"string.empty": "Notification name is required",
|
"string.empty": "Notification name is required",
|
||||||
"any.required": "Notification name is required",
|
"any.required": "Notification name is required",
|
||||||
}),
|
}),
|
||||||
address: joi.string().required().messages({
|
|
||||||
"string.empty": "This field cannot be empty",
|
type: joi
|
||||||
"string.base": "This field must be a string",
|
.string()
|
||||||
"any.required": "This field is required",
|
.valid("email", "webhook", "slack", "discord", "pager_duty")
|
||||||
}),
|
.required()
|
||||||
type: joi.string().required().messages({
|
.messages({
|
||||||
"string.empty": "This field is required",
|
"string.empty": "Notification type is required",
|
||||||
"any.required": "This field is required",
|
"any.required": "Notification type is required",
|
||||||
|
"any.only": "Notification type must be email, webhook, or pager_duty",
|
||||||
|
}),
|
||||||
|
|
||||||
|
address: joi.when("type", {
|
||||||
|
is: "email",
|
||||||
|
then: joi
|
||||||
|
.string()
|
||||||
|
.email({ tlds: { allow: false } })
|
||||||
|
.required()
|
||||||
|
.messages({
|
||||||
|
"string.empty": "E-mail address cannot be empty",
|
||||||
|
"any.required": "E-mail address is required",
|
||||||
|
"string.email": "Please enter a valid e-mail address",
|
||||||
|
}),
|
||||||
|
otherwise: joi.string().uri().required().messages({
|
||||||
|
"string.empty": "Webhook URL cannot be empty",
|
||||||
|
"any.required": "Webhook URL is required",
|
||||||
|
"string.uri": "Please enter a valid Webhook URL",
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -229,6 +229,9 @@
|
|||||||
"unknownError": "Unknown error"
|
"unknownError": "Unknown error"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"general": {
|
||||||
|
"noOptionsFound": "No {{unit}} found"
|
||||||
|
},
|
||||||
"commonSave": "Save",
|
"commonSave": "Save",
|
||||||
"commonSaving": "Saving...",
|
"commonSaving": "Saving...",
|
||||||
"companyName": "Company name",
|
"companyName": "Company name",
|
||||||
@@ -443,7 +446,7 @@
|
|||||||
"inviteNoTokenFound": "No invite token found",
|
"inviteNoTokenFound": "No invite token found",
|
||||||
"loginHere": "Login here",
|
"loginHere": "Login here",
|
||||||
"logsPage": {
|
"logsPage": {
|
||||||
"description": "This page shows the latest 1000 lines of logs from the Checkmate server",
|
"description": "System logs - last 1000 lines",
|
||||||
"logLevelSelect": {
|
"logLevelSelect": {
|
||||||
"title": "Log level",
|
"title": "Log level",
|
||||||
"values": {
|
"values": {
|
||||||
@@ -456,13 +459,35 @@
|
|||||||
},
|
},
|
||||||
"tabs": {
|
"tabs": {
|
||||||
"logs": "Server logs",
|
"logs": "Server logs",
|
||||||
"queue": "Job queue"
|
"queue": "Job queue",
|
||||||
|
"diagnostics": "Diagnostics"
|
||||||
},
|
},
|
||||||
"title": "Logs",
|
"title": "Logs",
|
||||||
"toast": {
|
"toast": {
|
||||||
"fetchLogsSuccess": "Logs fetched successfully"
|
"fetchLogsSuccess": "Logs fetched successfully"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"diagnosticsPage": {
|
||||||
|
"diagnosticDescription": "System diagnostics",
|
||||||
|
"statsDescription": "System statistics",
|
||||||
|
"gauges": {
|
||||||
|
"heapAllocationTitle": "Heap allocation",
|
||||||
|
"heapAllocationSubtitle": "% of available memory",
|
||||||
|
"heapUsageTitle": "Heap usage",
|
||||||
|
"heapUsageSubtitle": "% of available memory",
|
||||||
|
"heapUtilizationTitle": "Heap utilization",
|
||||||
|
"heapUtilizationSubtitle": "% of allocated",
|
||||||
|
"instantCpuUsageTitle": "Instant CPU usage",
|
||||||
|
"instantCpuUsageSubtitle": "% of 1s used by CPU"
|
||||||
|
},
|
||||||
|
"stats": {
|
||||||
|
"eventLoopDelayTitle": "Event loop delay",
|
||||||
|
"uptimeTitle": "Uptime",
|
||||||
|
"usedHeapSizeTitle": "Used heap size",
|
||||||
|
"totalHeapSizeTitle": "Total heap size",
|
||||||
|
"osMemoryLimitTitle": "OS Memory Limit"
|
||||||
|
}
|
||||||
|
},
|
||||||
"low": "low",
|
"low": "low",
|
||||||
"maintenance": "maintenance",
|
"maintenance": "maintenance",
|
||||||
"maintenanceRepeat": "Maintenance Repeat",
|
"maintenanceRepeat": "Maintenance Repeat",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createAnnouncementValidation } from "../validation/joi.js";
|
import { createAnnouncementValidation } from "../validation/joi.js";
|
||||||
import { handleError } from "./controllerUtils.js";
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "announcementController";
|
const SERVICE_NAME = "announcementController";
|
||||||
|
|
||||||
@@ -28,16 +28,10 @@ class AnnouncementController {
|
|||||||
*
|
*
|
||||||
* @returns {Promise<void>} A promise that resolves once the response is sent.
|
* @returns {Promise<void>} A promise that resolves once the response is sent.
|
||||||
*/
|
*/
|
||||||
createAnnouncement = async (req, res, next) => {
|
createAnnouncement = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createAnnouncementValidation.validateAsync(req.body);
|
await createAnnouncementValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
const { title, message } = req.body;
|
||||||
return next(handleError(error, SERVICE_NAME)); // Handle Joi validation errors
|
|
||||||
}
|
|
||||||
|
|
||||||
const { title, message } = req.body;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const announcementData = {
|
const announcementData = {
|
||||||
title: title.trim(),
|
title: title.trim(),
|
||||||
message: message.trim(),
|
message: message.trim(),
|
||||||
@@ -49,10 +43,10 @@ class AnnouncementController {
|
|||||||
msg: this.stringService.createAnnouncement,
|
msg: this.stringService.createAnnouncement,
|
||||||
data: newAnnouncement,
|
data: newAnnouncement,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createAnnouncement"));
|
SERVICE_NAME,
|
||||||
}
|
"createAnnouncement"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles retrieving announcements with pagination.
|
* Handles retrieving announcements with pagination.
|
||||||
@@ -63,17 +57,17 @@ class AnnouncementController {
|
|||||||
* - `msg`: A message about the success of the request.
|
* - `msg`: A message about the success of the request.
|
||||||
* @param {Function} next - The next middleware function in the stack for error handling.
|
* @param {Function} next - The next middleware function in the stack for error handling.
|
||||||
*/
|
*/
|
||||||
getAnnouncement = async (req, res, next) => {
|
getAnnouncement = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const allAnnouncements = await this.db.getAnnouncements();
|
const allAnnouncements = await this.db.getAnnouncements();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.getAnnouncement,
|
msg: this.stringService.getAnnouncement,
|
||||||
data: allAnnouncements,
|
data: allAnnouncements,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getAnnouncement"));
|
SERVICE_NAME,
|
||||||
}
|
"getAnnouncement"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AnnouncementController;
|
export default AnnouncementController;
|
||||||
@@ -10,7 +10,8 @@ import {
|
|||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||||
import crypto from "crypto";
|
import crypto from "crypto";
|
||||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
import { asyncHandler, createAuthError, createError } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "authController";
|
const SERVICE_NAME = "authController";
|
||||||
|
|
||||||
class AuthController {
|
class AuthController {
|
||||||
@@ -32,15 +33,10 @@ class AuthController {
|
|||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
issueToken = (payload, appSettings) => {
|
issueToken = (payload, appSettings) => {
|
||||||
try {
|
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
||||||
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
const tokenSecret = appSettings?.jwtSecret;
|
||||||
const tokenSecret = appSettings?.jwtSecret;
|
const payloadData = payload;
|
||||||
const payloadData = payload;
|
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
||||||
|
|
||||||
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
|
||||||
} catch (error) {
|
|
||||||
throw handleError(error, SERVICE_NAME, "issueToken");
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,19 +51,14 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
|
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
registerUser = async (req, res, next) => {
|
registerUser = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
if (req.body?.email) {
|
if (req.body?.email) {
|
||||||
req.body.email = req.body.email?.toLowerCase();
|
req.body.email = req.body.email?.toLowerCase();
|
||||||
}
|
}
|
||||||
await registrationBodyValidation.validateAsync(req.body);
|
await registrationBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
// Create a new user
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Create a new user
|
|
||||||
try {
|
|
||||||
const user = req.body;
|
const user = req.body;
|
||||||
// If superAdmin exists, a token should be attached to all further register requests
|
// If superAdmin exists, a token should be attached to all further register requests
|
||||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||||
@@ -123,10 +114,10 @@ class AuthController {
|
|||||||
msg: this.stringService.authCreateUser,
|
msg: this.stringService.authCreateUser,
|
||||||
data: { user: newUser, token: token },
|
data: { user: newUser, token: token },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "registerController"));
|
SERVICE_NAME,
|
||||||
}
|
"registerUser"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs in a user by validating the user's credentials and issuing a JWT token.
|
* Logs in a user by validating the user's credentials and issuing a JWT token.
|
||||||
@@ -140,18 +131,13 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
|
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
||||||
*/
|
*/
|
||||||
loginUser = async (req, res, next) => {
|
loginUser = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
if (req.body?.email) {
|
if (req.body?.email) {
|
||||||
req.body.email = req.body.email?.toLowerCase();
|
req.body.email = req.body.email?.toLowerCase();
|
||||||
}
|
}
|
||||||
await loginValidation.validateAsync(req.body);
|
await loginValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const { email, password } = req.body;
|
const { email, password } = req.body;
|
||||||
|
|
||||||
// Check if user exists
|
// Check if user exists
|
||||||
@@ -160,10 +146,7 @@ class AuthController {
|
|||||||
// Compare password
|
// Compare password
|
||||||
const match = await user.comparePassword(password);
|
const match = await user.comparePassword(password);
|
||||||
if (match !== true) {
|
if (match !== true) {
|
||||||
const error = new Error(this.stringService.authIncorrectPassword);
|
throw createAuthError(this.stringService.authIncorrectPassword);
|
||||||
error.status = 401;
|
|
||||||
next(error);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove password from user object. Should this be abstracted to DB layer?
|
// Remove password from user object. Should this be abstracted to DB layer?
|
||||||
@@ -184,11 +167,10 @@ class AuthController {
|
|||||||
token: token,
|
token: token,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
error.status = 401;
|
SERVICE_NAME,
|
||||||
next(handleError(error, SERVICE_NAME, "loginUser"));
|
"loginUser"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
|
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
|
||||||
@@ -204,26 +186,16 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
|
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
||||||
*/
|
*/
|
||||||
editUser = async (req, res, next) => {
|
editUser = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await editUserParamValidation.validateAsync(req.params);
|
await editUserParamValidation.validateAsync(req.params);
|
||||||
await editUserBodyValidation.validateAsync(req.body);
|
await editUserBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO is this neccessary any longer? Verify ownership middleware should handle this
|
// TODO is this neccessary any longer? Verify ownership middleware should handle this
|
||||||
if (req.params.userId !== req.user._id.toString()) {
|
if (req.params.userId !== req.user._id.toString()) {
|
||||||
const error = new Error(this.stringService.unauthorized);
|
throw createAuthError(this.stringService.unauthorized);
|
||||||
error.status = 401;
|
}
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
next(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Change Password check
|
// Change Password check
|
||||||
if (req.body.password && req.body.newPassword) {
|
if (req.body.password && req.body.newPassword) {
|
||||||
// Get token from headers
|
// Get token from headers
|
||||||
@@ -240,10 +212,7 @@ class AuthController {
|
|||||||
// If not a match, throw a 403
|
// If not a match, throw a 403
|
||||||
// 403 instead of 401 to avoid triggering axios interceptor
|
// 403 instead of 401 to avoid triggering axios interceptor
|
||||||
if (!match) {
|
if (!match) {
|
||||||
const error = new Error(this.stringService.authIncorrectPassword);
|
throw createError(this.stringService.authIncorrectPassword, 403);
|
||||||
error.status = 403;
|
|
||||||
next(error);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
// If a match, update the password
|
// If a match, update the password
|
||||||
req.body.password = req.body.newPassword;
|
req.body.password = req.body.newPassword;
|
||||||
@@ -254,10 +223,10 @@ class AuthController {
|
|||||||
msg: this.stringService.authUpdateUser,
|
msg: this.stringService.authUpdateUser,
|
||||||
data: updatedUser,
|
data: updatedUser,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "userEditController"));
|
SERVICE_NAME,
|
||||||
}
|
"editUser"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if a superadmin account exists in the database.
|
* Checks if a superadmin account exists in the database.
|
||||||
@@ -268,18 +237,17 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
|
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
|
||||||
* @throws {Error} If there is an error during the process.
|
* @throws {Error} If there is an error during the process.
|
||||||
*/
|
*/
|
||||||
checkSuperadminExists = async (req, res, next) => {
|
checkSuperadminExists = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
const superAdminExists = await this.db.checkSuperadmin(req, res);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.authAdminExists,
|
msg: this.stringService.authAdminExists,
|
||||||
data: superAdminExists,
|
data: superAdminExists,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
|
SERVICE_NAME,
|
||||||
}
|
"checkSuperadminExists"
|
||||||
};
|
);
|
||||||
/**
|
/**
|
||||||
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
|
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
|
||||||
* @async
|
* @async
|
||||||
@@ -291,16 +259,9 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
|
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
requestRecovery = async (req, res, next) => {
|
requestRecovery = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await recoveryValidation.validateAsync(req.body);
|
await recoveryValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { email } = req.body;
|
const { email } = req.body;
|
||||||
const user = await this.db.getUserByEmail(email);
|
const user = await this.db.getUserByEmail(email);
|
||||||
const recoveryToken = await this.db.requestRecoveryToken(req, res);
|
const recoveryToken = await this.db.requestRecoveryToken(req, res);
|
||||||
@@ -323,10 +284,10 @@ class AuthController {
|
|||||||
msg: this.stringService.authCreateRecoveryToken,
|
msg: this.stringService.authCreateRecoveryToken,
|
||||||
data: msgId,
|
data: msgId,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
|
SERVICE_NAME,
|
||||||
}
|
"requestRecovery"
|
||||||
};
|
);
|
||||||
/**
|
/**
|
||||||
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
|
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
|
||||||
* @async
|
* @async
|
||||||
@@ -338,25 +299,17 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
|
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
validateRecovery = async (req, res, next) => {
|
validateRecovery = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await recoveryTokenValidation.validateAsync(req.body);
|
await recoveryTokenValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.db.validateRecoveryToken(req, res);
|
await this.db.validateRecoveryToken(req, res);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.authVerifyRecoveryToken,
|
msg: this.stringService.authVerifyRecoveryToken,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
|
SERVICE_NAME,
|
||||||
}
|
"validateRecovery"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
|
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
|
||||||
@@ -370,27 +323,20 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
|
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
resetPassword = async (req, res, next) => {
|
resetPassword = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await newPasswordValidation.validateAsync(req.body);
|
await newPasswordValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
const validationError = handleValidationError(error, SERVICE_NAME);
|
|
||||||
next(validationError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const user = await this.db.resetPassword(req, res);
|
const user = await this.db.resetPassword(req, res);
|
||||||
const appSettings = await this.settingsService.getSettings();
|
const appSettings = await this.settingsService.getSettings();
|
||||||
const token = this.issueToken(user._doc, appSettings);
|
const token = this.issueToken(user._doc, appSettings);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.authResetPassword,
|
msg: this.stringService.authResetPassword,
|
||||||
data: { user, token },
|
data: { user, token },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
|
SERVICE_NAME,
|
||||||
}
|
"resetPassword"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes a user and all associated monitors, checks, and alerts.
|
* Deletes a user and all associated monitors, checks, and alerts.
|
||||||
@@ -401,8 +347,8 @@ class AuthController {
|
|||||||
* @returns {Object} The response object with success status and message.
|
* @returns {Object} The response object with success status and message.
|
||||||
* @throws {Error} If user validation fails or user is not found in the database.
|
* @throws {Error} If user validation fails or user is not found in the database.
|
||||||
*/
|
*/
|
||||||
deleteUser = async (req, res, next) => {
|
deleteUser = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const token = getTokenFromHeaders(req.headers);
|
const token = getTokenFromHeaders(req.headers);
|
||||||
const decodedToken = jwt.decode(token);
|
const decodedToken = jwt.decode(token);
|
||||||
const { email } = decodedToken;
|
const { email } = decodedToken;
|
||||||
@@ -430,23 +376,22 @@ class AuthController {
|
|||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.authDeleteUser,
|
msg: this.stringService.authDeleteUser,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteUserController"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteUser"
|
||||||
};
|
);
|
||||||
|
|
||||||
getAllUsers = async (req, res, next) => {
|
getAllUsers = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const allUsers = await this.db.getAllUsers(req, res);
|
const allUsers = await this.db.getAllUsers(req, res);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.authGetAllUsers,
|
msg: this.stringService.authGetAllUsers,
|
||||||
data: allUsers,
|
data: allUsers,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
|
SERVICE_NAME,
|
||||||
}
|
"getAllUsers"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AuthController;
|
export default AuthController;
|
||||||
@@ -12,9 +12,7 @@ import {
|
|||||||
ackAllChecksParamValidation,
|
ackAllChecksParamValidation,
|
||||||
ackAllChecksBodyValidation,
|
ackAllChecksBodyValidation,
|
||||||
} from "../validation/joi.js";
|
} from "../validation/joi.js";
|
||||||
import jwt from "jsonwebtoken";
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
|
||||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
|
||||||
|
|
||||||
const SERVICE_NAME = "checkController";
|
const SERVICE_NAME = "checkController";
|
||||||
|
|
||||||
@@ -25,16 +23,11 @@ class CheckController {
|
|||||||
this.stringService = stringService;
|
this.stringService = stringService;
|
||||||
}
|
}
|
||||||
|
|
||||||
createCheck = async (req, res, next) => {
|
createCheck = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createCheckParamValidation.validateAsync(req.params);
|
await createCheckParamValidation.validateAsync(req.params);
|
||||||
await createCheckBodyValidation.validateAsync(req.body);
|
await createCheckBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const checkData = { ...req.body };
|
const checkData = { ...req.body };
|
||||||
const check = await this.db.createCheck(checkData);
|
const check = await this.db.createCheck(checkData);
|
||||||
|
|
||||||
@@ -42,21 +35,16 @@ class CheckController {
|
|||||||
msg: this.stringService.checkCreate,
|
msg: this.stringService.checkCreate,
|
||||||
data: check,
|
data: check,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createCheck"));
|
SERVICE_NAME,
|
||||||
}
|
"createCheck"
|
||||||
};
|
);
|
||||||
|
|
||||||
getChecksByMonitor = async (req, res, next) => {
|
getChecksByMonitor = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getChecksParamValidation.validateAsync(req.params);
|
await getChecksParamValidation.validateAsync(req.params);
|
||||||
await getChecksQueryValidation.validateAsync(req.query);
|
await getChecksQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } =
|
let { type, sortOrder, dateRange, filter, ack, page, rowsPerPage, status } =
|
||||||
req.query;
|
req.query;
|
||||||
@@ -76,20 +64,16 @@ class CheckController {
|
|||||||
msg: this.stringService.checkGet,
|
msg: this.stringService.checkGet,
|
||||||
data: result,
|
data: result,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getChecks"));
|
SERVICE_NAME,
|
||||||
}
|
"getChecksByMonitor"
|
||||||
};
|
);
|
||||||
|
|
||||||
getChecksByTeam = async (req, res, next) => {
|
getChecksByTeam = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getTeamChecksParamValidation.validateAsync(req.params);
|
await getTeamChecksParamValidation.validateAsync(req.params);
|
||||||
await getTeamChecksQueryValidation.validateAsync(req.query);
|
await getTeamChecksQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = req.query;
|
let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = req.query;
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
|
|
||||||
@@ -106,33 +90,28 @@ class CheckController {
|
|||||||
msg: this.stringService.checkGet,
|
msg: this.stringService.checkGet,
|
||||||
data: checkData,
|
data: checkData,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
|
SERVICE_NAME,
|
||||||
}
|
"getChecksByTeam"
|
||||||
};
|
);
|
||||||
|
|
||||||
getChecksSummaryByTeamId = async (req, res, next) => {
|
getChecksSummaryByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const summary = await this.db.getChecksSummaryByTeamId({ teamId });
|
const summary = await this.db.getChecksSummaryByTeamId({ teamId });
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.checkGetSummary,
|
msg: this.stringService.checkGetSummary,
|
||||||
data: summary,
|
data: summary,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getChecksSummaryByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getChecksSummaryByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
ackCheck = async (req, res, next) => {
|
ackCheck = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await ackCheckBodyValidation.validateAsync(req.body);
|
await ackCheckBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { checkId } = req.params;
|
const { checkId } = req.params;
|
||||||
const { ack } = req.body;
|
const { ack } = req.body;
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
@@ -143,21 +122,16 @@ class CheckController {
|
|||||||
msg: this.stringService.checkUpdateStatus,
|
msg: this.stringService.checkUpdateStatus,
|
||||||
data: updatedCheck,
|
data: updatedCheck,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "ackCheck"));
|
SERVICE_NAME,
|
||||||
}
|
"ackCheck"
|
||||||
};
|
);
|
||||||
|
|
||||||
ackAllChecks = async (req, res, next) => {
|
ackAllChecks = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await ackAllChecksParamValidation.validateAsync(req.params);
|
await ackAllChecksParamValidation.validateAsync(req.params);
|
||||||
await ackAllChecksBodyValidation.validateAsync(req.body);
|
await ackAllChecksBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { monitorId, path } = req.params;
|
const { monitorId, path } = req.params;
|
||||||
const { ack } = req.body;
|
const { ack } = req.body;
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
@@ -168,40 +142,30 @@ class CheckController {
|
|||||||
msg: this.stringService.checkUpdateStatus,
|
msg: this.stringService.checkUpdateStatus,
|
||||||
data: updatedChecks,
|
data: updatedChecks,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "ackAllChecks"));
|
SERVICE_NAME,
|
||||||
}
|
"ackAllChecks"
|
||||||
};
|
);
|
||||||
|
|
||||||
deleteChecks = async (req, res, next) => {
|
deleteChecks = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await deleteChecksParamValidation.validateAsync(req.params);
|
await deleteChecksParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const deletedCount = await this.db.deleteChecks(req.params.monitorId);
|
const deletedCount = await this.db.deleteChecks(req.params.monitorId);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.checkDelete,
|
msg: this.stringService.checkDelete,
|
||||||
data: { deletedCount },
|
data: { deletedCount },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteChecks"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteChecks"
|
||||||
};
|
);
|
||||||
|
|
||||||
deleteChecksByTeamId = async (req, res, next) => {
|
deleteChecksByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const deletedCount = await this.db.deleteChecksByTeamId(teamId);
|
const deletedCount = await this.db.deleteChecksByTeamId(teamId);
|
||||||
|
|
||||||
@@ -209,23 +173,17 @@ class CheckController {
|
|||||||
msg: this.stringService.checkDelete,
|
msg: this.stringService.checkDelete,
|
||||||
data: { deletedCount },
|
data: { deletedCount },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteChecksByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
updateChecksTTL = async (req, res, next) => {
|
updateChecksTTL = asyncHandler(
|
||||||
const SECONDS_PER_DAY = 86400;
|
async (req, res, next) => {
|
||||||
|
const SECONDS_PER_DAY = 86400;
|
||||||
|
|
||||||
try {
|
|
||||||
await updateChecksTTLBodyValidation.validateAsync(req.body);
|
await updateChecksTTLBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get user's teamId
|
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
|
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
|
||||||
await this.db.updateChecksTTL(teamId, ttl);
|
await this.db.updateChecksTTL(teamId, ttl);
|
||||||
@@ -233,9 +191,9 @@ class CheckController {
|
|||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.checkUpdateTTL,
|
msg: this.stringService.checkUpdateTTL,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "updateTTL"));
|
SERVICE_NAME,
|
||||||
}
|
"updateChecksTtl"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
export default CheckController;
|
export default CheckController;
|
||||||
@@ -1,16 +1,4 @@
|
|||||||
const handleValidationError = (error, serviceName) => {
|
import { createServerError } from "../utils/errorUtils.js";
|
||||||
error.status = 422;
|
|
||||||
error.service = serviceName;
|
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
return error;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleError = (error, serviceName, method, status = 500) => {
|
|
||||||
error.status === undefined ? (error.status = status) : null;
|
|
||||||
error.service === undefined ? (error.service = serviceName) : null;
|
|
||||||
error.method === undefined ? (error.method = method) : null;
|
|
||||||
return error;
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchMonitorCertificate = async (sslChecker, monitor) => {
|
const fetchMonitorCertificate = async (sslChecker, monitor) => {
|
||||||
const monitorUrl = new URL(monitor.url);
|
const monitorUrl = new URL(monitor.url);
|
||||||
@@ -18,9 +6,9 @@ const fetchMonitorCertificate = async (sslChecker, monitor) => {
|
|||||||
const cert = await sslChecker(hostname);
|
const cert = await sslChecker(hostname);
|
||||||
// Throw an error if no cert or if cert.validTo is not present
|
// Throw an error if no cert or if cert.validTo is not present
|
||||||
if (cert?.validTo === null || cert?.validTo === undefined) {
|
if (cert?.validTo === null || cert?.validTo === undefined) {
|
||||||
throw new Error("Certificate not found");
|
throw createServerError("Certificate not found");
|
||||||
}
|
}
|
||||||
return cert;
|
return cert;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { handleValidationError, handleError, fetchMonitorCertificate };
|
export { fetchMonitorCertificate };
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
import { handleError } from "./controllerUtils.js";
|
import v8 from "v8";
|
||||||
|
import os from "os";
|
||||||
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "diagnosticController";
|
const SERVICE_NAME = "diagnosticController";
|
||||||
|
|
||||||
|
const obs = new PerformanceObserver((items) => {
|
||||||
|
const entry = items.getEntries()[0];
|
||||||
|
performance.clearMarks();
|
||||||
|
});
|
||||||
|
obs.observe({ entryTypes: ["measure"] });
|
||||||
class DiagnosticController {
|
class DiagnosticController {
|
||||||
constructor(db) {
|
constructor(db) {
|
||||||
this.db = db;
|
this.db = db;
|
||||||
@@ -9,20 +17,20 @@ class DiagnosticController {
|
|||||||
this.getDbStats = this.getDbStats.bind(this);
|
this.getDbStats = this.getDbStats.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMonitorsByTeamIdExecutionStats(req, res, next) {
|
getMonitorsByTeamIdExecutionStats = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const data = await this.db.getMonitorsByTeamIdExecutionStats(req);
|
const data = await this.db.getMonitorsByTeamIdExecutionStats(req);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: "OK",
|
msg: "OK",
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamIdExecutionStats"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorsByTeamIdExecutionStats"
|
||||||
}
|
);
|
||||||
|
|
||||||
async getDbStats(req, res, next) {
|
getDbStats = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { methodName, args = [] } = req.body;
|
const { methodName, args = [] } = req.body;
|
||||||
if (!methodName || !this.db[methodName]) {
|
if (!methodName || !this.db[methodName]) {
|
||||||
return res.error({
|
return res.error({
|
||||||
@@ -40,9 +48,87 @@ class DiagnosticController {
|
|||||||
msg: "OK",
|
msg: "OK",
|
||||||
data: stats,
|
data: stats,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getDbStats"));
|
SERVICE_NAME,
|
||||||
}
|
"getDbStats"
|
||||||
}
|
);
|
||||||
|
|
||||||
|
getCPUUsage = asyncHandler(
|
||||||
|
async (req, res, next) => {
|
||||||
|
const startUsage = process.cpuUsage();
|
||||||
|
const timingPeriod = 1000; // measured in ms
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
|
||||||
|
const endUsage = process.cpuUsage(startUsage);
|
||||||
|
const cpuUsage = {
|
||||||
|
userUsageMs: endUsage.user / 1000,
|
||||||
|
systemUsageMs: endUsage.system / 1000,
|
||||||
|
usagePercentage: ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100,
|
||||||
|
};
|
||||||
|
return cpuUsage;
|
||||||
|
},
|
||||||
|
SERVICE_NAME,
|
||||||
|
"getCPUUsage"
|
||||||
|
);
|
||||||
|
|
||||||
|
getSystemStats = asyncHandler(
|
||||||
|
async (req, res, next) => {
|
||||||
|
// Memory Usage
|
||||||
|
const totalMemory = os.totalmem();
|
||||||
|
const freeMemory = os.freemem();
|
||||||
|
|
||||||
|
const osStats = {
|
||||||
|
freeMemoryBytes: freeMemory, // bytes
|
||||||
|
totalMemoryBytes: totalMemory, // bytes
|
||||||
|
};
|
||||||
|
|
||||||
|
const used = process.memoryUsage();
|
||||||
|
const memoryUsage = {};
|
||||||
|
for (let key in used) {
|
||||||
|
memoryUsage[`${key}Mb`] = Math.round((used[key] / 1024 / 1024) * 100) / 100; // MB
|
||||||
|
}
|
||||||
|
|
||||||
|
// CPU Usage
|
||||||
|
const cpuMetrics = await this.getCPUUsage();
|
||||||
|
|
||||||
|
// V8 Heap Statistics
|
||||||
|
const heapStats = v8.getHeapStatistics();
|
||||||
|
const v8Metrics = {
|
||||||
|
totalHeapSizeBytes: heapStats.total_heap_size, // bytes
|
||||||
|
usedHeapSizeBytes: heapStats.used_heap_size, // bytes
|
||||||
|
heapSizeLimitBytes: heapStats.heap_size_limit, // bytes
|
||||||
|
};
|
||||||
|
|
||||||
|
// Event Loop Delay
|
||||||
|
let eventLoopDelay = 0;
|
||||||
|
performance.mark("start");
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
performance.mark("end");
|
||||||
|
performance.measure("eventLoopDelay", "start", "end");
|
||||||
|
const entries = performance.getEntriesByName("eventLoopDelay");
|
||||||
|
if (entries.length > 0) {
|
||||||
|
eventLoopDelay = entries[0].duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uptime
|
||||||
|
const uptimeMs = process.uptime() * 1000; // ms
|
||||||
|
|
||||||
|
// Combine Metrics
|
||||||
|
const diagnostics = {
|
||||||
|
osStats,
|
||||||
|
memoryUsage,
|
||||||
|
cpuUsage: cpuMetrics,
|
||||||
|
v8HeapStats: v8Metrics,
|
||||||
|
eventLoopDelayMs: eventLoopDelay,
|
||||||
|
uptimeMs,
|
||||||
|
};
|
||||||
|
|
||||||
|
return res.success({
|
||||||
|
msg: "OK",
|
||||||
|
data: diagnostics,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
SERVICE_NAME,
|
||||||
|
"getSystemStats"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
export default DiagnosticController;
|
export default DiagnosticController;
|
||||||
@@ -3,10 +3,9 @@ import {
|
|||||||
inviteBodyValidation,
|
inviteBodyValidation,
|
||||||
inviteVerificationBodyValidation,
|
inviteVerificationBodyValidation,
|
||||||
} from "../validation/joi.js";
|
} from "../validation/joi.js";
|
||||||
import logger from "../utils/logger.js";
|
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
|
||||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||||
|
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "inviteController";
|
const SERVICE_NAME = "inviteController";
|
||||||
|
|
||||||
@@ -31,99 +30,73 @@ class InviteController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
|
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
getInviteToken = async (req, res, next) => {
|
getInviteToken = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
// Only admins can invite
|
// Only admins can invite
|
||||||
const token = getTokenFromHeaders(req.headers);
|
const token = getTokenFromHeaders(req.headers);
|
||||||
const { role, teamId } = jwt.decode(token);
|
const { role, teamId } = jwt.decode(token);
|
||||||
req.body.teamId = teamId;
|
req.body.teamId = teamId;
|
||||||
try {
|
await inviteRoleValidation.validateAsync({ roles: role });
|
||||||
await inviteRoleValidation.validateAsync({ roles: role });
|
await inviteBodyValidation.validateAsync(req.body);
|
||||||
await inviteBodyValidation.validateAsync(req.body);
|
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.inviteIssued,
|
msg: this.stringService.inviteIssued,
|
||||||
data: inviteToken,
|
data: inviteToken,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "inviteController"));
|
SERVICE_NAME,
|
||||||
}
|
"getInviteToken"
|
||||||
};
|
);
|
||||||
|
|
||||||
sendInviteEmail = async (req, res, next) => {
|
sendInviteEmail = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
// Only admins can invite
|
// Only admins can invite
|
||||||
const token = getTokenFromHeaders(req.headers);
|
const token = getTokenFromHeaders(req.headers);
|
||||||
const { role, firstname, teamId } = jwt.decode(token);
|
const { role, firstname, teamId } = jwt.decode(token);
|
||||||
req.body.teamId = teamId;
|
req.body.teamId = teamId;
|
||||||
try {
|
await inviteRoleValidation.validateAsync({ roles: role });
|
||||||
await inviteRoleValidation.validateAsync({ roles: role });
|
await inviteBodyValidation.validateAsync(req.body);
|
||||||
await inviteBodyValidation.validateAsync(req.body);
|
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||||
const { clientHost } = this.settingsService.getSettings();
|
const { clientHost } = this.settingsService.getSettings();
|
||||||
|
|
||||||
try {
|
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
||||||
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
name: firstname,
|
||||||
name: firstname,
|
link: `${clientHost}/register/${inviteToken.token}`,
|
||||||
link: `${clientHost}/register/${inviteToken.token}`,
|
});
|
||||||
});
|
const result = await this.emailService.sendEmail(
|
||||||
const result = await this.emailService.sendEmail(
|
req.body.email,
|
||||||
req.body.email,
|
"Welcome to Uptime Monitor",
|
||||||
"Welcome to Uptime Monitor",
|
html
|
||||||
html
|
);
|
||||||
|
if (!result) {
|
||||||
|
throw createServerError(
|
||||||
|
"Failed to send invite e-mail... Please verify your settings."
|
||||||
);
|
);
|
||||||
if (!result) {
|
|
||||||
return res.error({
|
|
||||||
msg: "Failed to send invite e-mail... Please verify your settings.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.warn({
|
|
||||||
message: error.message,
|
|
||||||
service: SERVICE_NAME,
|
|
||||||
method: "sendInviteEmail",
|
|
||||||
stack: error.stack,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.inviteIssued,
|
msg: this.stringService.inviteIssued,
|
||||||
data: inviteToken,
|
data: inviteToken,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "inviteController"));
|
SERVICE_NAME,
|
||||||
}
|
"sendInviteEmail"
|
||||||
};
|
);
|
||||||
|
|
||||||
inviteVerifyController = async (req, res, next) => {
|
inviteVerifyController = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await inviteVerificationBodyValidation.validateAsync(req.body);
|
await inviteVerificationBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const invite = await this.db.getInviteToken(req.body.token);
|
const invite = await this.db.getInviteToken(req.body.token);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.inviteVerified,
|
msg: this.stringService.inviteVerified,
|
||||||
data: invite,
|
data: invite,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
|
SERVICE_NAME,
|
||||||
}
|
"inviteVerifyController"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default InviteController;
|
export default InviteController;
|
||||||
@@ -1,23 +1,22 @@
|
|||||||
import { handleError } from "./controllerUtils.js";
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "JobQueueController";
|
const SERVICE_NAME = "LogController";
|
||||||
|
|
||||||
class LogController {
|
class LogController {
|
||||||
constructor(logger) {
|
constructor(logger) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
getLogs = async (req, res, next) => {
|
getLogs = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const logs = await this.logger.getLogs();
|
const logs = await this.logger.getLogs();
|
||||||
res.success({
|
res.success({
|
||||||
msg: "Logs fetched successfully",
|
msg: "Logs fetched successfully",
|
||||||
data: logs,
|
data: logs,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getLogs"));
|
SERVICE_NAME,
|
||||||
return;
|
"getLogs"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
}
|
}
|
||||||
export default LogController;
|
export default LogController;
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
getMaintenanceWindowsByTeamIdQueryValidation,
|
getMaintenanceWindowsByTeamIdQueryValidation,
|
||||||
deleteMaintenanceWindowByIdParamValidation,
|
deleteMaintenanceWindowByIdParamValidation,
|
||||||
} from "../validation/joi.js";
|
} from "../validation/joi.js";
|
||||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "maintenanceWindowController";
|
const SERVICE_NAME = "maintenanceWindowController";
|
||||||
|
|
||||||
@@ -18,14 +18,10 @@ class MaintenanceWindowController {
|
|||||||
this.stringService = stringService;
|
this.stringService = stringService;
|
||||||
}
|
}
|
||||||
|
|
||||||
createMaintenanceWindows = async (req, res, next) => {
|
createMaintenanceWindows = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const monitorIds = req.body.monitors;
|
const monitorIds = req.body.monitors;
|
||||||
const dbTransactions = monitorIds.map((monitorId) => {
|
const dbTransactions = monitorIds.map((monitorId) => {
|
||||||
@@ -44,39 +40,28 @@ class MaintenanceWindowController {
|
|||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.maintenanceWindowCreate,
|
msg: this.stringService.maintenanceWindowCreate,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
|
SERVICE_NAME,
|
||||||
}
|
"createMaintenanceWindows"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMaintenanceWindowById = async (req, res, next) => {
|
getMaintenanceWindowById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
|
const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.maintenanceWindowGetById,
|
msg: this.stringService.maintenanceWindowGetById,
|
||||||
data: maintenanceWindow,
|
data: maintenanceWindow,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
|
SERVICE_NAME,
|
||||||
}
|
"getMaintenanceWindowById"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
getMaintenanceWindowsByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
|
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
|
||||||
teamId,
|
teamId,
|
||||||
@@ -87,20 +72,15 @@ class MaintenanceWindowController {
|
|||||||
msg: this.stringService.maintenanceWindowGetByTeam,
|
msg: this.stringService.maintenanceWindowGetByTeam,
|
||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
|
SERVICE_NAME,
|
||||||
}
|
"getMaintenanceWindowsByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
getMaintenanceWindowsByMonitorId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
|
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
|
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
|
||||||
req.params.monitorId
|
req.params.monitorId
|
||||||
);
|
);
|
||||||
@@ -109,37 +89,27 @@ class MaintenanceWindowController {
|
|||||||
msg: this.stringService.maintenanceWindowGetByUser,
|
msg: this.stringService.maintenanceWindowGetByUser,
|
||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
|
SERVICE_NAME,
|
||||||
}
|
"getMaintenanceWindowsByMonitorId"
|
||||||
};
|
);
|
||||||
|
|
||||||
deleteMaintenanceWindow = async (req, res, next) => {
|
deleteMaintenanceWindow = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await this.db.deleteMaintenanceWindowById(req.params.id);
|
await this.db.deleteMaintenanceWindowById(req.params.id);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.maintenanceWindowDelete,
|
msg: this.stringService.maintenanceWindowDelete,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteMaintenanceWindow"
|
||||||
};
|
);
|
||||||
|
|
||||||
editMaintenanceWindow = async (req, res, next) => {
|
editMaintenanceWindow = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
|
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
|
||||||
req.params.id,
|
req.params.id,
|
||||||
req.body
|
req.body
|
||||||
@@ -148,10 +118,10 @@ class MaintenanceWindowController {
|
|||||||
msg: this.stringService.maintenanceWindowEdit,
|
msg: this.stringService.maintenanceWindowEdit,
|
||||||
data: editedMaintenanceWindow,
|
data: editedMaintenanceWindow,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
|
SERVICE_NAME,
|
||||||
}
|
"editMaintenanceWindow"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default MaintenanceWindowController;
|
export default MaintenanceWindowController;
|
||||||
@@ -16,12 +16,12 @@ import {
|
|||||||
} from "../validation/joi.js";
|
} from "../validation/joi.js";
|
||||||
import sslChecker from "ssl-checker";
|
import sslChecker from "ssl-checker";
|
||||||
import logger from "../utils/logger.js";
|
import logger from "../utils/logger.js";
|
||||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import seedDb from "../db/mongo/utils/seedDb.js";
|
import seedDb from "../db/mongo/utils/seedDb.js";
|
||||||
const SERVICE_NAME = "monitorController";
|
|
||||||
import pkg from "papaparse";
|
import pkg from "papaparse";
|
||||||
|
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
|
const SERVICE_NAME = "monitorController";
|
||||||
class MonitorController {
|
class MonitorController {
|
||||||
constructor(db, settingsService, jobQueue, stringService, emailService) {
|
constructor(db, settingsService, jobQueue, stringService, emailService) {
|
||||||
this.db = db;
|
this.db = db;
|
||||||
@@ -40,17 +40,17 @@ class MonitorController {
|
|||||||
* @returns {Promise<Express.Response>}
|
* @returns {Promise<Express.Response>}
|
||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
getAllMonitors = async (req, res, next) => {
|
getAllMonitors = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const monitors = await this.db.getAllMonitors();
|
const monitors = await this.db.getAllMonitors();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.monitorGetAll,
|
msg: this.stringService.monitorGetAll,
|
||||||
data: monitors,
|
data: monitors,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
|
SERVICE_NAME,
|
||||||
}
|
"getAllMonitors"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all monitors with uptime stats for 1,7,30, and 90 days
|
* Returns all monitors with uptime stats for 1,7,30, and 90 days
|
||||||
@@ -61,20 +61,20 @@ class MonitorController {
|
|||||||
* @returns {Promise<Express.Response>}
|
* @returns {Promise<Express.Response>}
|
||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
getAllMonitorsWithUptimeStats = async (req, res, next) => {
|
getAllMonitorsWithUptimeStats = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const monitors = await this.db.getAllMonitorsWithUptimeStats();
|
const monitors = await this.db.getAllMonitorsWithUptimeStats();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.monitorGetAll,
|
msg: this.stringService.monitorGetAll,
|
||||||
data: monitors,
|
data: monitors,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getAllMonitorsWithUptimeStats"));
|
SERVICE_NAME,
|
||||||
}
|
"getAllMonitorsWithUptimeStats"
|
||||||
};
|
);
|
||||||
|
|
||||||
getUptimeDetailsById = async (req, res, next) => {
|
getUptimeDetailsById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
const { dateRange, normalize } = req.query;
|
const { dateRange, normalize } = req.query;
|
||||||
|
|
||||||
@@ -87,10 +87,10 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorGetByIdSuccess,
|
msg: this.stringService.monitorGetByIdSuccess,
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorDetailsById"));
|
SERVICE_NAME,
|
||||||
}
|
"getUptimeDetailsById"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns monitor stats for monitor with matching ID
|
* Returns monitor stats for monitor with matching ID
|
||||||
@@ -101,16 +101,11 @@ class MonitorController {
|
|||||||
* @returns {Promise<Express.Response>}
|
* @returns {Promise<Express.Response>}
|
||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
getMonitorStatsById = async (req, res, next) => {
|
getMonitorStatsById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
|
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
|
|
||||||
@@ -126,10 +121,10 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorStatsById,
|
msg: this.stringService.monitorStatsById,
|
||||||
data: monitorStats,
|
data: monitorStats,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorStatsById"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get hardware details for a specific monitor by ID
|
* Get hardware details for a specific monitor by ID
|
||||||
@@ -140,15 +135,11 @@ class MonitorController {
|
|||||||
* @returns {Promise<Express.Response>}
|
* @returns {Promise<Express.Response>}
|
||||||
* @throws {Error} - Throws error if monitor not found or other database errors
|
* @throws {Error} - Throws error if monitor not found or other database errors
|
||||||
*/
|
*/
|
||||||
getHardwareDetailsById = async (req, res, next) => {
|
getHardwareDetailsById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getHardwareDetailsByIdParamValidation.validateAsync(req.params);
|
await getHardwareDetailsByIdParamValidation.validateAsync(req.params);
|
||||||
await getHardwareDetailsByIdQueryValidation.validateAsync(req.query);
|
await getHardwareDetailsByIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
const { dateRange } = req.query;
|
const { dateRange } = req.query;
|
||||||
const monitor = await this.db.getHardwareDetailsById({ monitorId, dateRange });
|
const monitor = await this.db.getHardwareDetailsById({ monitorId, dateRange });
|
||||||
@@ -156,19 +147,15 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorGetByIdSuccess,
|
msg: this.stringService.monitorGetByIdSuccess,
|
||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getHardwareDetailsById"));
|
SERVICE_NAME,
|
||||||
}
|
"getHardwareDetailsById"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
|
getMonitorCertificate = asyncHandler(
|
||||||
try {
|
async (req, res, next, fetchMonitorCertificate) => {
|
||||||
await getCertificateParamValidation.validateAsync(req.params);
|
await getCertificateParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
const monitor = await this.db.getMonitorById(monitorId);
|
const monitor = await this.db.getMonitorById(monitorId);
|
||||||
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
const certificate = await fetchMonitorCertificate(sslChecker, monitor);
|
||||||
@@ -179,10 +166,10 @@ class MonitorController {
|
|||||||
certificateDate: new Date(certificate.validTo),
|
certificateDate: new Date(certificate.validTo),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorCertificate"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a monitor by its ID.
|
* Retrieves a monitor by its ID.
|
||||||
@@ -195,25 +182,20 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
|
* @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
|
||||||
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
getMonitorById = async (req, res, next) => {
|
getMonitorById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const monitor = await this.db.getMonitorById(req.params.monitorId);
|
const monitor = await this.db.getMonitorById(req.params.monitorId);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.monitorGetByIdSuccess,
|
msg: this.stringService.monitorGetByIdSuccess,
|
||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorById"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorById"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new monitor and adds it to the job queue.
|
* Creates a new monitor and adds it to the job queue.
|
||||||
@@ -226,15 +208,10 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data.
|
* @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
createMonitor = async (req, res, next) => {
|
createMonitor = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createMonitorBodyValidation.validateAsync(req.body);
|
await createMonitorBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { _id, teamId } = req.user;
|
const { _id, teamId } = req.user;
|
||||||
const monitor = await this.db.createMonitor({
|
const monitor = await this.db.createMonitor({
|
||||||
body: req.body,
|
body: req.body,
|
||||||
@@ -248,10 +225,10 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorCreate,
|
msg: this.stringService.monitorCreate,
|
||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createMonitor"));
|
SERVICE_NAME,
|
||||||
}
|
"createMonitor"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates bulk monitors and adds them to the job queue after parsing CSV.
|
* Creates bulk monitors and adds them to the job queue after parsing CSV.
|
||||||
@@ -263,8 +240,8 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status and message.
|
* @returns {Object} The response object with a success status and message.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
createBulkMonitors = async (req, res, next) => {
|
createBulkMonitors = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { parse } = pkg;
|
const { parse } = pkg;
|
||||||
|
|
||||||
// validate the file
|
// validate the file
|
||||||
@@ -310,51 +287,43 @@ class MonitorController {
|
|||||||
return value;
|
return value;
|
||||||
},
|
},
|
||||||
complete: async ({ data, errors }) => {
|
complete: async ({ data, errors }) => {
|
||||||
try {
|
if (errors.length > 0) {
|
||||||
if (errors.length > 0) {
|
throw createServerError("Error parsing CSV");
|
||||||
throw new Error("Error parsing CSV");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!data || data.length === 0) {
|
|
||||||
throw new Error("CSV file contains no data rows");
|
|
||||||
}
|
|
||||||
|
|
||||||
const enrichedData = data.map((monitor) => ({
|
|
||||||
userId: _id,
|
|
||||||
teamId,
|
|
||||||
...monitor,
|
|
||||||
description: monitor.description || monitor.name || monitor.url,
|
|
||||||
name: monitor.name || monitor.url,
|
|
||||||
type: monitor.type || "http",
|
|
||||||
}));
|
|
||||||
|
|
||||||
await createMonitorsBodyValidation.validateAsync(enrichedData);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const monitors = await this.db.createBulkMonitors(enrichedData);
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
monitors.map(async (monitor, index) => {
|
|
||||||
this.jobQueue.addJob(monitor._id, monitor);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
return res.success({
|
|
||||||
msg: this.stringService.bulkMonitorsCreate,
|
|
||||||
data: monitors,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
throw createServerError("CSV file contains no data rows");
|
||||||
|
}
|
||||||
|
|
||||||
|
const enrichedData = data.map((monitor) => ({
|
||||||
|
userId: _id,
|
||||||
|
teamId,
|
||||||
|
...monitor,
|
||||||
|
description: monitor.description || monitor.name || monitor.url,
|
||||||
|
name: monitor.name || monitor.url,
|
||||||
|
type: monitor.type || "http",
|
||||||
|
}));
|
||||||
|
|
||||||
|
await createMonitorsBodyValidation.validateAsync(enrichedData);
|
||||||
|
|
||||||
|
const monitors = await this.db.createBulkMonitors(enrichedData);
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
monitors.map(async (monitor, index) => {
|
||||||
|
this.jobQueue.addJob(monitor._id, monitor);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.success({
|
||||||
|
msg: this.stringService.bulkMonitorsCreate,
|
||||||
|
data: monitors,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
return next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
SERVICE_NAME,
|
||||||
}
|
"createBulkMonitors"
|
||||||
};
|
);
|
||||||
/**
|
/**
|
||||||
* Checks if the endpoint can be resolved
|
* Checks if the endpoint can be resolved
|
||||||
* @async
|
* @async
|
||||||
@@ -365,15 +334,9 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message, and the resolution result.
|
* @returns {Object} The response object with a success status, a message, and the resolution result.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
checkEndpointResolution = async (req, res, next) => {
|
checkEndpointResolution = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorURLByQueryValidation.validateAsync(req.query);
|
await getMonitorURLByQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { monitorURL } = req.query;
|
const { monitorURL } = req.query;
|
||||||
const parsedUrl = new URL(monitorURL);
|
const parsedUrl = new URL(monitorURL);
|
||||||
const response = await axios.get(parsedUrl, {
|
const response = await axios.get(parsedUrl, {
|
||||||
@@ -384,10 +347,10 @@ class MonitorController {
|
|||||||
status: response.status,
|
status: response.status,
|
||||||
msg: response.statusText,
|
msg: response.statusText,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
|
SERVICE_NAME,
|
||||||
}
|
"checkEndpointResolution"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
|
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
|
||||||
@@ -400,24 +363,18 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status and a message indicating the deletion of the monitor.
|
* @returns {Object} The response object with a success status and a message indicating the deletion of the monitor.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
|
||||||
*/
|
*/
|
||||||
deleteMonitor = async (req, res, next) => {
|
deleteMonitor = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const monitorId = req.params.monitorId;
|
const monitorId = req.params.monitorId;
|
||||||
const monitor = await this.db.deleteMonitor({ monitorId });
|
const monitor = await this.db.deleteMonitor({ monitorId });
|
||||||
await this.jobQueue.deleteJob(monitor);
|
await this.jobQueue.deleteJob(monitor);
|
||||||
await this.db.deleteStatusPagesByMonitorId(monitor._id);
|
await this.db.deleteStatusPagesByMonitorId(monitor._id);
|
||||||
return res.success({ msg: this.stringService.monitorDelete });
|
return res.success({ msg: this.stringService.monitorDelete });
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteMonitor"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes all monitors associated with a team.
|
* Deletes all monitors associated with a team.
|
||||||
@@ -430,8 +387,8 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors.
|
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors.
|
||||||
* @throws {Error} If there is an error during the deletion process.
|
* @throws {Error} If there is an error during the deletion process.
|
||||||
*/
|
*/
|
||||||
deleteAllMonitors = async (req, res, next) => {
|
deleteAllMonitors = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
|
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
@@ -442,7 +399,7 @@ class MonitorController {
|
|||||||
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
|
||||||
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
await this.db.deleteNotificationsByMonitorId(monitor._id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error({
|
logger.warn({
|
||||||
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
|
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "deleteAllMonitors",
|
method: "deleteAllMonitors",
|
||||||
@@ -452,10 +409,10 @@ class MonitorController {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
return res.success({ msg: `Deleted ${deletedCount} monitors` });
|
return res.success({ msg: `Deleted ${deletedCount} monitors` });
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteAllMonitors"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
|
* Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
|
||||||
@@ -470,16 +427,10 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
|
* @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
|
||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
editMonitor = async (req, res, next) => {
|
editMonitor = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
await editMonitorBodyValidation.validateAsync(req.body);
|
await editMonitorBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { monitorId } = req.params;
|
const { monitorId } = req.params;
|
||||||
|
|
||||||
const editedMonitor = await this.db.editMonitor(monitorId, req.body);
|
const editedMonitor = await this.db.editMonitor(monitorId, req.body);
|
||||||
@@ -490,10 +441,10 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorEdit,
|
msg: this.stringService.monitorEdit,
|
||||||
data: editedMonitor,
|
data: editedMonitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "editMonitor"));
|
SERVICE_NAME,
|
||||||
}
|
"editMonitor"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pauses or resumes a monitor based on its current state.
|
* Pauses or resumes a monitor based on its current state.
|
||||||
@@ -506,14 +457,10 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
|
* @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
|
||||||
* @throws {Error} If there is an error during the process.
|
* @throws {Error} If there is an error during the process.
|
||||||
*/
|
*/
|
||||||
pauseMonitor = async (req, res, next) => {
|
pauseMonitor = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await pauseMonitorParamValidation.validateAsync(req.params);
|
await pauseMonitorParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const monitorId = req.params.monitorId;
|
const monitorId = req.params.monitorId;
|
||||||
const monitor = await this.db.pauseMonitor({ monitorId });
|
const monitor = await this.db.pauseMonitor({ monitorId });
|
||||||
monitor.isActive === true
|
monitor.isActive === true
|
||||||
@@ -526,10 +473,10 @@ class MonitorController {
|
|||||||
: this.stringService.monitorPause,
|
: this.stringService.monitorPause,
|
||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "pauseMonitor"));
|
SERVICE_NAME,
|
||||||
}
|
"pauseMonitor"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds demo monitors for a team.
|
* Adds demo monitors for a team.
|
||||||
@@ -542,8 +489,8 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added.
|
* @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added.
|
||||||
* @throws {Error} If there is an error during the process.
|
* @throws {Error} If there is an error during the process.
|
||||||
*/
|
*/
|
||||||
addDemoMonitors = async (req, res, next) => {
|
addDemoMonitors = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { _id, teamId } = req.user;
|
const { _id, teamId } = req.user;
|
||||||
const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
|
const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
@@ -554,10 +501,10 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorDemoAdded,
|
msg: this.stringService.monitorDemoAdded,
|
||||||
data: demoMonitors.length,
|
data: demoMonitors.length,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
|
SERVICE_NAME,
|
||||||
}
|
"addDemoMonitors"
|
||||||
};
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a test email to verify email delivery functionality.
|
* Sends a test email to verify email delivery functionality.
|
||||||
@@ -570,8 +517,8 @@ class MonitorController {
|
|||||||
* @returns {Object} The response object with a success status and the email delivery message ID.
|
* @returns {Object} The response object with a success status and the email delivery message ID.
|
||||||
* @throws {Error} If there is an error while sending the test email.
|
* @throws {Error} If there is an error while sending the test email.
|
||||||
*/
|
*/
|
||||||
sendTestEmail = async (req, res, next) => {
|
sendTestEmail = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { to } = req.body;
|
const { to } = req.body;
|
||||||
if (!to || typeof to !== "string") {
|
if (!to || typeof to !== "string") {
|
||||||
throw new Error(this.stringService.errorForValidEmailAddress);
|
throw new Error(this.stringService.errorForValidEmailAddress);
|
||||||
@@ -584,29 +531,23 @@ class MonitorController {
|
|||||||
const messageId = await this.emailService.sendEmail(to, subject, html);
|
const messageId = await this.emailService.sendEmail(to, subject, html);
|
||||||
|
|
||||||
if (!messageId) {
|
if (!messageId) {
|
||||||
return res.error({
|
throw createServerError("Failed to send test email.");
|
||||||
msg: "Failed to send test email.",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.sendTestEmail,
|
msg: this.stringService.sendTestEmail,
|
||||||
data: { messageId },
|
data: { messageId },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "sendTestEmail"));
|
SERVICE_NAME,
|
||||||
}
|
"sendTestEmail"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMonitorsByTeamId = async (req, res, next) => {
|
getMonitorsByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
||||||
const teamId = req.user.teamId;
|
const teamId = req.user.teamId;
|
||||||
|
|
||||||
@@ -624,20 +565,16 @@ class MonitorController {
|
|||||||
msg: this.stringService.monitorGetByTeamId,
|
msg: this.stringService.monitorGetByTeamId,
|
||||||
data: monitors,
|
data: monitors,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorsByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
getMonitorsAndSummaryByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
return next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { explain } = req;
|
const { explain } = req;
|
||||||
const { type } = req.query;
|
const { type } = req.query;
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
@@ -651,20 +588,16 @@ class MonitorController {
|
|||||||
msg: "OK", // TODO
|
msg: "OK", // TODO
|
||||||
data: result,
|
data: result,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
return next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorsAndSummaryByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
getMonitorsWithChecksByTeamId = async (req, res, next) => {
|
getMonitorsWithChecksByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
await getMonitorsByTeamIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
return next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { explain } = req;
|
const { explain } = req;
|
||||||
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
@@ -684,23 +617,23 @@ class MonitorController {
|
|||||||
msg: "OK",
|
msg: "OK",
|
||||||
data: result,
|
data: result,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
return next(handleError(error, SERVICE_NAME, "getMonitorsWithChecksByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getMonitorsWithChecksByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
seedDb = async (req, res, next) => {
|
seedDb = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { _id, teamId } = req.user;
|
const { _id, teamId } = req.user;
|
||||||
await seedDb(_id, teamId);
|
await seedDb(_id, teamId);
|
||||||
res.success({ msg: "Database seeded" });
|
res.success({ msg: "Database seeded" });
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "seedDb"));
|
SERVICE_NAME,
|
||||||
}
|
"seedDb"
|
||||||
};
|
);
|
||||||
|
|
||||||
exportMonitorsToCSV = async (req, res, next) => {
|
exportMonitorsToCSV = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { teamId } = req.user;
|
const { teamId } = req.user;
|
||||||
|
|
||||||
const monitors = await this.db.getMonitorsByTeamId({ teamId });
|
const monitors = await this.db.getMonitorsByTeamId({ teamId });
|
||||||
@@ -730,10 +663,10 @@ class MonitorController {
|
|||||||
"Content-Disposition": "attachment; filename=monitors.csv",
|
"Content-Disposition": "attachment; filename=monitors.csv",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "exportMonitorsToCSV"));
|
SERVICE_NAME,
|
||||||
}
|
"exportMonitorsToCSV"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default MonitorController;
|
export default MonitorController;
|
||||||
@@ -1,22 +1,8 @@
|
|||||||
import {
|
import { createNotificationBodyValidation } from "../validation/joi.js";
|
||||||
triggerNotificationBodyValidation,
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
createNotificationBodyValidation,
|
|
||||||
} from "../validation/joi.js";
|
|
||||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
|
||||||
|
|
||||||
const SERVICE_NAME = "NotificationController";
|
const SERVICE_NAME = "NotificationController";
|
||||||
|
|
||||||
const NOTIFICATION_TYPES = {
|
|
||||||
WEBHOOK: "webhook",
|
|
||||||
TELEGRAM: "telegram",
|
|
||||||
};
|
|
||||||
|
|
||||||
const PLATFORMS = {
|
|
||||||
SLACK: "slack",
|
|
||||||
DISCORD: "discord",
|
|
||||||
TELEGRAM: "telegram",
|
|
||||||
};
|
|
||||||
|
|
||||||
class NotificationController {
|
class NotificationController {
|
||||||
constructor({ notificationService, stringService, statusService, db }) {
|
constructor({ notificationService, stringService, statusService, db }) {
|
||||||
this.notificationService = notificationService;
|
this.notificationService = notificationService;
|
||||||
@@ -25,8 +11,8 @@ class NotificationController {
|
|||||||
this.db = db;
|
this.db = db;
|
||||||
}
|
}
|
||||||
|
|
||||||
testNotification = async (req, res, next) => {
|
testNotification = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const notification = req.body;
|
const notification = req.body;
|
||||||
|
|
||||||
const success = await this.notificationService.sendTestNotification(notification);
|
const success = await this.notificationService.sendTestNotification(notification);
|
||||||
@@ -41,22 +27,17 @@ class NotificationController {
|
|||||||
return res.success({
|
return res.success({
|
||||||
msg: "Notification sent successfully",
|
msg: "Notification sent successfully",
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "testWebhook"));
|
SERVICE_NAME,
|
||||||
}
|
"testNotification"
|
||||||
};
|
);
|
||||||
|
|
||||||
createNotification = async (req, res, next) => {
|
createNotification = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createNotificationBodyValidation.validateAsync(req.body, {
|
await createNotificationBodyValidation.validateAsync(req.body, {
|
||||||
abortEarly: false,
|
abortEarly: false,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const body = req.body;
|
const body = req.body;
|
||||||
const { _id, teamId } = req.user;
|
const { _id, teamId } = req.user;
|
||||||
body.userId = _id;
|
body.userId = _id;
|
||||||
@@ -66,69 +47,64 @@ class NotificationController {
|
|||||||
msg: "Notification created successfully",
|
msg: "Notification created successfully",
|
||||||
data: notification,
|
data: notification,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createNotification"));
|
SERVICE_NAME,
|
||||||
}
|
"createNotification"
|
||||||
};
|
);
|
||||||
|
|
||||||
getNotificationsByTeamId = async (req, res, next) => {
|
getNotificationsByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const notifications = await this.db.getNotificationsByTeamId(req.user.teamId);
|
const notifications = await this.db.getNotificationsByTeamId(req.user.teamId);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: "Notifications fetched successfully",
|
msg: "Notifications fetched successfully",
|
||||||
data: notifications,
|
data: notifications,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getNotificationsByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getNotificationsByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
deleteNotification = async (req, res, next) => {
|
deleteNotification = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await this.db.deleteNotificationById(req.params.id);
|
await this.db.deleteNotificationById(req.params.id);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: "Notification deleted successfully",
|
msg: "Notification deleted successfully",
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteNotification"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteNotification"
|
||||||
};
|
);
|
||||||
|
|
||||||
getNotificationById = async (req, res, next) => {
|
getNotificationById = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const notification = await this.db.getNotificationById(req.params.id);
|
const notification = await this.db.getNotificationById(req.params.id);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: "Notification fetched successfully",
|
msg: "Notification fetched successfully",
|
||||||
data: notification,
|
data: notification,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getNotificationById"));
|
SERVICE_NAME,
|
||||||
}
|
"getNotificationById"
|
||||||
};
|
);
|
||||||
|
|
||||||
editNotification = async (req, res, next) => {
|
editNotification = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createNotificationBodyValidation.validateAsync(req.body, {
|
await createNotificationBodyValidation.validateAsync(req.body, {
|
||||||
abortEarly: false,
|
abortEarly: false,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const notification = await this.db.editNotification(req.params.id, req.body);
|
const notification = await this.db.editNotification(req.params.id, req.body);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: "Notification updated successfully",
|
msg: "Notification updated successfully",
|
||||||
data: notification,
|
data: notification,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "editNotification"));
|
SERVICE_NAME,
|
||||||
}
|
"editNotification"
|
||||||
};
|
);
|
||||||
|
|
||||||
testAllNotifications = async (req, res, next) => {
|
testAllNotifications = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const { monitorId } = req.body;
|
const { monitorId } = req.body;
|
||||||
const monitor = await this.db.getMonitorById(monitorId);
|
const monitor = await this.db.getMonitorById(monitorId);
|
||||||
const notifications = monitor.notifications;
|
const notifications = monitor.notifications;
|
||||||
@@ -138,10 +114,10 @@ class NotificationController {
|
|||||||
return res.success({
|
return res.success({
|
||||||
msg: "All notifications sent successfully",
|
msg: "All notifications sent successfully",
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "testAllNotifications"));
|
SERVICE_NAME,
|
||||||
}
|
"testAllNotifications"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default NotificationController;
|
export default NotificationController;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { handleError } from "./controllerUtils.js";
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "JobQueueController";
|
const SERVICE_NAME = "JobQueueController";
|
||||||
|
|
||||||
@@ -8,82 +8,76 @@ class JobQueueController {
|
|||||||
this.stringService = stringService;
|
this.stringService = stringService;
|
||||||
}
|
}
|
||||||
|
|
||||||
getMetrics = async (req, res, next) => {
|
getMetrics = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const metrics = await this.jobQueue.getMetrics();
|
const metrics = await this.jobQueue.getMetrics();
|
||||||
res.success({
|
res.success({
|
||||||
msg: this.stringService.queueGetMetrics,
|
msg: this.stringService.queueGetMetrics,
|
||||||
data: metrics,
|
data: metrics,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getMetrics"));
|
SERVICE_NAME,
|
||||||
return;
|
"getMetrics"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
getJobs = async (req, res, next) => {
|
getJobs = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const jobs = await this.jobQueue.getJobs();
|
const jobs = await this.jobQueue.getJobs();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.queueGetJobs,
|
msg: this.stringService.queueGetJobs,
|
||||||
data: jobs,
|
data: jobs,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getJobs"));
|
SERVICE_NAME,
|
||||||
return;
|
"getJobs"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
getAllMetrics = async (req, res, next) => {
|
getAllMetrics = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const jobs = await this.jobQueue.getJobs();
|
const jobs = await this.jobQueue.getJobs();
|
||||||
const metrics = await this.jobQueue.getMetrics();
|
const metrics = await this.jobQueue.getMetrics();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.queueGetAllMetrics,
|
msg: this.stringService.queueGetAllMetrics,
|
||||||
data: { jobs, metrics },
|
data: { jobs, metrics },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getAllMetrics"));
|
SERVICE_NAME,
|
||||||
return;
|
"getAllMetrics"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
addJob = async (req, res, next) => {
|
addJob = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
|
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.queueAddJob,
|
msg: this.stringService.queueAddJob,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "addJob"));
|
SERVICE_NAME,
|
||||||
return;
|
"addJob"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
flushQueue = async (req, res, next) => {
|
flushQueue = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const result = await this.jobQueue.flushQueues();
|
const result = await this.jobQueue.flushQueues();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.jobQueueFlush,
|
msg: this.stringService.jobQueueFlush,
|
||||||
data: result,
|
data: result,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "flushQueue"));
|
SERVICE_NAME,
|
||||||
return;
|
"flushQueue"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
checkQueueHealth = async (req, res, next) => {
|
checkQueueHealth = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const stuckQueues = await this.jobQueue.checkQueueHealth();
|
const stuckQueues = await this.jobQueue.checkQueueHealth();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.queueHealthCheck,
|
msg: this.stringService.queueHealthCheck,
|
||||||
data: stuckQueues,
|
data: stuckQueues,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "checkQueueHealth"));
|
SERVICE_NAME,
|
||||||
return;
|
"checkQueueHealth"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
}
|
}
|
||||||
export default JobQueueController;
|
export default JobQueueController;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
|
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
|
||||||
import { handleValidationError, handleError } from "./controllerUtils.js";
|
|
||||||
import { sendTestEmailBodyValidation } from "../validation/joi.js";
|
import { sendTestEmailBodyValidation } from "../validation/joi.js";
|
||||||
|
import { asyncHandler, createServerError } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "SettingsController";
|
const SERVICE_NAME = "SettingsController";
|
||||||
|
|
||||||
class SettingsController {
|
class SettingsController {
|
||||||
@@ -32,45 +33,44 @@ class SettingsController {
|
|||||||
return returnSettings;
|
return returnSettings;
|
||||||
};
|
};
|
||||||
|
|
||||||
getAppSettings = async (req, res, next) => {
|
getAppSettings = asyncHandler(
|
||||||
const dbSettings = await this.settingsService.getDBSettings();
|
async (req, res, next) => {
|
||||||
|
const dbSettings = await this.settingsService.getDBSettings();
|
||||||
|
|
||||||
const returnSettings = this.buildAppSettings(dbSettings);
|
const returnSettings = this.buildAppSettings(dbSettings);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.getAppSettings,
|
msg: this.stringService.getAppSettings,
|
||||||
data: returnSettings,
|
data: returnSettings,
|
||||||
});
|
});
|
||||||
};
|
},
|
||||||
|
SERVICE_NAME,
|
||||||
|
"getAppSettings"
|
||||||
|
);
|
||||||
|
|
||||||
updateAppSettings = async (req, res, next) => {
|
updateAppSettings = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const updatedSettings = await this.db.updateAppSettings(req.body);
|
const updatedSettings = await this.db.updateAppSettings(req.body);
|
||||||
const returnSettings = this.buildAppSettings(updatedSettings);
|
const returnSettings = this.buildAppSettings(updatedSettings);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.updateAppSettings,
|
msg: this.stringService.updateAppSettings,
|
||||||
data: returnSettings,
|
data: returnSettings,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
|
SERVICE_NAME,
|
||||||
}
|
"updateAppSettings"
|
||||||
};
|
);
|
||||||
|
|
||||||
sendTestEmail = async (req, res, next) => {
|
sendTestEmail = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await sendTestEmailBodyValidation.validateAsync(req.body);
|
try {
|
||||||
} catch (error) {
|
await sendTestEmailBodyValidation.validateAsync(req.body);
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
} catch (error) {
|
||||||
return;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
}
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const {
|
const {
|
||||||
to,
|
to,
|
||||||
systemEmailHost,
|
systemEmailHost,
|
||||||
@@ -107,20 +107,17 @@ class SettingsController {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!messageId) {
|
if (!messageId) {
|
||||||
return res.error({
|
throw createServerError("Failed to send test email.");
|
||||||
msg: "Failed to send test email.",
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.sendTestEmail,
|
msg: this.stringService.sendTestEmail,
|
||||||
data: { messageId },
|
data: { messageId },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME));
|
SERVICE_NAME,
|
||||||
return;
|
"sendTestEmail"
|
||||||
}
|
);
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default SettingsController;
|
export default SettingsController;
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { handleError, handleValidationError } from "./controllerUtils.js";
|
|
||||||
import {
|
import {
|
||||||
createStatusPageBodyValidation,
|
createStatusPageBodyValidation,
|
||||||
getStatusPageParamValidation,
|
getStatusPageParamValidation,
|
||||||
getStatusPageQueryValidation,
|
getStatusPageQueryValidation,
|
||||||
imageValidation,
|
imageValidation,
|
||||||
} from "../validation/joi.js";
|
} from "../validation/joi.js";
|
||||||
|
import { asyncHandler } from "../utils/errorUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "statusPageController";
|
const SERVICE_NAME = "statusPageController";
|
||||||
|
|
||||||
@@ -14,16 +14,11 @@ class StatusPageController {
|
|||||||
this.stringService = stringService;
|
this.stringService = stringService;
|
||||||
}
|
}
|
||||||
|
|
||||||
createStatusPage = async (req, res, next) => {
|
createStatusPage = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createStatusPageBodyValidation.validateAsync(req.body);
|
await createStatusPageBodyValidation.validateAsync(req.body);
|
||||||
await imageValidation.validateAsync(req.file);
|
await imageValidation.validateAsync(req.file);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { _id, teamId } = req.user;
|
const { _id, teamId } = req.user;
|
||||||
const statusPage = await this.db.createStatusPage({
|
const statusPage = await this.db.createStatusPage({
|
||||||
statusPageData: req.body,
|
statusPageData: req.body,
|
||||||
@@ -35,21 +30,16 @@ class StatusPageController {
|
|||||||
msg: this.stringService.statusPageCreate,
|
msg: this.stringService.statusPageCreate,
|
||||||
data: statusPage,
|
data: statusPage,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "createStatusPage"));
|
SERVICE_NAME,
|
||||||
}
|
"createStatusPage"
|
||||||
};
|
);
|
||||||
|
|
||||||
updateStatusPage = async (req, res, next) => {
|
updateStatusPage = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await createStatusPageBodyValidation.validateAsync(req.body);
|
await createStatusPageBodyValidation.validateAsync(req.body);
|
||||||
await imageValidation.validateAsync(req.file);
|
await imageValidation.validateAsync(req.file);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const statusPage = await this.db.updateStatusPage(req.body, req.file);
|
const statusPage = await this.db.updateStatusPage(req.body, req.file);
|
||||||
if (statusPage === null) {
|
if (statusPage === null) {
|
||||||
const error = new Error(this.stringService.statusPageNotFound);
|
const error = new Error(this.stringService.statusPageNotFound);
|
||||||
@@ -60,45 +50,40 @@ class StatusPageController {
|
|||||||
msg: this.stringService.statusPageUpdate,
|
msg: this.stringService.statusPageUpdate,
|
||||||
data: statusPage,
|
data: statusPage,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "updateStatusPage"));
|
SERVICE_NAME,
|
||||||
}
|
"updateStatusPage"
|
||||||
};
|
);
|
||||||
|
|
||||||
getStatusPage = async (req, res, next) => {
|
getStatusPage = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const statusPage = await this.db.getStatusPage();
|
const statusPage = await this.db.getStatusPage();
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.statusPageByUrl,
|
msg: this.stringService.statusPageByUrl,
|
||||||
data: statusPage,
|
data: statusPage,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getStatusPage"));
|
SERVICE_NAME,
|
||||||
}
|
"getStatusPage"
|
||||||
};
|
);
|
||||||
|
|
||||||
getStatusPageByUrl = async (req, res, next) => {
|
getStatusPageByUrl = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await getStatusPageParamValidation.validateAsync(req.params);
|
await getStatusPageParamValidation.validateAsync(req.params);
|
||||||
await getStatusPageQueryValidation.validateAsync(req.query);
|
await getStatusPageQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const statusPage = await this.db.getStatusPageByUrl(req.params.url, req.query.type);
|
const statusPage = await this.db.getStatusPageByUrl(req.params.url, req.query.type);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.statusPageByUrl,
|
msg: this.stringService.statusPageByUrl,
|
||||||
data: statusPage,
|
data: statusPage,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getStatusPageByUrl"));
|
SERVICE_NAME,
|
||||||
}
|
"getStatusPageByUrl"
|
||||||
};
|
);
|
||||||
|
|
||||||
getStatusPagesByTeamId = async (req, res, next) => {
|
getStatusPagesByTeamId = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
const teamId = req.user.teamId;
|
const teamId = req.user.teamId;
|
||||||
const statusPages = await this.db.getStatusPagesByTeamId(teamId);
|
const statusPages = await this.db.getStatusPagesByTeamId(teamId);
|
||||||
|
|
||||||
@@ -106,21 +91,21 @@ class StatusPageController {
|
|||||||
msg: this.stringService.statusPageByTeamId,
|
msg: this.stringService.statusPageByTeamId,
|
||||||
data: statusPages,
|
data: statusPages,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "getStatusPageByTeamId"));
|
SERVICE_NAME,
|
||||||
}
|
"getStatusPagesByTeamId"
|
||||||
};
|
);
|
||||||
|
|
||||||
deleteStatusPage = async (req, res, next) => {
|
deleteStatusPage = asyncHandler(
|
||||||
try {
|
async (req, res, next) => {
|
||||||
await this.db.deleteStatusPage(req.params.url);
|
await this.db.deleteStatusPage(req.params.url);
|
||||||
return res.success({
|
return res.success({
|
||||||
msg: this.stringService.statusPageDelete,
|
msg: this.stringService.statusPageDelete,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
},
|
||||||
next(handleError(error, SERVICE_NAME, "deleteStatusPage"));
|
SERVICE_NAME,
|
||||||
}
|
"deleteStatusPage"
|
||||||
};
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default StatusPageController;
|
export default StatusPageController;
|
||||||
@@ -3,6 +3,7 @@ import ServiceRegistry from "../service/serviceRegistry.js";
|
|||||||
import StringService from "../service/stringService.js";
|
import StringService from "../service/stringService.js";
|
||||||
|
|
||||||
const handleErrors = (error, req, res, next) => {
|
const handleErrors = (error, req, res, next) => {
|
||||||
|
console.log("ERROR", error);
|
||||||
const status = error.status || 500;
|
const status = error.status || 500;
|
||||||
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
|
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
|
||||||
const message = error.message || stringService.authIncorrectPassword;
|
const message = error.message || stringService.authIncorrectPassword;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ class DiagnosticRoutes {
|
|||||||
);
|
);
|
||||||
|
|
||||||
this.router.post("/db/stats", this.diagnosticController.getDbStats);
|
this.router.post("/db/stats", this.diagnosticController.getDbStats);
|
||||||
|
this.router.get("/system", this.diagnosticController.getSystemStats);
|
||||||
}
|
}
|
||||||
|
|
||||||
getRouter() {
|
getRouter() {
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
class AppError extends Error {
|
||||||
|
constructor(message, status = 500, service = null, method = null, details = null) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
this.service = service;
|
||||||
|
this.method = method;
|
||||||
|
this.details = details;
|
||||||
|
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createError = (
|
||||||
|
message,
|
||||||
|
status = 500,
|
||||||
|
service = null,
|
||||||
|
method = null,
|
||||||
|
details = null
|
||||||
|
) => {
|
||||||
|
return new AppError(message, status, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createValidationError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 422, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createAuthError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 401, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createForbiddenError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 403, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createNotFoundError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 404, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createConflictError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 409, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createServerError = (
|
||||||
|
message,
|
||||||
|
details = null,
|
||||||
|
service = null,
|
||||||
|
method = null
|
||||||
|
) => {
|
||||||
|
return createError(message, 500, service, method, details);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const asyncHandler = (fn, serviceName, methodName) => {
|
||||||
|
return async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await fn(req, res, next);
|
||||||
|
} catch (error) {
|
||||||
|
// Handle validation errors
|
||||||
|
if (error.isJoi || error.name === "ValidationError") {
|
||||||
|
const validationError = createValidationError(
|
||||||
|
error.message,
|
||||||
|
error.details,
|
||||||
|
serviceName,
|
||||||
|
methodName
|
||||||
|
);
|
||||||
|
return next(validationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof AppError) {
|
||||||
|
error.service = error.service || serviceName;
|
||||||
|
error.method = error.method || methodName;
|
||||||
|
return next(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.code === "23505") {
|
||||||
|
const appError = createConflictError("Resource already exists", {
|
||||||
|
originalError: error.message,
|
||||||
|
code: error.code,
|
||||||
|
});
|
||||||
|
appError.service = serviceName;
|
||||||
|
appError.method = methodName;
|
||||||
|
return next(appError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For unknown errors, create a server error
|
||||||
|
const appError = createServerError(
|
||||||
|
error.message || "An unexpected error occurred",
|
||||||
|
{ originalError: error.message, stack: error.stack }
|
||||||
|
);
|
||||||
|
appError.service = serviceName;
|
||||||
|
appError.method = methodName;
|
||||||
|
appError.stack = error.stack; // Preserve original stack
|
||||||
|
|
||||||
|
return next(appError);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -577,14 +577,7 @@ const createNotificationBodyValidation = joi.object({
|
|||||||
"string.empty": "Notification name is required",
|
"string.empty": "Notification name is required",
|
||||||
"any.required": "Notification name is required",
|
"any.required": "Notification name is required",
|
||||||
}),
|
}),
|
||||||
address: joi.when("type", {
|
|
||||||
is: "email",
|
|
||||||
then: joi.string().email().required().messages({
|
|
||||||
"string.empty": "E-mail address cannot be empty",
|
|
||||||
"any.required": "E-mail address is required",
|
|
||||||
"string.email": "Please enter a valid e-mail address",
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
type: joi
|
type: joi
|
||||||
.string()
|
.string()
|
||||||
.valid("email", "webhook", "slack", "discord", "pager_duty")
|
.valid("email", "webhook", "slack", "discord", "pager_duty")
|
||||||
@@ -594,6 +587,20 @@ const createNotificationBodyValidation = joi.object({
|
|||||||
"any.required": "Notification type is required",
|
"any.required": "Notification type is required",
|
||||||
"any.only": "Notification type must be email, webhook, or pager_duty",
|
"any.only": "Notification type must be email, webhook, or pager_duty",
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
address: joi.when("type", {
|
||||||
|
is: "email",
|
||||||
|
then: joi.string().email().required().messages({
|
||||||
|
"string.empty": "E-mail address cannot be empty",
|
||||||
|
"any.required": "E-mail address is required",
|
||||||
|
"string.email": "Please enter a valid e-mail address",
|
||||||
|
}),
|
||||||
|
otherwise: joi.string().uri().required().messages({
|
||||||
|
"string.empty": "Webhook URL cannot be empty",
|
||||||
|
"any.required": "Webhook URL is required",
|
||||||
|
"string.uri": "Please enter a valid Webhook URL",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
//****************************************
|
//****************************************
|
||||||
|
|||||||
Reference in new issue
Block a user