Skip to content

chore: get env by name endpoint#1061

Merged
adityachoudhari26 merged 1 commit intomainfrom
get-env-by-name
Apr 24, 2026
Merged

chore: get env by name endpoint#1061
adityachoudhari26 merged 1 commit intomainfrom
get-env-by-name

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Apr 24, 2026

Summary by CodeRabbit

Release Notes

  • New Features

    • New API endpoint enables retrieval of environments by name within a workspace, offering an intuitive lookup method alongside existing ID-based approaches and ensuring appropriate error handling when environments are not found
  • Tests

    • Added comprehensive test coverage for the new environment name-based lookup feature, validating successful retrieval with complete environment details and verifying proper error responses for missing resources

Copilot AI review requested due to automatic review settings April 24, 2026 20:19
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

📝 Walkthrough

Walkthrough

A new GET endpoint is introduced to retrieve an environment by name within a workspace (GET /v1/workspaces/{workspaceId}/environments/name/{name}). The implementation includes route handler refactoring to extract system-lookup logic into a shared helper, corresponding OpenAPI schema definitions across multiple files, and end-to-end tests validating the functionality. Schema property removals also update deployment variable type definitions.

Changes

Cohort / File(s) Summary
OpenAPI Specification
apps/api/openapi/openapi.json, apps/api/openapi/paths/environments.jsonnet
Defined new getEnvironmentByName endpoint with workspaceId and name path parameters, returning EnvironmentWithSystems on success with 400 and 404 error handling.
TypeScript Type Definitions
apps/api/src/types/openapi.ts, e2e/api/schema.ts
Added operations.getEnvironmentByName operation signatures; updated schema.ts with new environment-by-name path and removed defaultValue property from DeploymentVariable and UpsertDeploymentVariableRequest schemas.
Route Implementation
apps/api/src/routes/v1/workspaces/environments.ts
Added new GET-by-name route handler; refactored existing GET-by-id handler to delegate system lookup and response shaping to a shared getEnvironmentWithSystems() helper function.
End-to-End Tests
e2e/tests/api/environments.spec.ts
Added two new test cases validating retrieval of environments by name (including correct metadata and resource cleanup) and 404 behavior for non-existent names.

Sequence Diagram

sequenceDiagram
    participant Client
    participant RouteHandler as Route Handler
    participant Database as Environment<br/>Lookup
    participant SystemHelper as getEnvironmentWithSystems<br/>Helper
    participant SystemDB as System<br/>Lookup

    Client->>RouteHandler: GET /v1/workspaces/{id}/environments/name/{name}
    RouteHandler->>Database: Find environment by name
    alt Environment found
        Database-->>RouteHandler: Environment data
        RouteHandler->>SystemHelper: getEnvironmentWithSystems(env)
        SystemHelper->>SystemDB: Fetch associated systems
        SystemDB-->>SystemHelper: Systems list
        SystemHelper-->>RouteHandler: EnvironmentWithSystems
        RouteHandler-->>Client: 200 EnvironmentWithSystems
    else Environment not found
        Database-->>RouteHandler: null
        RouteHandler-->>Client: 404 ErrorResponse
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • ctrlplane#1058: Modifies the same apps/api/src/routes/v1/workspaces/environments.ts file to add uniqueness validation and conflict handling for environment create/upsert operations.

Suggested reviewers

  • jsbroks

Poem

🐰 A bunny finds joy in the name-based way,
No more IDs needed—just query by day!
Through schemas and routes, the logic now flows,
Systems are bundled wherever it goes! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding a new endpoint to retrieve environments by name, which is the primary focus across all modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch get-env-by-name

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Copy Markdown
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.

Caution

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

⚠️ Outside diff range comments (1)
apps/api/src/routes/v1/workspaces/environments.ts (1)

73-80: ⚠️ Potential issue | 🟡 Minor

system.slug is incorrectly populated from system.name.

In the mapped systems array, slug is set to r.system.name instead of r.system.slug. This pre-existing bug (previously inside getEnvironment) is now shared by both the getEnvironment and the new getEnvironmentByName responses, so API consumers of both endpoints will receive the environment's system name where the slug is expected. Since this PR extracts and reuses this logic, it's a good opportunity to correct it.

🐛 Proposed fix
   const systems = systemRows.map((r) => ({
     id: r.system.id,
     workspaceId: r.system.workspaceId,
     name: r.system.name,
-    slug: r.system.name,
+    slug: r.system.slug,
     description: r.system.description,
     metadata: r.system.metadata,
   }));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/api/src/routes/v1/workspaces/environments.ts` around lines 73 - 80, The
systems mapping sets slug incorrectly to r.system.name; update the mapping that
builds the systems array (where systemRows.map(...) creates const systems) to
assign slug: r.system.slug instead of slug: r.system.name so both getEnvironment
and getEnvironmentByName responses return the correct system.slug value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@apps/api/src/routes/v1/workspaces/environments.ts`:
- Around line 73-80: The systems mapping sets slug incorrectly to r.system.name;
update the mapping that builds the systems array (where systemRows.map(...)
creates const systems) to assign slug: r.system.slug instead of slug:
r.system.name so both getEnvironment and getEnvironmentByName responses return
the correct system.slug value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b4213bb0-3013-46d7-a240-d2ce4db848ac

📥 Commits

Reviewing files that changed from the base of the PR and between 5ad7b81 and a6584b6.

📒 Files selected for processing (6)
  • apps/api/openapi/openapi.json
  • apps/api/openapi/paths/environments.jsonnet
  • apps/api/src/routes/v1/workspaces/environments.ts
  • apps/api/src/types/openapi.ts
  • e2e/api/schema.ts
  • e2e/tests/api/environments.spec.ts

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds a new API endpoint to fetch a workspace environment by its name, and updates the OpenAPI artifacts and e2e coverage accordingly.

Changes:

  • Implement GET /v1/workspaces/{workspaceId}/environments/name/{name} in the environments router.
  • Extend OpenAPI path definitions and generated OpenAPI TypeScript types to include the new operation.
  • Add Playwright e2e tests covering successful lookup by name and 404 for missing names.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
e2e/tests/api/environments.spec.ts Adds e2e tests for “get environment by name” and missing-name behavior.
e2e/api/schema.ts Updates generated e2e OpenAPI TS schema to include the new endpoint/operation.
apps/api/src/types/openapi.ts Updates generated API-side OpenAPI TS types with getEnvironmentByName.
apps/api/src/routes/v1/workspaces/environments.ts Implements the handler and wires the new /name/:name route; refactors shared “env + systems” response building.
apps/api/openapi/paths/environments.jsonnet Defines the new OpenAPI path entry for lookup-by-name.
apps/api/openapi/openapi.json Adds the new path to the compiled OpenAPI JSON.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +103 to +118
const getEnvironmentByName: AsyncTypedHandler<
"/v1/workspaces/{workspaceId}/environments/name/{name}",
"get"
> = async (req, res) => {
const { workspaceId, name } = req.params;

const env = await db.query.environment.findFirst({
where: and(
eq(schema.environment.name, name),
eq(schema.environment.workspaceId, workspaceId),
),
});

if (env == null) throw new ApiError("Environment not found", 404);

res.status(200).json(await getEnvironmentWithSystems(env));
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

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

GET /environments/name/:name uses the raw environment name as a path segment, but environment names are not validated/normalized (create/upsert accept any string). This means some valid names (e.g. containing / or other reserved characters) cannot be reliably fetched via this endpoint. Consider either (a) enforcing a URL-safe name/slug format at create/upsert (and documenting it in OpenAPI with a pattern), or (b) changing this lookup to use a query parameter instead of a path parameter.

Copilot uses AI. Check for mistakes.
Comment on lines +236 to +239
await api.DELETE(
"/v1/workspaces/{workspaceId}/environments/{environmentId}",
{ params: { path: { workspaceId: workspace.id, environmentId } } },
);
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

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

The new test deletes the created environment but doesn't assert the delete request succeeded. Adding a status expectation (e.g. 202) here would make the test more robust and reduce the chance of leaking test data when deletes fail.

Suggested change
await api.DELETE(
"/v1/workspaces/{workspaceId}/environments/{environmentId}",
{ params: { path: { workspaceId: workspace.id, environmentId } } },
);
const deleteRes = await api.DELETE(
"/v1/workspaces/{workspaceId}/environments/{environmentId}",
{ params: { path: { workspaceId: workspace.id, environmentId } } },
);
expect(deleteRes.response.status).toBe(202);

Copilot uses AI. Check for mistakes.
@adityachoudhari26 adityachoudhari26 merged commit 8fd85f4 into main Apr 24, 2026
17 checks passed
@adityachoudhari26 adityachoudhari26 deleted the get-env-by-name branch April 24, 2026 21:18
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