Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 25, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced commands for creating relationships between jobs and resources, enhancing resource management capabilities.
    • Added new command for establishing relationships between two specified resources with required flags.
  • Bug Fixes

    • Simplified command execution flow for relationship commands, improving user experience.
  • Documentation

    • Updated command usage instructions to reflect new relationship creation functionalities.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce new command functionalities for creating relationships between jobs and resources in the API. This includes the addition of new commands in various packages, modifications to existing command structures, and enhancements to the API client to handle relationship creation requests. The new commands require specific flags for execution and incorporate validation checks to ensure proper usage. Overall, the updates expand the command capabilities and improve the API's functionality regarding resource relationships.

Changes

File Change Summary
cmd/ctrlc/root/api/create/create.go Added import for relationship package and included relationship.NewRelationshipCmd() in NewCreateCmd function to expand command functionality.
cmd/ctrlc/root/api/create/relationship/jobtoresource/job-to-resource.go Introduced NewCreateRelationshipCmd for creating job-resource relationships with required flags --job and --resource. Added validation in PreRunE and logic in RunE for API client creation and relationship creation.
cmd/ctrlc/root/api/create/relationship/relationship.go Renamed NewCreateRelationshipCmd to NewRelationshipCmd, modified command usage, removed detailed error handling, and added sub-commands for more specific relationship creation functionalities.
cmd/ctrlc/root/api/create/relationship/resourcetoresource/resource-to-resource.go Added NewCreateRelationshipCmd for creating resource-resource relationships with flags for source and target identifiers, workspace ID, and relationship type. Included validation checks in PreRunE and command execution logic in RunE.
internal/api/client.gen.go Introduced new types and methods for handling job-resource relationships, including JSON body types, request body types, and methods for creating relationships. Added response types and parsing functions for server responses.

Possibly related PRs

  • fix: Delete release channel #1: The main PR introduces a new command for creating relationships, while the retrieved PR adds a command for deleting release channels; both involve command structure modifications in the same API framework, indicating a potential overlap in command handling.

Suggested reviewers

  • jsbroks

Poem

🐇 In the garden where we play,
New commands have come to stay.
Jobs and resources, hand in hand,
Building bridges, oh so grand!
With flags to guide, and checks to see,
A world of links, for you and me! 🌼


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 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

🧹 Outside diff range and nitpick comments (9)
cmd/ctrlc/root/api/create/relationship/relationship.go (1)

11-15: Consider enhancing the help text

While the current help text is clear, it could be more informative by mentioning the available subcommands and their purposes.

-		Long:  `Create a relationship between two entities.`,
+		Long:  `Create a relationship between two entities.
+
+Available Commands:
+  - resource-to-resource: Create relationships between resources
+  - job-to-resource: Create relationships between jobs and resources`,
cmd/ctrlc/root/api/create/relationship/jobtoresource/job-to-resource.go (3)

26-36: Remove redundant flag validation

The PreRunE validation is redundant since you're using cmd.MarkFlagRequired() which already handles required flag validation.

Consider removing the entire PreRunE block as Cobra will automatically validate required flags:

-		PreRunE: func(cmd *cobra.Command, args []string) error {
-			if jobId == "" {
-				return fmt.Errorf("job-id is required")
-			}
-
-			if resourceIdentifier == "" {
-				return fmt.Errorf("resource-identifier is required")
-			}
-
-			return nil
-		},

37-60: Enhance error handling

Consider adding validation for API configuration and more specific error handling for the API call.

Suggested improvements:

 		RunE: func(cmd *cobra.Command, args []string) error {
 			apiURL := viper.GetString("url")
 			apiKey := viper.GetString("api-key")
 
+			if apiURL == "" || apiKey == "" {
+				return fmt.Errorf("API URL and API key must be configured")
+			}
+
 			client, err := api.NewAPIKeyClientWithResponses(apiURL, apiKey)
 			if err != nil {
 				return fmt.Errorf("failed to create relationship API client: %w", err)
 			}
 
 			jobIdUUID, err := uuid.Parse(jobId)
 			if err != nil {
 				return fmt.Errorf("failed to parse job-id: %w", err)
 			}
 
 			resp, err := client.CreateJobToResourceRelationship(cmd.Context(), api.CreateJobToResourceRelationshipJSONRequestBody{
 				JobId:              jobIdUUID,
 				ResourceIdentifier: resourceIdentifier,
 			})
 			if err != nil {
-				return fmt.Errorf("failed to create job-to-resource relationship: %w", err)
+				if resp != nil {
+					return fmt.Errorf("failed to create job-to-resource relationship (status: %d): %w", resp.StatusCode(), err)
+				}
+				return fmt.Errorf("failed to create job-to-resource relationship (network error): %w", err)
 			}

63-67: Consider using more specific flag names

The flag names could be more consistent with the API's terminology. Consider using --job-id and --resource-identifier to match the API parameters.

-	cmd.Flags().StringVarP(&jobId, "job", "j", "", "ID of the job (required)")
-	cmd.Flags().StringVarP(&resourceIdentifier, "resource", "r", "", "Identifier of the resource (required)")
+	cmd.Flags().StringVarP(&jobId, "job-id", "j", "", "ID of the job (required)")
+	cmd.Flags().StringVarP(&resourceIdentifier, "resource-identifier", "r", "", "Identifier of the resource (required)")

-	cmd.MarkFlagRequired("job")
-	cmd.MarkFlagRequired("resource")
+	cmd.MarkFlagRequired("job-id")
+	cmd.MarkFlagRequired("resource-identifier")
cmd/ctrlc/root/api/create/relationship/resourcetoresource/resource-to-resource.go (3)

24-27: Update example to match actual flag names and show all valid options

The example should be updated for consistency with the actual implementation:

  1. Use --workspace instead of --workspace-id
  2. Show both valid relationship types
 			# Create a new relationship between two resources
-			$ ctrlc create relationship resource-to-resource --from my-resource --to another-resource --workspace-id 123e4567-e89b-12d3-a456-426614174000 --type depends_on
+			# Create a dependency relationship
+			$ ctrlc create relationship resource-to-resource --from my-resource --to another-resource --workspace 123e4567-e89b-12d3-a456-426614174000 --type depends_on
+			
+			# Create an association relationship
+			$ ctrlc create relationship resource-to-resource --from my-resource --to another-resource --workspace 123e4567-e89b-12d3-a456-426614174000 --type associated_with

28-54: Enhance validation error messages and move UUID validation

Consider the following improvements to the validation:

  1. Make error messages more descriptive for better user experience
  2. Move UUID validation to PreRunE to fail fast before making API calls
 		PreRunE: func(cmd *cobra.Command, args []string) error {
 			if workspaceId == "" {
-				return fmt.Errorf("workspace-id is required")
+				return fmt.Errorf("workspace ID is required (--workspace)")
 			}
+			
+			if _, err := uuid.Parse(workspaceId); err != nil {
+				return fmt.Errorf("invalid workspace ID format: must be a valid UUID")
+			}
 
 			if fromIdentifier == "" {
-				return fmt.Errorf("from is required")
+				return fmt.Errorf("source resource identifier is required (--from)")
 			}
 
 			if toIdentifier == "" {
-				return fmt.Errorf("to is required")
+				return fmt.Errorf("target resource identifier is required (--to)")
 			}
 
 			if relationshipType == "" {
-				return fmt.Errorf("type is required")
+				return fmt.Errorf("relationship type is required (--type)")
 			}

83-91: Improve flag definitions for better usability

Consider the following improvements to the flag definitions:

  1. Use lowercase -t for the type flag (uppercase is unconventional)
  2. Add UUID format requirement to the workspace flag description
 	cmd.Flags().StringVarP(&fromIdentifier, "from", "f", "", "Identifier of the source resource (required)")
 	cmd.Flags().StringVarP(&toIdentifier, "to", "t", "", "Identifier of the target resource (required)")
-	cmd.Flags().StringVarP(&workspaceId, "workspace", "w", "", "ID of the workspace (required)")
-	cmd.Flags().StringVarP(&relationshipType, "type", "T", "", "Type of the relationship (must be 'associated_with' or 'depends_on') (required)")
+	cmd.Flags().StringVarP(&workspaceId, "workspace", "w", "", "Workspace UUID (required)")
+	cmd.Flags().StringVarP(&relationshipType, "type", "t", "", "Type of the relationship (must be 'associated_with' or 'depends_on') (required)")
internal/api/client.gen.go (2)

73-77: Ensure consistent comment punctuation.

Some comments do not end with a period. For consistency, consider ending all comments with a period.


82-92: Ensure consistent comment punctuation.

Some comments do not end with a period. For consistency, consider ending all comments with a period.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dd181db and fbb9320.

📒 Files selected for processing (5)
  • cmd/ctrlc/root/api/create/create.go (2 hunks)
  • cmd/ctrlc/root/api/create/relationship/jobtoresource/job-to-resource.go (1 hunks)
  • cmd/ctrlc/root/api/create/relationship/relationship.go (1 hunks)
  • cmd/ctrlc/root/api/create/relationship/resourcetoresource/resource-to-resource.go (1 hunks)
  • internal/api/client.gen.go (9 hunks)
🔇 Additional comments (16)
cmd/ctrlc/root/api/create/relationship/relationship.go (2)

4-5: LGTM! Clean import structure

The imports are well-organized and reflect proper separation of concerns between job-to-resource and resource-to-resource relationships.


19-20: Verify subcommand implementations

The command structure looks good, but let's verify the implementation of the subcommands to ensure proper error handling and validation.

✅ Verification successful

Both subcommands are well-implemented with proper validation and error handling

The implementation of both relationship subcommands is robust and complete:

  • The resource-to-resource command:

    • Validates all required flags (from, to, workspace, type)
    • Includes type validation for relationship types ('associated_with' or 'depends_on')
    • Prevents self-referential relationships
    • Properly handles UUID parsing and API errors
  • The job-to-resource command:

    • Validates all required flags (job, resource)
    • Includes proper UUID parsing for job ID
    • Handles API errors appropriately

Both implementations follow consistent patterns and include proper documentation with examples.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of relationship subcommands

# Check resourcetoresource implementation
echo "Checking resource-to-resource relationship command implementation..."
ast-grep --pattern 'func NewCreateRelationshipCmd() *cobra.Command {
  $$$
}' resourcetoresource/relationship.go

# Check jobtoresource implementation
echo "Checking job-to-resource relationship command implementation..."
ast-grep --pattern 'func NewCreateRelationshipCmd() *cobra.Command {
  $$$
}' jobtoresource/relationship.go

# Check for required flag validation
echo "Checking flag validation..."
rg -A 5 "Required\(" resourcetoresource/relationship.go jobtoresource/relationship.go

Length of output: 965


Script:

#!/bin/bash
# Let's find the correct paths for these files first
echo "Finding relationship command files..."
fd -t f "relationship.go" cmd/

# Once we find the files, let's check their implementation
echo -e "\nChecking command implementations..."
ast-grep --pattern 'func NewCreateRelationshipCmd() *cobra.Command {
  $$$
}'

# Check for required flag validation in all relationship.go files
echo -e "\nChecking flag validation..."
rg -A 5 "Required\(" cmd/

Length of output: 19340

cmd/ctrlc/root/api/create/create.go (2)

5-5: LGTM! Import statement is properly placed

The new import for the relationship package follows Go conventions and is correctly grouped with related imports.


24-24: Verify command documentation and naming consistency

The relationship command integration looks good, but let's ensure proper documentation and consistent naming.

✅ Verification successful

Let me gather more information about the command documentation and naming consistency.


Command documentation and naming are well-implemented

The relationship commands are well documented and follow consistent naming patterns:

  • Parent command has clear Use, Short, and Long descriptions
  • Subcommands have detailed documentation including examples using heredoc
  • Command naming follows the established pattern with New*Cmd() functions
  • Flag names and descriptions are clear and consistent
  • Command hierarchy and structure align with other create commands
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify help text and command naming consistency

# Check help text for the new relationship command
echo "Checking help text for relationship command..."
./ctrlc create relationship --help

# Verify naming consistency across related commands
echo "Checking command naming patterns..."
ast-grep --pattern 'func New${_}Cmd() *cobra.Command'

# Check for any existing relationship-related commands to ensure consistency
echo "Checking for other relationship commands..."
rg -l "relationship" cmd/

Length of output: 750


Script:

#!/bin/bash
# Check the content of relationship command files to verify documentation and naming
echo "Checking relationship command implementation..."
cat cmd/ctrlc/root/api/create/relationship/relationship.go

echo -e "\nChecking resource-to-resource command..."
cat cmd/ctrlc/root/api/create/relationship/resourcetoresource/resource-to-resource.go

echo -e "\nChecking job-to-resource command..."
cat cmd/ctrlc/root/api/create/relationship/jobtoresource/job-to-resource.go

# Check other create commands for naming pattern comparison
echo -e "\nChecking other create commands for consistency..."
fd -e go . cmd/ctrlc/root/api/create --exclude relationship --exec cat {}

Length of output: 15356

cmd/ctrlc/root/api/create/relationship/jobtoresource/job-to-resource.go (2)

1-12: LGTM: Clean package structure and imports

The package name and imports are well-organized and follow Go conventions.


14-70: Verify command registration and uniqueness

Please ensure this command is properly integrated into the CLI hierarchy.

✅ Verification successful

Let me gather more information to verify the command registration.


Command is properly integrated and distinct

The command is correctly registered in the parent relationship command (cmd/ctrlc/root/api/create/relationship/relationship.go). There are two distinct relationship commands:

  • job-to-resource: For creating job-to-resource relationships
  • resource-to-resource: For creating resource-to-resource relationships

Each serves a different purpose and their naming clearly indicates their distinct functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the command is properly registered and if there are similar commands
# that might cause confusion

# Look for command registration
rg -A 5 "job-to-resource" --type go

# Look for similar relationship commands
ast-grep --pattern 'func New.*RelationshipCmd() *cobra.Command {
  $$$
}'

Length of output: 2343


Script:

#!/bin/bash
# Check if the command is registered in the parent command structure
rg -A 5 "NewCreateRelationshipCmd" --type go

# Look for the relationship command structure
fd relationship cmd -t d

Length of output: 1766

cmd/ctrlc/root/api/create/relationship/resourcetoresource/resource-to-resource.go (2)

1-12: LGTM: Package structure and imports are well-organized

The package name follows the directory structure, and all imports are necessary for the functionality.


59-62: Verify API client security configuration

Please ensure that the API client:

  1. Properly handles sensitive data (API keys, workspace IDs)
  2. Has appropriate timeout and rate limiting configurations
internal/api/client.gen.go (8)

71-78: Consistent struct definition for request body.

The CreateJobToResourceRelationshipJSONBody struct is defined appropriately and follows existing naming conventions and patterns.


80-93: Consistent struct definition for request body.

The CreateResourceToResourceRelationshipJSONBody struct is appropriately defined and aligns with existing patterns.


159-164: Request body type definitions are correct.

The type definitions for CreateJobToResourceRelationshipJSONRequestBody and CreateResourceToResourceRelationshipJSONRequestBody are accurately declared and consistent with the existing codebase.


380-389: New client interface methods added correctly.

The methods CreateJobToResourceRelationship and CreateResourceToResourceRelationship are added to the ClientInterface consistently with existing methods, ensuring extended functionality.


605-651: Method implementations follow existing patterns.

The implementations of CreateJobToResourceRelationship and CreateResourceToResourceRelationship in the Client struct properly adhere to the established patterns in the codebase.


1263-1342: New request constructors are consistent.

The request constructors NewCreateJobToResourceRelationshipRequest and NewCreateResourceToResourceRelationshipRequest are consistent with the patterns used elsewhere, ensuring uniformity in request building.


1905-1914: Response interfaces defined correctly.

The response interfaces for CreateJobToResourceRelationshipResponse and CreateResourceToResourceRelationshipResponse are properly defined in the ClientWithResponsesInterface, aligning with existing interface definitions.


2365-2436: Response types defined appropriately.

The response types CreateJobToResourceRelationshipResponse and CreateResourceToResourceRelationshipResponse are accurately declared, including all necessary fields for handling server responses.

Comment on lines 18 to 25
cmd := &cobra.Command{
Use: "job-to-resource [flags]",
Short: "Create a new relationship between a job and a resource",
Long: `Create a new relationship between a job and a resource.`,
Example: heredoc.Doc(`
# Create a new relationship between a job and a resource
$ ctrlc create relationship job-to-resource --job-id 123e4567-e89b-12d3-a456-426614174000 --resource-identifier my-resource
`),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent flag names in example

The example documentation doesn't match the actual flag names:

  • Example uses --job-id but the actual flag is --job
  • Example uses --resource-identifier but the actual flag is --resource

Update the example to match the actual flags:

 		Example: heredoc.Doc(`
 			# Create a new relationship between a job and a resource
-			$ ctrlc create relationship job-to-resource --job-id 123e4567-e89b-12d3-a456-426614174000 --resource-identifier my-resource
+			$ ctrlc create relationship job-to-resource --job 123e4567-e89b-12d3-a456-426614174000 --resource my-resource
 		`),
📝 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.

Suggested change
cmd := &cobra.Command{
Use: "job-to-resource [flags]",
Short: "Create a new relationship between a job and a resource",
Long: `Create a new relationship between a job and a resource.`,
Example: heredoc.Doc(`
# Create a new relationship between a job and a resource
$ ctrlc create relationship job-to-resource --job-id 123e4567-e89b-12d3-a456-426614174000 --resource-identifier my-resource
`),
cmd := &cobra.Command{
Use: "job-to-resource [flags]",
Short: "Create a new relationship between a job and a resource",
Long: `Create a new relationship between a job and a resource.`,
Example: heredoc.Doc(`
# Create a new relationship between a job and a resource
$ ctrlc create relationship job-to-resource --job 123e4567-e89b-12d3-a456-426614174000 --resource my-resource
`),

Comment on lines +55 to +80
RunE: func(cmd *cobra.Command, args []string) error {
apiURL := viper.GetString("url")
apiKey := viper.GetString("api-key")

client, err := api.NewAPIKeyClientWithResponses(apiURL, apiKey)
if err != nil {
return fmt.Errorf("failed to create relationship API client: %w", err)
}

workspaceIdUUID, err := uuid.Parse(workspaceId)
if err != nil {
return fmt.Errorf("failed to parse workspace-id: %w", err)
}

resp, err := client.CreateResourceToResourceRelationship(cmd.Context(), api.CreateResourceToResourceRelationshipJSONRequestBody{
FromIdentifier: fromIdentifier,
ToIdentifier: toIdentifier,
WorkspaceId: workspaceIdUUID,
Type: relationshipType,
})
if err != nil {
return fmt.Errorf("failed to create resource-to-resource relationship: %w", err)
}

return cliutil.HandleOutput(cmd, resp)
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance API response error handling

The current implementation doesn't check the API response status code or provide detailed error information from the response body.

 			resp, err := client.CreateResourceToResourceRelationship(cmd.Context(), api.CreateResourceToResourceRelationshipJSONRequestBody{
 				FromIdentifier: fromIdentifier,
 				ToIdentifier:   toIdentifier,
 				WorkspaceId:    workspaceIdUUID,
 				Type:           relationshipType,
 			})
 			if err != nil {
-				return fmt.Errorf("failed to create resource-to-resource relationship: %w", err)
+				return fmt.Errorf("API request failed: %w", err)
+			}
+			
+			if resp.StatusCode() >= 400 {
+				return fmt.Errorf("API returned error (status %d): %s", resp.StatusCode(), resp.Body)
 			}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +3615 to +3742
// ParseCreateJobToResourceRelationshipResponse parses an HTTP response from a CreateJobToResourceRelationshipWithResponse call
func ParseCreateJobToResourceRelationshipResponse(rsp *http.Response) (*CreateJobToResourceRelationshipResponse, error) {
bodyBytes, err := io.ReadAll(rsp.Body)
defer func() { _ = rsp.Body.Close() }()
if err != nil {
return nil, err
}

response := &CreateJobToResourceRelationshipResponse{
Body: bodyBytes,
HTTPResponse: rsp,
}

switch {
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
var dest struct {
Message *string `json:"message,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON200 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON400 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON404 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON409 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON500 = &dest

}

return response, nil
}

// ParseCreateResourceToResourceRelationshipResponse parses an HTTP response from a CreateResourceToResourceRelationshipWithResponse call
func ParseCreateResourceToResourceRelationshipResponse(rsp *http.Response) (*CreateResourceToResourceRelationshipResponse, error) {
bodyBytes, err := io.ReadAll(rsp.Body)
defer func() { _ = rsp.Body.Close() }()
if err != nil {
return nil, err
}

response := &CreateResourceToResourceRelationshipResponse{
Body: bodyBytes,
HTTPResponse: rsp,
}

switch {
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
var dest struct {
Message *string `json:"message,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON200 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON400 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON404 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON409 = &dest

case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500:
var dest struct {
Error *string `json:"error,omitempty"`
}
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
return nil, err
}
response.JSON500 = &dest

}

return response, nil
}

Copy link
Contributor

@coderabbitai coderabbitai bot Nov 25, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring repetitive code in response parsing functions.

The parsing functions ParseCreateJobToResourceRelationshipResponse and ParseCreateResourceToResourceRelationshipResponse contain repetitive code similar to other parsing functions in the file. To adhere to the DRY (Don't Repeat Yourself) principle and improve maintainability, consider abstracting the common logic into a shared function or helper method.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this file is generated by a library, ignore generated files

Copy link
Contributor

Choose a reason for hiding this comment

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

@adityachoudhari26, understood. We'll ignore generated files in future reviews.


✏️ Learnings added
Learnt from: adityachoudhari26
PR: ctrlplanedev/cli#2
File: internal/api/client.gen.go:3615-3742
Timestamp: 2024-11-25T05:52:25.043Z
Learning: Files in the `internal/api/` directory are generated by a library and should be ignored during code reviews.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@adityachoudhari26 adityachoudhari26 merged commit 688ad08 into main Nov 25, 2024
1 check was pending
@coderabbitai coderabbitai bot mentioned this pull request Nov 25, 2024
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.

2 participants