-
Notifications
You must be signed in to change notification settings - Fork 11
export mock data as csv and json buttons added and js implemented #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis change introduces two new export buttons to the Mock Data Generator interface, allowing users to download generated mock data as either JSON or CSV files. The HTML is updated to include these buttons and a text input for an optional filename. New JavaScript functions handle file creation and download by serializing the data in the chosen format and triggering a file download with the appropriate file extension and MIME type. The logic verifies the presence and validity of the generated data before exporting. No changes are made to existing public APIs beyond adding these new functions. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant UI
participant JSLogic
User->>UI: Clicks "Export as JSON" or "Export as CSV"
UI->>JSLogic: Calls exportMockOutput(format)
JSLogic->>JSLogic: Validate latestMockData
alt Valid Data
JSLogic->>JSLogic: Serialize data (JSON or CSV)
JSLogic->>JSLogic: Call downloadFile(content, filename, type)
JSLogic->>User: Triggers file download
else Invalid Data
JSLogic->>JSLogic: Log error, abort
end
Possibly related PRs
Poem
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
index.js (1)
1189-1211: The export function handles data validation and different formats well.The function properly validates that data exists before attempting to export, handles both JSON and CSV formats appropriately, and reuses the downloadFile utility. The special handling for single-item arrays in JSON export is a good user experience touch.
A small suggestion for improved error handling:
if (!Array.isArray(latestMockData) || latestMockData.length === 0) { console.error("No data available to export."); + alert("No data available to export. Please generate data first."); return; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
index.html(1 hunks)index.js(1 hunks)
🔇 Additional comments (2)
index.js (1)
1177-1187: Well-implemented file download utility function.This utility function implements the Blob API and URL.createObjectURL pattern correctly to facilitate browser downloads. Good job properly cleaning up resources with URL.revokeObjectURL.
index.html (1)
164-165: Good addition of export buttons that match the existing UI pattern.The new export buttons are properly positioned alongside the existing copy buttons and follow the same naming convention and function call pattern. This maintains UI consistency and provides users with intuitive export functionality.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
index.js (2)
1196-1218: CSV generation could be improved for special characters.The current CSV implementation uses
JSON.stringify()on each value, which could cause issues with CSV formatting if the data contains commas, quotes, or newlines. A more robust CSV generation approach would be better.function exportMockOutput(format = "json") { if (!Array.isArray(latestMockData) || latestMockData.length === 0) { console.error("No data available to export."); return; } let content = ""; let filename = userInputValue !== "" ? userInputValue : "mock_data"; // Use user input if available if (format === "json") { content = JSON.stringify(latestMockData.length === 1 ? latestMockData[0] : latestMockData, null, 2); filename += ".json"; downloadFile(content, filename, "application/json"); } else if (format === "csv") { if (!latestMockData.length || typeof latestMockData[0] !== "object") return; const keys = Object.keys(latestMockData[0]); - const rows = latestMockData.map(obj => keys.map(k => JSON.stringify(obj[k] ?? ""))); + // Properly escape CSV values to handle commas, quotes, and newlines + const escapeCSV = (value) => { + if (value === null || value === undefined) return ''; + const str = typeof value === 'object' ? JSON.stringify(value) : String(value); + if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) { + return `"${str.replace(/"/g, '""')}"`; + } + return str; + }; + const rows = latestMockData.map(obj => keys.map(k => escapeCSV(obj[k]))); content = [keys.join(","), ...rows.map(r => r.join(","))].join("\n"); filename += ".csv"; downloadFile(content, filename, "text/csv"); } }Also, you might want to add error handling for the download process and provide user feedback if the export fails.
1196-1209: Consider validating the filename before download.The function uses the raw user input for the filename which could potentially contain invalid characters for filenames. Adding validation or sanitization would be beneficial.
function exportMockOutput(format = "json") { if (!Array.isArray(latestMockData) || latestMockData.length === 0) { console.error("No data available to export."); return; } let content = ""; - let filename = userInputValue !== "" ? userInputValue : "mock_data"; // Use user input if available + // Sanitize filename to remove invalid characters + let filename = userInputValue !== "" ? userInputValue.replace(/[^\w\-\.]/g, '_') : "mock_data"; // Use user input if available if (format === "json") { content = JSON.stringify(latestMockData.length === 1 ? latestMockData[0] : latestMockData, null, 2); filename += ".json"; downloadFile(content, filename, "application/json");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
index.html(1 hunks)index.js(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- index.html
🔇 Additional comments (1)
index.js (1)
1177-1187: Good implementation of file download functionality.The function creates a Blob, generates a temporary URL, triggers a download via a dynamically created anchor element, and properly cleans up resources by removing the element and revoking the URL.
| let userInputValue = ""; // This variable will store filename input from user using the following event listener: | ||
|
|
||
| document.getElementById("userInput").addEventListener("input", function (e) { | ||
| userInputValue = e.target.value; | ||
| //console.log("Saved input:", userInputValue); // Optional: see it live | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider adding error handling for the missing DOM element.
The event listener assumes that the element with id "userInput" exists in the DOM, but there's no defensive check for this. If the element doesn't exist when this code runs, it will throw an error.
- document.getElementById("userInput").addEventListener("input", function (e) {
+ const userInputElement = document.getElementById("userInput");
+ if (userInputElement) {
+ userInputElement.addEventListener("input", function (e) {
userInputValue = e.target.value;
//console.log("Saved input:", userInputValue); // Optional: see it live
- });
+ });
+ }Also, the commented console.log should be removed for production code.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| let userInputValue = ""; // This variable will store filename input from user using the following event listener: | |
| document.getElementById("userInput").addEventListener("input", function (e) { | |
| userInputValue = e.target.value; | |
| //console.log("Saved input:", userInputValue); // Optional: see it live | |
| }); | |
| let userInputValue = ""; // This variable will store filename input from user using the following event listener: | |
| const userInputElement = document.getElementById("userInput"); | |
| if (userInputElement) { | |
| userInputElement.addEventListener("input", function (e) { | |
| userInputValue = e.target.value; | |
| //console.log("Saved input:", userInputValue); // Optional: see it live | |
| }); | |
| } |
|
Nice work @BDFL669 |
|
Overall LGTM |
exportMockOutputfunction to generate mock data as .json or .csvSummary by CodeRabbit