Skip to content

feat: create projects/project memberships/environments/folders #17

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

Merged
merged 4 commits into from
Apr 11, 2025

Conversation

DanielHougaard
Copy link
Member

@DanielHougaard DanielHougaard commented Apr 11, 2025

This PR implements the creation of projects, project memberships, environments, and folders. This is an extension of the current SDK, which adds quite a few new resources. We'll need to further extend this in the future to support other operations such as read and update.

I also went ahead and fixed zod errors not being properly formatted. Previously they would appear as [object Object], but now they're displayed as their json string value like so:

[URL=http://localhost:8080/api/v2/workspace/437cbb5e-e95e-4616-bcdb-87527c9dd806/memberships] [Method=post] [StatusCode=422] {"reqId":"req-bMe4e1DVxjPvr3","statusCode":422,"message":[{"validation":"email","code":"invalid_string","message":"Invalid email","path":["emails",0]}],"error":"ValidationFailure"}

Summary by CodeRabbit

  • Documentation

    • Updated documentation to detail new functionalities for managing projects and environments.
  • New Features

    • Enabled creation of projects, environments, and folders, along with functionality to invite project members.
    • Integrated enhancements for secure authentication using environment variables.
  • Refactor

    • Improved error messaging for specific API responses to provide clearer feedback.
  • Tests

    • Revised test flows to align with the new project, environment, and folder management operations.

@DanielHougaard DanielHougaard requested a review from maidul98 April 11, 2025 21:51
@DanielHougaard DanielHougaard self-assigned this Apr 11, 2025
Copy link

coderabbitai bot commented Apr 11, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes enhance the SDK by adding new client classes for projects, environments, and folders along with their corresponding methods. The SDK now supports operations to create projects (with invitation capabilities), environments, and folders. Additionally, the README documentation has been updated to reflect these new functionalities. Error handling has been refined for specific API error responses. Finally, the tests have been revised to utilize environment variables for authentication and validate the new project management workflow.

Changes

File(s) Change Summary
README.md Updated documentation with new sections for projects (create, inviteMembers) and environments (create, folder creation) detailing parameters and return types.
src/custom/environments.ts, src/custom/projects.ts, src/custom/folders.ts Introduced new client classes (EnvironmentsClient, ProjectsClient, FoldersClient) including methods (create, inviteMembers for projects) and related type definitions for handling API requests.
src/custom/errors.ts Refined error handling by enhancing message construction for Axios errors, especially replacing the message with a JSON string for status code 422.
src/index.ts Integrated new client instances into the InfisicalSDK by adding private fields and public access methods; clients are initialized during construction and authentication.
test/index.ts Revised test logic: replaced legacy secret management with new flows for project, environment, and folder creation, and added member invitation functionality using environment variables for authentication.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant S as InfisicalSDK
    participant P as ProjectsClient
    participant E as EnvironmentsClient
    participant F as FoldersClient
    participant A as API

    U->>S: authenticate(credentials)
    S->>S: Initialize Clients (#projectsClient, #environmentsClient, #foldersClient)
    
    U->>S: projects().create(projectData)
    P->>A: POST /createProject
    A-->>P: projectResponse
    P-->>S: projectData

    U->>S: environments().create(envData)
    E->>A: POST /createEnvironment
    A-->>E: environmentResponse
    E-->>S: environmentData

    U->>S: folders().create(folderData)
    F->>A: POST /createFolder
    A-->>F: folderResponse
    F-->>S: folderData

    U->>S: projects().inviteMembers(inviteData)
    P->>A: POST /inviteMembers
    A-->>P: invitationResponse
    P-->>S: invitationResult
Loading

Poem

I'm a rabbit leaping with pure delight,
Hoping through code in the soft moonlight.
New projects and folders make my heart race,
Environments bloom in this digital space.
With each change, I nibble on fresh API treats,
Celebrating these updates with happy, bouncy beats!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d33090a and 4949d78.

📒 Files selected for processing (1)
  • README.md (1 hunks)

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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

@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: 0

🧹 Nitpick comments (3)
src/custom/projects.ts (1)

38-55: Invite members implementation includes proper validation.

The method correctly validates that either usernames or emails must be provided before making the API call, which prevents unnecessary requests.

Consider adding more comprehensive validation for the email and username arrays. For example, you might want to check that the email strings are valid email formats and that usernames meet any requirements your system has.

 inviteMembers = async (options: InviteMemberToProjectOptions): Promise<InviteMemberToProjectResult["memberships"]> => {
 	try {
 		if (!options.usernames?.length && !options.emails?.length) {
 			throw new Error("Either usernames or emails must be provided");
 		}
+
+		// Additional validation for emails if provided
+		if (options.emails?.length) {
+			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+			for (const email of options.emails) {
+				if (!emailRegex.test(email)) {
+					throw new Error(`Invalid email format: ${email}`);
+				}
+			}
+		}
 
 		const res = await this.#apiInstance.apiV2WorkspaceProjectIdMembershipsPost(
 			{
 				projectId: options.projectId,
 				apiV2WorkspaceProjectIdMembershipsPostRequest: options
 			},
 			this.#requestOptions
 		);
 		return res.data.memberships;
 	} catch (err) {
 		throw newInfisicalError(err);
 	}
 };
test/index.ts (1)

8-8: Consider using environment variables or local config for test emails.

Storing a placeholder email here might be acceptable for demonstration, but make sure no sensitive email is committed if used in production tests.

README.md (1)

435-483: Comprehensive documentation of project creation and invitation methods.

This section provides clear parameters and return types, ensuring users can easily follow the code for project creation and member invitations. Adding a small code example for multiple different project types (e.g., kms, ssh) might further clarify usage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6e5a03 and d33090a.

📒 Files selected for processing (7)
  • README.md (1 hunks)
  • src/custom/environments.ts (1 hunks)
  • src/custom/errors.ts (1 hunks)
  • src/custom/folders.ts (1 hunks)
  • src/custom/projects.ts (1 hunks)
  • src/index.ts (4 hunks)
  • test/index.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
src/custom/folders.ts (1)
src/custom/errors.ts (1)
  • newInfisicalError (31-57)
src/custom/projects.ts (1)
src/custom/errors.ts (1)
  • newInfisicalError (31-57)
src/custom/environments.ts (1)
src/custom/errors.ts (1)
  • newInfisicalError (31-57)
test/index.ts (1)
test/index.js (1)
  • client (4-4)
src/index.ts (3)
src/custom/environments.ts (1)
  • EnvironmentsClient (11-33)
src/custom/projects.ts (1)
  • ProjectsClient (16-56)
src/custom/folders.ts (1)
  • FoldersClient (11-35)
🔇 Additional comments (22)
src/custom/errors.ts (1)

36-40: Improved error handling for validation errors.

The change enhances error reporting by providing more detailed information for validation errors (status 422). This addresses the issue mentioned in the PR description where errors were previously displayed as [object Object].

src/custom/folders.ts (2)

6-9: Type definitions look good.

The types correctly extend the API request type while mapping projectId to workspaceId to provide a more intuitive API for users.


19-34: Successfully implemented folder creation functionality.

The implementation follows good practices with proper error handling using the newInfisicalError function.

Can you confirm that mapping projectId to workspaceId on line 25 is intentional? This suggests an inconsistency in naming between the API and the SDK, which could potentially be confusing to users. If this mapping is necessary, consider adding a code comment explaining the reason.

src/custom/environments.ts (2)

6-9: Type definitions are appropriate.

The types properly define the structure required for creating environments, mapping the project ID to workspace ID.


19-32: Environment creation implementation looks good.

The method implementation follows the established pattern with proper error handling.

On line 24, you're passing both workspaceId: options.projectId separately and the full options object which still includes projectId. Is this intentional? The API might receive both parameters, which could be confusing. Consider removing projectId from the options object before passing it, or document this behavior.

src/custom/projects.ts (2)

11-15: Well-defined type definitions.

The types correctly map to the corresponding API request and response types.


24-36: Project creation implementation is solid.

The implementation correctly creates a project and handles errors appropriately.

src/index.ts (5)

9-11: Good import structure and clarity in naming.

These newly introduced client imports properly align with existing naming conventions and make the code self-explanatory.


32-34: Neat encapsulation for new client references.

Defining these private fields keeps the code organized, ensuring each client object’s lifecycle is managed within this SDK class. No issues found.


50-52: Instantiation logic is consistent with existing patterns.

Initializing the new clients in the constructor follows the established approach for the other clients. This maintains a cohesive class design.


74-76: Re-initialization after authentication looks good.

Recreating each client with updated request options ensures the SDK maintains the correct authorization state. The design is consistent with the rest of the code.


82-84: Well-structured getter methods.

Providing simple access to your new client instances helps maintain a clean public API.

test/index.ts (8)

10-11: Great use of environment variables for credentials.

This ensures credentials are not hardcoded, improving security.


13-15: Good defensive check for missing credentials.

Failing early reduces confusion and provides clearer error feedback to developers.


17-20: Authentication flow is straightforward and consistent.

The universalAuth login call neatly integrates environment-provided credentials.


22-29: Project creation step is clear.

These parameters (name, description, type, slug) cover the essential fields for a new project.


30-35: Environment creation follows logical steps.

Properly references the newly created project’s ID. This ensures a correct linkage.


37-42: Folder creation code is intuitive.

Aligns with the environment slug and references the project ID.


44-49: Project invitation looks properly handled.

Inviting members with roles is clearly expressed.


51-51: Logging membership data for debugging.

This is helpful for verifying correct invites and debugging.

README.md (2)

485-505: Excellent explanation for environment creation.

Well-detailed parameters and usage info make creating environments straightforward.


506-527: Folder creation documentation is clear and aligns with the code.

Providing the optional description parameter and path is a nice detail. These instructions enable new users to quickly implement folder functionality.

@DanielHougaard DanielHougaard merged commit 5261fbb into main Apr 11, 2025
1 of 2 checks passed
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