Fixed the errors coming out in csv.

This commit is contained in:
Owaise Imdad committed 2025-05-01 12:05:28 +05:30
1 parent ecce31ce34
commit 075559ffc3
3 files changed
+52 -28

No files matched your search

+4 -6
View File
@@ -3,11 +3,9 @@ import { networkService } from "../main";
export const useBulkMonitors = () => { export const useBulkMonitors = () => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const createBulkMonitors = async (file, user) => { const createBulkMonitors = async (file, user) => {
setIsLoading(true); setIsLoading(true);
setError(null);
const formData = new FormData(); const formData = new FormData();
formData.append("csvFile", file); formData.append("csvFile", file);
@@ -16,14 +14,14 @@ export const useBulkMonitors = () => {
try { try {
const response = await networkService.createBulkMonitors(formData); const response = await networkService.createBulkMonitors(formData);
return response.data; return [true, response.data, null]; // [success, data, error]
} catch (err) { } catch (err) {
setError(err?.response?.data?.msg ?? err.message); const errorMessage = err?.response?.data?.errors?.[0]?.message || err.message;
return null; return [false, null, errorMessage];
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
return [createBulkMonitors, isLoading, error]; return [createBulkMonitors, isLoading];
}; };
+5 -3
View File
@@ -26,20 +26,22 @@ const BulkImport = () => {
{ name: t("bulkImport.title"), path: `/uptime/bulk-import` }, { name: t("bulkImport.title"), path: `/uptime/bulk-import` },
]; ];
const [createBulkMonitors, hookLoading, error] = useBulkMonitors(); const [createBulkMonitors, hookLoading] = useBulkMonitors();
const handleSubmit = async () => { const handleSubmit = async () => {
if (!selectedFile) { if (!selectedFile) {
createToast({ body: t("bulkImport.noFileSelected") }); createToast({ body: t("bulkImport.noFileSelected") });
return; return;
} }
const success = await createBulkMonitors(selectedFile, user);
const [success, data, error] = await createBulkMonitors(selectedFile, user);
if (success) { if (success) {
// You can use `data` here if needed
createToast({ body: t("bulkImport.uploadSuccess") }); createToast({ body: t("bulkImport.uploadSuccess") });
navigate("/uptime"); navigate("/uptime");
} else { } else {
createToast({ body: error }); createToast({ body: error || t("bulkImport.uploadFailed") });
} }
}; };
+43 -19
View File
@@ -256,37 +256,60 @@ class MonitorController {
createBulkMonitors = async (req, res, next) => { createBulkMonitors = async (req, res, next) => {
try { try {
const { parse } = pkg; const { parse } = pkg;
if (!req.file) { if (!req.file) {
return res.status(400).json({ msg: "No file uploaded" }); return res.status(400).json({
errors: [
{ message: "No file uploaded" }
]
});
} }
const { userId, teamId } = req.body; const { userId, teamId } = req.body;
if (!userId || !teamId) { if (!userId || !teamId) {
return res.status(400).json({ msg: "Missing userId or teamId in form data" }); return res.status(400).json({
errors: [
{ message: "Missing userId or teamId in form data" }
]
});
} }
// Get file buffer from memory and convert to string // Get file buffer from memory and convert to string
const fileData = req.file.buffer.toString("utf-8"); const fileData = req.file.buffer.toString("utf-8");
console.log("File data:", fileData);
// Parse the CSV data
parse(fileData, { parse(fileData, {
header: true, header: true,
skipEmptyLines: true, skipEmptyLines: true,
transform: (value, header) => { transform: (value, header) => {
if (value === "") return undefined; if (value === "") return undefined; // Empty fields become undefined
// Handle 'port' and 'interval' fields, check if they're valid numbers
if (["port", "interval"].includes(header)) { if (["port", "interval"].includes(header)) {
const num = parseInt(value, 10); const num = parseInt(value, 10);
return isNaN(num) ? undefined : num; if (isNaN(num)) {
return res.status(400).json({
errors: [
{ message: `${header} should be a valid number, got: ${value}` }
]
}); // Return error immediately with this structure
}
return num;
} }
return value; return value;
}, },
complete: async ({ data, errors }) => { complete: async ({ data, errors }) => {
if (errors.length > 0) { if (errors.length > 0) {
return res.status(400).json({ msg: "Error parsing CSV", errors }); return res.status(400).json({
errors: [
{ message: "Error parsing CSV" }
]
});
} }
const enrichedData = data.map((monitor) => ({ const enrichedData = data.map((monitor) => ({
userId, userId,
teamId, teamId,
@@ -295,20 +318,21 @@ class MonitorController {
name: monitor.name || monitor.url, name: monitor.name || monitor.url,
type: monitor.type || "http", type: monitor.type || "http",
})); }));
try { try {
// Run Joi validation
await createMonitorsBodyValidation.validateAsync(enrichedData); await createMonitorsBodyValidation.validateAsync(enrichedData);
} catch (error) { } catch (error) {
return next(handleValidationError(error, SERVICE_NAME)); return next(handleValidationError(error, SERVICE_NAME));
} }
try { try {
const monitors = await this.db.createBulkMonitors(enrichedData); const monitors = await this.db.createBulkMonitors(enrichedData);
await Promise.all( await Promise.all(
monitors.map(async (monitor, index) => { monitors.map(async (monitor, index) => {
const notifications = enrichedData[index].notifications; const notifications = enrichedData[index].notifications;
if (notifications?.length) { if (notifications?.length) {
monitor.notifications = await Promise.all( monitor.notifications = await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
@@ -318,11 +342,11 @@ class MonitorController {
); );
await monitor.save(); await monitor.save();
} }
this.jobQueue.addJob(monitor._id, monitor); this.jobQueue.addJob(monitor._id, monitor);
}) })
); );
return res.success({ return res.success({
msg: this.stringService.bulkMonitorsCreate, msg: this.stringService.bulkMonitorsCreate,
data: monitors, data: monitors,
@@ -335,7 +359,7 @@ class MonitorController {
} catch (error) { } catch (error) {
return 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