Skip to content

fix: add robust data validation for serial terminal API responses - #53

Open
m50S79sM6SRNp8Jn wants to merge 1 commit into
masterfrom
fix/serial-terminal-validation
Open

fix: add robust data validation for serial terminal API responses#53
m50S79sM6SRNp8Jn wants to merge 1 commit into
masterfrom
fix/serial-terminal-validation

Conversation

@m50S79sM6SRNp8Jn

@m50S79sM6SRNp8Jn m50S79sM6SRNp8Jn commented Nov 23, 2025

Copy link
Copy Markdown
Collaborator
  • Add Array.isArray() validation for response data
  • Integrate useAlert for better error handling and user feedback
  • Add missing ref import for reactive state management
  • Ensure empty array fallback for invalid API responses
  • Improve error handling with consistent alert messaging

Summary by CodeRabbit

  • New Features

    • Added alert notifications to inform users of operation failures and errors during serial port management.
  • Bug Fixes

    • Enhanced data validation for serial port responses to ensure proper handling.
    • Improved error handling to provide feedback across all failure scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

- Add Array.isArray() validation for response data
- Integrate useAlert for better error handling and user feedback
- Add missing ref import for reactive state management
- Ensure empty array fallback for invalid API responses
- Improve error handling with consistent alert messaging

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 23, 2025

Copy link
Copy Markdown

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'version', 'project', 'review', 'style', 'commits', 'checks', 'notes'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Walkthrough

The pull request enhances useSerialTerminal.js by adding alert notifications and stricter data validation. Changes include integrating a new useAlert composable, requiring response data to be an array before use, and dispatching user-facing alerts for error and non-success scenarios.

Changes

Cohort / File(s) Summary
Alert Integration & Data Validation
src/composables/useSerialTerminal.js
Added ref import and useAlert composable integration; initialized sendAlert within useSerialPorts; tightened response handling to validate response.data.data is an array, resetting serialPortList to [] if invalid; augmented error handling with alert dispatch for non-success responses and catch blocks.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant useSerialTerminal
    participant API
    participant useAlert
    
    Component->>useSerialTerminal: getPortList() or setSerial()
    useSerialTerminal->>API: Request port data
    alt Success with Valid Response
        API-->>useSerialTerminal: response.data.data (array)
        useSerialTerminal->>useSerialTerminal: Set serialPortList
    else Success with Invalid Data
        API-->>useSerialTerminal: response.data.data (not array)
        useSerialTerminal->>useSerialTerminal: Set serialPortList = []
        useSerialTerminal->>useAlert: sendAlert(title, message)
        useAlert-->>Component: Display validation error
    else Error or Non-Success
        API-->>useSerialTerminal: Error response
        useSerialTerminal->>useSerialTerminal: Set serialPortList = []
        useSerialTerminal->>useAlert: sendAlert(title, message)
        useAlert-->>Component: Display error alert
    else Exception
        API--X useSerialTerminal: Exception thrown
        useSerialTerminal->>useSerialTerminal: Set serialPortList = []
        useSerialTerminal->>useAlert: sendAlert(title, message)
        useAlert-->>Component: Display error alert
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Single file modified with consistent pattern changes across multiple functions
  • Validation logic is straightforward array type checking
  • No changes to method signatures or public API surface

Poem

🐰 Alert, alert! The ports are validated bright,
No more silent failures in the night!
With array checks and messages clear,
Every error whispers true and fair.
A rabbit's refactor, neat and tight! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding data validation for serial terminal API responses, which matches the core objective of implementing Array.isArray() validation and ensuring proper response handling.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/serial-terminal-validation

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/composables/useSerialTerminal.js (2)

33-35: Fix error message wording.

The phrase "Catch to get serial port list" is awkward for user-facing error messages.

Apply this diff to improve clarity:

-      const message = error.message || 'Catch to get serial port list';
+      const message = error.message || 'Failed to get serial port list';

58-60: Fix error message wording.

The phrase "Catch to set serial port" is awkward for user-facing error messages.

Apply this diff to improve clarity:

-      const message = error.message || 'Catch to set serial port';
+      const message = error.message || 'Failed to set serial port';
♻️ Duplicate comments (1)
src/composables/useSerialTerminal.js (1)

47-51: Consider alerting on malformed data and simplify validation.

Same issues as in getPortList (lines 22-26): the validation silently fails on malformed data and includes a redundant truthiness check.

Apply this diff:

-        if (response.data.data && Array.isArray(response.data.data)) {
+        if (Array.isArray(response.data.data)) {
           serialPortList.value = response.data.data;
         } else {
           serialPortList.value = [];
+          sendAlert('warning', 'Serial', 'Received unexpected data format from server');
         }
🧹 Nitpick comments (2)
src/composables/useSerialTerminal.js (2)

22-26: Consider alerting on malformed data and simplify validation.

The validation correctly falls back to an empty array when data is not an array, but this silent failure could hide API or server-side issues. Consider sending an alert when response.data.code === 0 but the data shape is unexpected.

Additionally, the response.data.data && check is redundant since Array.isArray() already returns false for null and undefined.

Apply this diff to simplify validation and add alerting:

-        if (response.data.data && Array.isArray(response.data.data)) {
+        if (Array.isArray(response.data.data)) {
           serialPortList.value = response.data.data;
         } else {
           serialPortList.value = [];
+          sendAlert('warning', 'Serial', 'Received unexpected data format from server');
         }

18-62: Consider extracting common validation logic.

Both getPortList and setSerial share identical validation and error handling patterns. Extracting this into a helper function would improve maintainability and ensure consistency.

Consider adding a helper function like this at the module level:

const handleSerialResponse = (response, sendAlert, actionDescription) => {
  if (response.status === 200 && response.data.code === 0) {
    if (Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      sendAlert('warning', 'Serial', 'Received unexpected data format from server');
      return [];
    }
  } else {
    const message = response.data.msg || `Failed to ${actionDescription}`;
    sendAlert('error', 'Serial', message);
    return [];
  }
};

Then simplify both functions:

const getPortList = async () => {
  try {
    const response = await http.get('/serial');
    serialPortList.value = handleSerialResponse(response, sendAlert, 'get serial port list');
  } catch (error) {
    const message = error.message || 'Failed to get serial port list';
    sendAlert('error', 'Serial', message);
    serialPortList.value = [];
  }
};
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06b1988 and ab9da02.

📒 Files selected for processing (1)
  • src/composables/useSerialTerminal.js (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/composables/useSerialTerminal.js (1)
src/utils/http.js (1)
  • http (30-33)
🔇 Additional comments (2)
src/composables/useSerialTerminal.js (2)

3-3: LGTM! Essential imports added.

The ref import fixes a missing dependency for the reactive references used at lines 12-13, and the useAlert import provides the error notification functionality used throughout the file.

Also applies to: 7-7


16-16: LGTM! Proper alert initialization.

The sendAlert function is correctly initialized and scoped within the composable function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant