Skip to content

Review and update prop validation logic for accuracy #14986

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Conversation

adolfo-pd
Copy link
Collaborator

@adolfo-pd adolfo-pd commented Dec 13, 2024

WHY

Summary by CodeRabbit

  • New Features

    • Enhanced error tracking for form fields with a new errors property in the form context.
    • Introduced new types and functions for handling configurable properties and validation mechanisms.
  • Bug Fixes

    • Relaxed validation rules for string props when the provided value is not a string.
  • Refactor

    • Simplified the useApp hook by updating type dependencies and removing unnecessary code.
  • Chores

    • Updated changelog to reflect the new version and changes made.

Copy link

linear bot commented Dec 13, 2024

Copy link

vercel bot commented Dec 13, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Dec 13, 2024 10:58pm
pipedream-docs ⬜️ Ignored (Inspect) Dec 13, 2024 10:58pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Dec 13, 2024 10:58pm

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Warning

Rate limit exceeded

@adolfo-pd has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 37 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6805a60 and 7c6e6c9.

📒 Files selected for processing (1)
  • packages/connect-react/src/utils/component.ts (1 hunks)

Walkthrough

The changes introduced in this pull request enhance the error handling and validation logic within the FormContext and useApp hook in the React application. The FormContext now includes an errors property for improved error tracking, and the propErrors function has been refactored for better modularity. The useApp hook has been simplified by updating its type dependencies and removing unused code. Additionally, a new file has been created to define types and functions for handling configurable properties, enhancing the overall structure and maintainability of the code.

Changes

File Path Change Summary
packages/connect-react/src/hooks/form-context.tsx - Added errors: Record<string, string[]> to FormContext type.
- Refactored propErrors function to use utility functions for error checking.
packages/connect-react/src/hooks/use-app.tsx - Updated useApp function to use GetAppResponse instead of AppRequestResponse.
- Removed several unused types and functions, simplifying the hook.
packages/connect-react/src/utils/component.ts - Introduced types and functions for handling configurable properties, including validation functions for various property types.
packages/connect-react/CHANGELOG.md - Updated changelog for version [1.0.0-preview.11] to reflect changes in prop validation and rules.
packages/connect-react/package.json - Updated version from 1.0.0-preview.10 to 1.0.0-preview.11.

Possibly related PRs

  • Register fields with form to enable complete error checking #14869: This PR modifies the FormContext to enhance error checking and management of form fields, which is directly related to the changes made in the main PR that also focuses on improving error handling within the FormContext.
  • fix: Enforce string limits #14953: This PR enforces string limits in the FormContext, which aligns with the main PR's updates to the error handling logic for string properties, enhancing validation within the same context.

Suggested labels

bug, enhancement, dependencies, docs, tracked internally, prioritized

Suggested reviewers

  • tjk
  • lcaresia

🐰 In the garden where errors bloom,
A new context brings light to the gloom.
With props validated, oh what a sight,
Our forms now handle errors just right!
Hopping along, we simplify the way,
For a smoother, brighter coding day! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0cadd6 and a84b407.

⛔ Files ignored due to path filters (1)
  • packages/connect-react/examples/nextjs/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • packages/connect-react/src/hooks/form-context.tsx (4 hunks)
  • packages/connect-react/src/hooks/use-app.tsx (1 hunks)
  • packages/connect-react/src/utils/component.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/connect-react/src/utils/component.ts

[error] 84-84: Comparing to itself is potentially pointless.

(lint/suspicious/noSelfCompare)

🔇 Additional comments (2)
packages/connect-react/src/hooks/form-context.tsx (1)

175-209: Refactored validation enhances modularity and readability

The refactoring of the propErrors function to utilize separate validation functions for each prop type (appPropErrors, booleanPropErrors, integerPropErrors, etc.) improves code modularity. This approach makes the validation logic more maintainable and easier to extend in the future.

packages/connect-react/src/hooks/use-app.tsx (1)

Line range hint 10-19: Simplification of useApp hook improves clarity

Updating the useApp hook to use the GetAppResponse type and removing unused types and functions streamlines the codebase. This simplification reduces complexity and enhances maintainability.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (3)
packages/connect-react/src/utils/component.ts (3)

52-62: Add explicit return for the success case

The function implicitly returns undefined when no errors are found. For better clarity and maintainability, consider adding an explicit return.

 export function arrayPropErrors(opts: ValidationOpts<ConfigurablePropStringArray>): string[] | undefined {
   const _values = valuesFromOptions(opts.value)
   if (!opts.prop.default && typeof _values === "undefined") {
     return [
       "required",
     ]
   }
   if (!opts.prop.default && Array.isArray(_values) && !_values.length) return [
     "empty array",
   ]
+  return undefined
 }

94-105: Add explicit return for consistency

Similar to arrayPropErrors, add an explicit return for the success case to maintain consistency across validation functions.

 export function stringPropErrors(opts: ValidationOpts<ConfigurablePropString>): string[] | undefined {
   const _value = valueFromOption(opts.value)

   if (!opts.prop.default) {
     if (typeof _value === "undefined" || _value == null) return [
       "required",
     ]
     if (!String(_value).length) return [
       "string must not be empty",
     ]
   }
+  return undefined
 }

144-184: Consider breaking down the validation logic

The appPropErrors function handles multiple validation scenarios, making it complex to maintain. Consider breaking it down into smaller, focused functions.

Example refactoring:

function validateOAuthToken(value: OauthAppPropValue): string[] {
  return !value.oauth_access_token ? ["missing oauth token"] : []
}

function validateCustomFields(app: App, value: AppPropValueWithCustomFields<AppCustomField[]>): string[] {
  const customFields = getCustomFields(app)
  return customFields
    .filter(cf => !cf.optional && !value[cf.name])
    .map(cf => `missing custom field: ${cf.name}`)
}

export function appPropErrors(opts: ValidationOpts<ConfigurablePropApp>): string[] | undefined {
  const { app, value } = opts
  
  if (!app) return ["app field not registered"]
  if (!value) return ["no app configured"]
  if (typeof value !== "object") return ["not an app"]
  
  const _value = value as PropValue<"app">
  if (!("authProvisionId" in _value && !_value.authProvisionId)) return undefined
  
  if (!app.auth_type) return undefined
  
  const errors = []
  
  if (app.auth_type === "oauth") {
    errors.push(...validateOAuthToken(_value as OauthAppPropValue))
  }
  
  if (app.auth_type === "oauth" || app.auth_type === "keys") {
    errors.push(...validateCustomFields(app, _value as AppPropValueWithCustomFields<AppCustomField[]>))
  }
  
  if (app.auth_type !== "none") {
    errors.push("no auth provision configured")
  }
  
  return errors.length > 0 ? errors : undefined
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a84b407 and 98a2706.

📒 Files selected for processing (1)
  • packages/connect-react/src/utils/component.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/connect-react/src/utils/component.ts

[error] 85-85: Comparing to itself is potentially pointless.

(lint/suspicious/noSelfCompare)

🔇 Additional comments (3)
packages/connect-react/src/utils/component.ts (3)

5-16: LGTM: Well-structured type definition and safe value extraction

The PropOptionValue type and valueFromOption function are well-implemented with proper type safety and handling of edge cases.


107-123: LGTM: Well-structured type definitions

The custom fields types are well-defined and make good use of TypeScript features for type safety.


77-79: ⚠️ Potential issue

Address existing issues with conditional logic and NaN check

Two issues need to be addressed as previously noted:

  1. The conditional logic needs parentheses for proper evaluation
  2. The NaN check should use Number.isNaN

Apply these fixes:

-if (!prop.default && value == null || typeof value === "undefined") return [
+if (!prop.default && (value == null || typeof value === "undefined")) return [
   "required",
 ]

-if (_value !== _value) return [
+if (Number.isNaN(_value)) return [
   "not a number",
 ]

Also applies to: 85-87

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
packages/connect-react/CHANGELOG.md (1)

6-7: Consider adding more details to the changelog entries.

While the entries are clear, they could be more specific about:

  • What inconsistencies were fixed in the prop validation
  • How the string prop validation was relaxed (e.g., what behavior to expect)

This would help users better understand the impact of these changes.

Example of more detailed entries:

-Make prop validation more consistent with app behavior
-Relax validation of string props when value is not a string
+Make prop validation more consistent with app behavior by [specific changes]
+Relax validation of string props to handle non-string values by [specific behavior]
packages/connect-react/src/utils/component.ts (2)

11-16: Improve type safety with type predicates

Consider using a type predicate to improve type narrowing and make the code more type-safe.

+type isPropOptionValue = <T>(value: unknown): value is PropOptionValue<T> => {
+  return typeof value === "object" && value !== null && "__lv" in value;
+}
+
-export function valueFromOption<T>(value: T | PropOptionValue<T>): T | undefined | null {
+export function valueFromOption<T>(value: T | PropOptionValue<T>): T {
-  if (typeof value === "object" && value && "__lv" in value) {
+  if (isPropOptionValue<T>(value)) {
     return (value as PropOptionValue<T>).__lv.value
   }
   return value
 }

145-185: Improve readability with early returns and error message organization

The function has deeply nested conditionals that make it hard to follow. Consider restructuring with early returns and organizing error messages better.

 export function appPropErrors(opts: ValidationOpts<ConfigurablePropApp>): string[] | undefined {
   const { app, value } = opts
+  const errors: string[] = []
+
   if (!app) {
     return ["app field not registered"]
   }
   if (!value) {
     return ["no app configured"]
   }
   if (typeof value !== "object") {
     return ["not an app"]
   }
+
   const _value = value as PropValue<"app">
-  if ("authProvisionId" in _value && !_value.authProvisionId) {
-    if (app.auth_type) {
-      const errs = []
-      if (app.auth_type === "oauth" && !(_value as OauthAppPropValue).oauth_access_token) {
-        errs.push("missing oauth token")
-      }
-      if (app.auth_type === "oauth" || app.auth_type === "keys") {
-        const customFields = getCustomFields(app)
-        const _valueWithCustomFields = _value as AppPropValueWithCustomFields<typeof customFields>
-        for (const cf of customFields) {
-          if (!cf.optional && !_valueWithCustomFields[cf.name]) {
-            errs.push(`missing custom field: ${cf.name}`)
-          }
-        }
-      }
-      if (app.auth_type !== "none")
-        errs.push("no auth provision configured")
-      return errs
+
+  if (!("authProvisionId" in _value) || _value.authProvisionId) {
+    return undefined
+  }
+
+  if (!app.auth_type) {
+    return undefined
+  }
+
+  if (app.auth_type === "oauth") {
+    if (!(_value as OauthAppPropValue).oauth_access_token) {
+      errors.push("missing oauth token")
     }
   }
+
+  if (app.auth_type === "oauth" || app.auth_type === "keys") {
+    const customFields = getCustomFields(app)
+    const _valueWithCustomFields = _value as AppPropValueWithCustomFields<typeof customFields>
+    for (const cf of customFields) {
+      if (!cf.optional && !_valueWithCustomFields[cf.name]) {
+        errors.push(`missing custom field: ${cf.name}`)
+      }
+    }
+  }
+
+  if (app.auth_type !== "none") {
+    errors.push("no auth provision configured")
+  }
+
+  return errors.length > 0 ? errors : undefined
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 98a2706 and 6805a60.

📒 Files selected for processing (3)
  • packages/connect-react/CHANGELOG.md (1 hunks)
  • packages/connect-react/package.json (1 hunks)
  • packages/connect-react/src/utils/component.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/connect-react/package.json
🔇 Additional comments (3)
packages/connect-react/CHANGELOG.md (1)

4-5: LGTM! Version and date format are correct.

The version number follows semantic versioning, and the preview designation is appropriate for breaking changes.

packages/connect-react/src/utils/component.ts (2)

25-45: ⚠️ Potential issue

Fix duplicate push operation and improve error handling

There are several issues in this function:

  1. Line 35 causes duplicate push when the value is already pushed in line 33
  2. Generic error messages make debugging difficult
  3. Missing explicit return type annotation
-export function valuesFromOptions<T>(value: unknown | T[] | PropOptions<T>): T[] {
+export function valuesFromOptions<T>(value: unknown | T[] | PropOptions<T>): T[] {
   if (typeof value === "object" && value && "selectedOptions" in value && Array.isArray(value.selectedOptions)) {
     const selectedOptions = value.selectedOptions as PropOption<T>[]
     const results: T[] = []
     for (const so of selectedOptions) {
       if (typeof so === "object" && so && "emitValue" in so) {
         const emitValue = so.emitValue as T | PropOptionValue<T>
         if (typeof emitValue === "object" && emitValue && "__lv" in emitValue) {
           results.push(emitValue.__lv.value)
+          continue
         }
-        results.push(emitValue as T)
+        results.push(emitValue as T)
       } else {
-        throw "unexpected value"
+        throw new Error("Invalid option structure: missing emitValue property")
       }
     }
     return results
   }
   if (!Array.isArray(value))
-    throw "unexpected value"
+    throw new Error("Invalid value: expected array or PropOptions object")
   return value as T[]
 }

Likely invalid or redundant comment.


125-143: ⚠️ Potential issue

Add error handling and avoid array mutation

The function has two issues:

  1. Missing error handling for JSON.parse
  2. Mutates array with push
 function getCustomFields(app: App): AppCustomField[] {
   const isOauth = app.auth_type === "oauth"
-  const userDefinedCustomFields = JSON.parse(app.custom_fields_json || "[]")
+  let userDefinedCustomFields: AppCustomField[] = []
+  try {
+    userDefinedCustomFields = JSON.parse(app.custom_fields_json || "[]")
+  } catch (error) {
+    console.error("Failed to parse custom_fields_json:", error)
+    userDefinedCustomFields = []
+  }
   if ("extracted_custom_fields_names" in app && app.extracted_custom_fields_names) {
     const extractedCustomFields = ((app as AppWithExtractedCustomFields).extracted_custom_fields_names || []).map(
       (name) => ({
         name,
       }),
     )
-    userDefinedCustomFields.push(...extractedCustomFields)
+    userDefinedCustomFields = [...userDefinedCustomFields, ...extractedCustomFields]
   }
   return userDefinedCustomFields.map((cf: AppCustomField) => {
     return {
       ...cf,
       optional: cf.optional || isOauth,
     }
   })
 }

Likely invalid or redundant comment.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant