Moved the parsing logic to backend as suggested.
This commit is contained in:
1 parent
b2fd9b1e89
commit
bd8554707d
10 files changed
+163
-101
No files matched your search
@@ -38,7 +38,6 @@
|
|||||||
"joi": "17.13.3",
|
"joi": "17.13.3",
|
||||||
"maplibre-gl": "5.3.1",
|
"maplibre-gl": "5.3.1",
|
||||||
"mui-color-input": "^6.0.0",
|
"mui-color-input": "^6.0.0",
|
||||||
"papaparse": "^5.5.2",
|
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-dnd": "^16.0.1",
|
"react-dnd": "^16.0.1",
|
||||||
"react-dnd-html5-backend": "^16.0.1",
|
"react-dnd-html5-backend": "^16.0.1",
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { networkService } from "../main"; // Your network service
|
||||||
|
|
||||||
|
export const useBulkMonitors = () => {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
const createBulkMonitors = async (file, user) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("csvFile", file);
|
||||||
|
formData.append("userId", user._id);
|
||||||
|
formData.append("teamId", user.teamId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await networkService.createBulkMonitors(formData);
|
||||||
|
return response.data;
|
||||||
|
} catch (err) {
|
||||||
|
setError(err?.response?.data?.msg ?? err.message);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return { createBulkMonitors, isLoading, error };
|
||||||
|
};
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { useState, useRef, useEffect } from "react";
|
import { useState, useRef } from "react";
|
||||||
import { Button, Typography } from "@mui/material";
|
import { Button, Typography } from "@mui/material";
|
||||||
import { parse } from "papaparse";
|
|
||||||
import { bulkMonitorsValidation } from "../../../Validation/validation";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
export function Upload({ onComplete }) {
|
const UploadFile = ({ onFileSelect }) => { // Changed prop to onFileSelect
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const [file, setFile] = useState();
|
const [file, setFile] = useState();
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -18,41 +17,19 @@ export function Upload({ onComplete }) {
|
|||||||
|
|
||||||
const handleFileChange = (e) => {
|
const handleFileChange = (e) => {
|
||||||
setError("");
|
setError("");
|
||||||
setFile(e.target.files[0]);
|
const selectedFile = e.target.files[0];
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
// Basic file validation
|
||||||
if (!file) return;
|
if (!selectedFile) return;
|
||||||
parse(file, {
|
|
||||||
header: true,
|
if (!selectedFile.name.endsWith('.csv')) {
|
||||||
skipEmptyLines: true,
|
setError(t("bulkImport.invalidFileType"));
|
||||||
transform: (value, header) => {
|
return;
|
||||||
if (!value) {
|
}
|
||||||
return undefined;
|
|
||||||
}
|
setFile(selectedFile);
|
||||||
if (header === "port" || header === "interval") {
|
onFileSelect(selectedFile); // Pass the file directly to parent
|
||||||
return parseInt(value);
|
};
|
||||||
}
|
|
||||||
return value;
|
|
||||||
},
|
|
||||||
complete: ({ data, errors }) => {
|
|
||||||
if (errors.length > 0) {
|
|
||||||
setError(t("bulkImport.parsingFailed"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const { error } = bulkMonitorsValidation.validate(data);
|
|
||||||
if (error) {
|
|
||||||
setError(
|
|
||||||
error.details?.[0]?.message ||
|
|
||||||
error.message ||
|
|
||||||
t("bulkImport.validationFailed")
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
onComplete(data);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}, [file]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -68,7 +45,7 @@ export function Upload({ onComplete }) {
|
|||||||
mb={theme.spacing(1.5)}
|
mb={theme.spacing(1.5)}
|
||||||
sx={{ wordBreak: "break-all" }}
|
sx={{ wordBreak: "break-all" }}
|
||||||
>
|
>
|
||||||
{file?.name}
|
{file?.name || t("bulkImport.noFileSelected")}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography
|
<Typography
|
||||||
component="div"
|
component="div"
|
||||||
@@ -87,3 +64,10 @@ export function Upload({ onComplete }) {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
UploadFile.prototype = {
|
||||||
|
onFileSelect: PropTypes.func.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UploadFile;
|
||||||
@@ -5,45 +5,41 @@ import { useState } from "react";
|
|||||||
import { Box, Stack, Typography, Button, Link } from "@mui/material";
|
import { Box, Stack, Typography, Button, Link } from "@mui/material";
|
||||||
|
|
||||||
//Components
|
//Components
|
||||||
import { networkService } from "../../../main";
|
|
||||||
import { createToast } from "../../../Utils/toastUtils";
|
import { createToast } from "../../../Utils/toastUtils";
|
||||||
import Breadcrumbs from "../../../Components/Breadcrumbs";
|
import Breadcrumbs from "../../../Components/Breadcrumbs";
|
||||||
import ConfigBox from "../../../Components/ConfigBox";
|
import ConfigBox from "../../../Components/ConfigBox";
|
||||||
import { Upload } from "./Upload";
|
import { UploadFile } from "./Upload";
|
||||||
import { useSelector } from "react-redux";
|
import { useSelector } from "react-redux";
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
import { Trans, useTranslation } from "react-i18next";
|
import { Trans, useTranslation } from "react-i18next";
|
||||||
|
import { useBulkMonitors } from "../../../Hooks/useBulkMonitors";
|
||||||
|
|
||||||
const BulkImport = () => {
|
const BulkImport = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const [monitors, setMonitors] = useState([]);
|
|
||||||
const { user } = useSelector((state) => state.auth);
|
const { user } = useSelector((state) => state.auth);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [selectedFile, setSelectedFile] = useState(null);
|
||||||
|
|
||||||
const crumbs = [
|
const crumbs = [
|
||||||
{ name: t("uptime"), path: "/uptime" },
|
{ name: t("uptime"), path: "/uptime" },
|
||||||
{ name: t("bulkImport.title"), path: `/uptime/bulk-import` },
|
{ name: t("bulkImport.title"), path: `/uptime/bulk-import` },
|
||||||
];
|
];
|
||||||
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const { createBulkMonitors, isLoading: hookLoading, error } = useBulkMonitors();
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
setIsLoading(true);
|
if (!selectedFile) {
|
||||||
try {
|
createToast({ body: t("bulkImport.noFileSelected") });
|
||||||
const monitorsWithUser = monitors.map((monitor) => ({
|
return;
|
||||||
...monitor,
|
}
|
||||||
description: monitor.name || monitor.url,
|
const success = await createBulkMonitors(selectedFile, user);
|
||||||
teamId: user.teamId,
|
|
||||||
userId: user._id,
|
if (success) {
|
||||||
}));
|
|
||||||
await networkService.createBulkMonitors({ monitors: monitorsWithUser });
|
|
||||||
createToast({ body: t("bulkImport.uploadSuccess") });
|
createToast({ body: t("bulkImport.uploadSuccess") });
|
||||||
navigate("/uptime");
|
navigate("/uptime");
|
||||||
} catch (error) {
|
} else {
|
||||||
createToast({ body: error?.response?.data?.msg ?? error.message });
|
createToast({ body: error });
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -63,9 +59,7 @@ const BulkImport = () => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
<ConfigBox>
|
<ConfigBox>
|
||||||
<Box>
|
<Box>
|
||||||
<Typography component="h2">
|
<Typography component="h2">{t("bulkImport.selectFileTips")}</Typography>
|
||||||
{t("bulkImport.selectFileTips")}
|
|
||||||
</Typography>
|
|
||||||
<Typography component="p">
|
<Typography component="p">
|
||||||
<Trans
|
<Trans
|
||||||
i18nKey="bulkImport.selectFileDescription"
|
i18nKey="bulkImport.selectFileDescription"
|
||||||
@@ -90,7 +84,7 @@ const BulkImport = () => {
|
|||||||
</Box>
|
</Box>
|
||||||
<Stack gap={theme.spacing(12)}>
|
<Stack gap={theme.spacing(12)}>
|
||||||
<Stack gap={theme.spacing(6)}>
|
<Stack gap={theme.spacing(6)}>
|
||||||
<Upload onComplete={setMonitors} />
|
<UploadFile onFileSelect={(file) => setSelectedFile(file)} />
|
||||||
</Stack>
|
</Stack>
|
||||||
</Stack>
|
</Stack>
|
||||||
</ConfigBox>
|
</ConfigBox>
|
||||||
@@ -102,8 +96,8 @@ const BulkImport = () => {
|
|||||||
variant="contained"
|
variant="contained"
|
||||||
color="accent"
|
color="accent"
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
disabled={!monitors?.length}
|
disabled={hookLoading}
|
||||||
loading={isLoading}
|
loading={hookLoading}
|
||||||
>
|
>
|
||||||
{t("submit")}
|
{t("submit")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1090,8 +1090,13 @@ class NetworkService {
|
|||||||
// Create bulk monitors
|
// Create bulk monitors
|
||||||
// ************************************
|
// ************************************
|
||||||
|
|
||||||
async createBulkMonitors({ monitors }) {
|
async createBulkMonitors(formData) {
|
||||||
return this.axiosInstance.post(`/monitors/bulk`, monitors);
|
const response = await this.axiosInstance.post(`/monitors/bulk`, formData, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "multipart/form-data",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ************************************
|
// ************************************
|
||||||
|
|||||||
@@ -403,6 +403,7 @@
|
|||||||
"selectFile": "Select File",
|
"selectFile": "Select File",
|
||||||
"parsingFailed": "Parsing failed",
|
"parsingFailed": "Parsing failed",
|
||||||
"uploadSuccess": "Monitors created successfully!",
|
"uploadSuccess": "Monitors created successfully!",
|
||||||
"validationFailed": "Validation failed"
|
"validationFailed": "Validation failed",
|
||||||
|
"noFileSelected": "No file selected"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,6 +24,7 @@ import axios from "axios";
|
|||||||
import seedDb from "../db/mongo/utils/seedDb.js";
|
import seedDb from "../db/mongo/utils/seedDb.js";
|
||||||
import { seedDistributedTest } from "../db/mongo/utils/seedDb.js";
|
import { seedDistributedTest } from "../db/mongo/utils/seedDb.js";
|
||||||
const SERVICE_NAME = "monitorController";
|
const SERVICE_NAME = "monitorController";
|
||||||
|
import pkg from "papaparse";
|
||||||
|
|
||||||
class MonitorController {
|
class MonitorController {
|
||||||
constructor(db, settingsService, jobQueue, stringService) {
|
constructor(db, settingsService, jobQueue, stringService) {
|
||||||
@@ -243,56 +244,98 @@ class MonitorController {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates bulk monitors and adds them to the job queue.
|
* Creates bulk monitors and adds them to the job queue after parsing CSV.
|
||||||
* @async
|
* @async
|
||||||
* @param {Object} req - The Express request object.
|
* @param {Object} req - The Express request object.
|
||||||
* @property {Object} req.body - The body of the request.
|
* @property {Object} req.file - The uploaded CSV file.
|
||||||
* @param {Object} res - The Express response object.
|
* @param {Object} res - The Express response object.
|
||||||
* @param {function} next - The next middleware function.
|
* @param {function} next - The next middleware function.
|
||||||
* @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 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 = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await createMonitorsBodyValidation.validateAsync(req.body);
|
const { parse } = pkg;
|
||||||
} catch (error) {
|
|
||||||
next(handleValidationError(error, SERVICE_NAME));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
if (!req.file) {
|
||||||
// create monitors
|
return res.status(400).json({ msg: "No file uploaded" });
|
||||||
const monitors = await this.db.createBulkMonitors(req);
|
}
|
||||||
|
|
||||||
// create notifications for each monitor
|
const { userId, teamId } = req.body;
|
||||||
await Promise.all(
|
|
||||||
monitors.map(async (monitor, index) => {
|
|
||||||
const notifications = req.body[index].notifications;
|
|
||||||
|
|
||||||
if (notifications?.length) {
|
if (!userId || !teamId) {
|
||||||
monitor.notifications = await Promise.all(
|
return res.status(400).json({ msg: "Missing userId or teamId in form data" });
|
||||||
notifications.map(async (notification) => {
|
}
|
||||||
notification.monitorId = monitor._id;
|
|
||||||
return await this.db.createNotification(notification);
|
// Get file buffer from memory and convert to string
|
||||||
})
|
const fileData = req.file.buffer.toString("utf-8");
|
||||||
);
|
|
||||||
await monitor.save();
|
parse(fileData, {
|
||||||
|
header: true,
|
||||||
|
skipEmptyLines: true,
|
||||||
|
transform: (value, header) => {
|
||||||
|
if (value === "") return undefined;
|
||||||
|
if (["port", "interval"].includes(header)) {
|
||||||
|
const num = parseInt(value, 10);
|
||||||
|
return isNaN(num) ? undefined : num;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add monitor to job queue
|
return value;
|
||||||
this.jobQueue.addJob(monitor._id, monitor);
|
},
|
||||||
})
|
complete: async ({ data, errors }) => {
|
||||||
);
|
if (errors.length > 0) {
|
||||||
|
return res.status(400).json({ msg: "Error parsing CSV", errors });
|
||||||
|
}
|
||||||
|
|
||||||
return res.success({
|
const enrichedData = data.map((monitor) => ({
|
||||||
msg: this.stringService.bulkMonitorsCreate,
|
userId,
|
||||||
data: monitors,
|
teamId,
|
||||||
|
...monitor,
|
||||||
|
description: monitor.description || monitor.name || monitor.url,
|
||||||
|
name: monitor.name || monitor.url,
|
||||||
|
type: monitor.type || "http",
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await createMonitorsBodyValidation.validateAsync(enrichedData);
|
||||||
|
} catch (error) {
|
||||||
|
return next(handleValidationError(error, SERVICE_NAME));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const monitors = await this.db.createBulkMonitors(enrichedData);
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
monitors.map(async (monitor, index) => {
|
||||||
|
const notifications = enrichedData[index].notifications;
|
||||||
|
|
||||||
|
if (notifications?.length) {
|
||||||
|
monitor.notifications = await Promise.all(
|
||||||
|
notifications.map(async (notification) => {
|
||||||
|
notification.monitorId = monitor._id;
|
||||||
|
return await this.db.createNotification(notification);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
await monitor.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.jobQueue.addJob(monitor._id, monitor);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.success({
|
||||||
|
msg: this.stringService.bulkMonitorsCreate,
|
||||||
|
data: monitors,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
||||||
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
return next(handleError(error, SERVICE_NAME, "createBulkMonitors"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if the endpoint can be resolved
|
* Checks if the endpoint can be resolved
|
||||||
* @async
|
* @async
|
||||||
|
|||||||
@@ -751,7 +751,7 @@ const createMonitor = async (req, res) => {
|
|||||||
*/
|
*/
|
||||||
const createBulkMonitors = async (req) => {
|
const createBulkMonitors = async (req) => {
|
||||||
try {
|
try {
|
||||||
const monitors = req.body.map(
|
const monitors = req.map(
|
||||||
(item) => new Monitor({ ...item, notifications: undefined })
|
(item) => new Monitor({ ...item, notifications: undefined })
|
||||||
);
|
);
|
||||||
await Monitor.bulkSave(monitors);
|
await Monitor.bulkSave(monitors);
|
||||||
|
|||||||
+2
-1
@@ -33,8 +33,9 @@
|
|||||||
"mailersend": "^2.2.0",
|
"mailersend": "^2.2.0",
|
||||||
"mjml": "^5.0.0-alpha.4",
|
"mjml": "^5.0.0-alpha.4",
|
||||||
"mongoose": "^8.3.3",
|
"mongoose": "^8.3.3",
|
||||||
"multer": "1.4.5-lts.1",
|
"multer": "^1.4.5-lts.1",
|
||||||
"nodemailer": "^6.9.14",
|
"nodemailer": "^6.9.14",
|
||||||
|
"papaparse": "^5.5.2",
|
||||||
"ping": "0.4.4",
|
"ping": "0.4.4",
|
||||||
"sharp": "0.33.5",
|
"sharp": "0.33.5",
|
||||||
"ssl-checker": "2.0.10",
|
"ssl-checker": "2.0.10",
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { isAllowed } from "../middleware/isAllowed.js";
|
import { isAllowed } from "../middleware/isAllowed.js";
|
||||||
|
import multer from "multer";
|
||||||
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
|
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
|
||||||
|
|
||||||
|
const upload = multer({
|
||||||
|
storage: multer.memoryStorage() // Store file in memory as Buffer
|
||||||
|
});
|
||||||
|
|
||||||
class MonitorRoutes {
|
class MonitorRoutes {
|
||||||
constructor(monitorController) {
|
constructor(monitorController) {
|
||||||
this.router = Router();
|
this.router = Router();
|
||||||
@@ -89,6 +94,7 @@ class MonitorRoutes {
|
|||||||
this.router.post(
|
this.router.post(
|
||||||
"/bulk",
|
"/bulk",
|
||||||
isAllowed(["admin", "superadmin"]),
|
isAllowed(["admin", "superadmin"]),
|
||||||
|
upload.single("csvFile"),
|
||||||
this.monitorController.createBulkMonitors
|
this.monitorController.createBulkMonitors
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user