Skip to content
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

fix: Use GraphQL-compliant response payload on error #972

Merged
merged 6 commits into from
Feb 4, 2025

Conversation

Natoandro
Copy link
Contributor

@Natoandro Natoandro commented Feb 4, 2025

  • Use GraphQL-compliant response payload on error on all GraphQL endpoints

Migration notes


  • The change comes with new or modified tests
  • Hard-to-understand functions have explanatory comments
  • End-user documentation is updated to reflect the change

Summary by CodeRabbit

  • Refactor
    • Consolidated JSON response formatting for both success and error cases.
    • Streamlined the handling of response structures across multiple service endpoints.
    • Improved consistency and reliability of data returned to clients, ensuring structured JSON output for all interactions.
    • Enhanced error handling to provide structured JSON responses across various services.

Copy link
Contributor

coderabbitai bot commented Feb 4, 2025

📝 Walkthrough

Walkthrough

This update standardizes JSON response handling across multiple services. The changes replace direct construction of Response objects with utility functions jsonOk and jsonError. Multiple modules—from artifact and authentication to GraphQL—now utilize these helpers to format both success and error responses consistently. Additionally, the utility functions themselves have been refactored to accept configuration objects, improving their flexibility and readability.

Changes

File(s) Change Summary
src/typegate/.../artifact_service.ts Replaced manual Response creation with jsonOk/jsonError in the handle method for invalid methods, parsing errors, missing tokens, artifact metadata, and successful uploads.
src/typegate/.../auth/mod.ts Updated handleAuth to use jsonOk in place of manually constructing a JSON response, abstracting header configuration.
src/typegate/.../auth/protocols/oauth2.ts Modified error handling in authMiddleware (and context in tokenMiddleware) to use jsonError for invalid OAuth2 operations and missing query parameters, ensuring structured error responses with a 400 status code.
src/typegate/.../auth/routes/take.ts Transitioned error and success responses in the take function to use jsonError and jsonOk, including consistent handling for domain mismatches and exception catch blocks.
src/typegate/.../auth/routes/validate.ts Updated the badRequest and validate functions to use jsonError and jsonOk, embedding structured JSON responses along with headers and an "access-control-allow-origin" configuration.
src/typegate/.../graphql_service.ts Adjusted the handleGraphQL function to standardize responses by encapsulating data in a { data, headers } object for success and by wrapping error messages with a consistent status field via jsonError.
src/typegate/.../responses.ts Refactored jsonOk and jsonError to accept configuration objects (JsonOkConfig and JsonErrorConfig) and initialize headers accordingly, thereby streamlining the parameter structure and default values.
src/typegate/.../typegate/mod.ts Revised error handling in the handle method to use an object-based jsonError call for JWT failure scenarios, improving response structure consistency across the application.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Service as API Service
    participant RespUtil as Response Utility

    Client->>Service: Send request
    Service->>Service: Validate request & process data
    alt Request is valid
        Service->>RespUtil: Call jsonOk({ data..., headers })
    else Request is invalid
        Service->>RespUtil: Call jsonError({ status, message, headers })
    end
    RespUtil-->>Service: Return structured JSON response
    Service-->>Client: Respond with JSON formatted data
Loading

Possibly related PRs

  • feat(docs): post on Durable Execution. #816: The changes in the main PR, which focus on modifying response handling in the ArtifactService class using jsonError and jsonOk, are related to the changes in the retrieved PR that also involve replacing direct Response object creation with jsonOk in the handleAuth function, indicating a shared approach to response management.
  • fix(gate,sdk): fail fast on bad credentials before artifact upload #961: The changes in the main PR, which focus on standardizing JSON response handling in the ArtifactService class, are related to the modifications in the retrieved PR that also involve transitioning to the jsonOk and jsonError utility functions for response generation in the handleAuth function. Both PRs enhance the consistency and structure of API responses.

Suggested reviewers

  • michael-0acf4
  • Yohe-Am
  • zifeo
  • luckasRanarison

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 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 3bebdd8 and e2fe935.

📒 Files selected for processing (3)
  • src/typegate/src/services/artifact_service.ts (6 hunks)
  • src/typegate/src/services/graphql_service.ts (1 hunks)
  • src/typegate/src/services/responses.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/typegate/src/services/artifact_service.ts
  • src/typegate/src/services/graphql_service.ts
  • src/typegate/src/services/responses.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: bulid-docker (linux/arm64, custom-arm)
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: bulid-docker (linux/amd64, custom-ubuntu-large)
  • GitHub Check: test-full
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
  • GitHub Check: pre-commit

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. (Beta)
  • @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: 0

🧹 Nitpick comments (5)
src/typegate/src/services/responses.ts (1)

16-18: Consider consolidating headers initialization logic.

The headers initialization logic is duplicated between jsonOk and jsonError.

Consider extracting to a shared utility function:

+const initHeaders = (headersInit?: Headers | HeadersInit) => {
+  const headers = headersInit != null
+    ? new Headers(headersInit)
+    : new Headers();
+  headers.set("content-type", "application/json");
+  return headers;
+};

 export const jsonOk = (
   { status = 200, data, headers: headersInit }: JsonOkConfig,
 ) => {
-  const headers = headersInit != null
-    ? new Headers(headersInit)
-    : new Headers();
-  headers.set("content-type", "application/json");
+  const headers = initHeaders(headersInit);
   return new Response(JSON.stringify({ data }), {
     status,
     headers,
   });
 };

Also applies to: 35-37

src/typegate/src/services/auth/routes/take.ts (1)

31-31: Consider adding error code to extensions.

For better error handling on the client side, consider adding an error code to the extensions field.

 return jsonError({
   status: 401,
   message: "not authorized",
+  extensions: { code: "UNAUTHORIZED" },
   headers: resHeaders,
 });

Also applies to: 34-38

src/typegate/src/services/auth/routes/validate.ts (1)

7-10: Address the TODO comment about using BaseError.

The comment indicates that BaseError should be used instead of direct jsonError calls.

Would you like me to help implement the BaseError integration? This would align with error handling in other parts of the codebase.

src/typegate/src/services/artifact_service.ts (2)

12-13: Consolidate jsonError and jsonOk imports.

The utilities are imported separately from the same module.

-import { jsonError } from "./responses.ts";
-import { jsonOk } from "./responses.ts";
+import { jsonError, jsonOk } from "./responses.ts";

51-55: Consider standardizing error handling.

Some error paths use BaseError.toResponse() while others use jsonError. Consider standardizing the approach for consistency.

Either:

  1. Convert all error handling to use jsonError, or
  2. Use BaseError.toResponse() consistently throughout the codebase
 } catch (e) {
   if (e instanceof BaseError) {
-    return e.toResponse();
+    return jsonError({
+      status: e.status,
+      message: e.message,
+      extensions: { code: e.type },
+    });
   }
   return new UnknownError(e).toResponse();
 }

Also applies to: 101-105

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f027067 and f6c6293.

📒 Files selected for processing (8)
  • src/typegate/src/services/artifact_service.ts (6 hunks)
  • src/typegate/src/services/auth/mod.ts (1 hunks)
  • src/typegate/src/services/auth/protocols/oauth2.ts (3 hunks)
  • src/typegate/src/services/auth/routes/take.ts (2 hunks)
  • src/typegate/src/services/auth/routes/validate.ts (2 hunks)
  • src/typegate/src/services/graphql_service.ts (1 hunks)
  • src/typegate/src/services/responses.ts (1 hunks)
  • src/typegate/src/typegate/mod.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: bulid-docker (linux/arm64, custom-arm)
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: bulid-docker (linux/amd64, custom-ubuntu-large)
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
  • GitHub Check: test-full
  • GitHub Check: pre-commit
🔇 Additional comments (12)
src/typegate/src/services/responses.ts (2)

7-11: LGTM! Well-structured type definitions.

The type definitions for JsonOkConfig and JsonErrorConfig are clear and properly typed. Good use of optional properties where appropriate.

Also applies to: 26-30


39-54: LGTM! GraphQL-compliant error response structure.

The error response format correctly follows the GraphQL specification with:

  • Array of error objects
  • Required fields: message, locations, path
  • Extensions field with timestamp
src/typegate/src/services/auth/routes/take.ts (1)

24-29: LGTM! Clear error message for domain mismatch.

The error response is well-structured with a descriptive message and proper status code.

src/typegate/src/services/auth/routes/validate.ts (1)

71-77: LGTM! Well-structured success response.

The response correctly uses jsonOk with proper headers handling.

src/typegate/src/services/auth/mod.ts (1)

135-135: LGTM! Standardized JSON response handling.

The change improves consistency by using the jsonOk utility function instead of directly constructing a Response object.

src/typegate/src/services/graphql_service.ts (4)

122-122: LGTM! GraphQL-compliant success response.

The change wraps the response in a data property, aligning with GraphQL specification.


130-130: LGTM! Standardized resolver error response.

The change includes a status code in the error response, improving error handling consistency.


133-137: LGTM! Improved authentication error handling.

The change dynamically sets the status code based on the context:

  • 401 for missing authentication
  • 403 for insufficient permissions

145-145: LGTM! Standardized generic error response.

The change includes a status code in the generic error response, maintaining consistency.

src/typegate/src/services/auth/protocols/oauth2.ts (2)

209-213: LGTM! Standardized OAuth2 credential error response.

The change improves error handling by:

  • Including a status code
  • Maintaining the error message
  • Preserving the headers for cookie clearing

242-245: LGTM! Standardized missing parameter error response.

The change improves error handling by including a status code for missing origin/redirect_uri parameters.

src/typegate/src/typegate/mod.ts (1)

288-288: LGTM! Standardized JWT error response.

The change improves consistency by using the structured jsonError format for JWT validation failures.

luckasRanarison
luckasRanarison previously approved these changes Feb 4, 2025
michael-0acf4
michael-0acf4 previously approved these changes Feb 4, 2025
Copy link

codecov bot commented Feb 4, 2025

Codecov Report

Attention: Patch coverage is 51.72414% with 28 lines in your changes missing coverage. Please review.

Project coverage is 77.85%. Comparing base (f027067) to head (e2fe935).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/typegate/src/services/artifact_service.ts 25.00% 12 Missing ⚠️
src/typegate/src/services/auth/routes/take.ts 22.22% 7 Missing ⚠️
src/typegate/src/services/auth/routes/validate.ts 16.66% 5 Missing ⚠️
src/typegate/src/services/auth/protocols/oauth2.ts 50.00% 3 Missing ⚠️
src/typegate/src/services/auth/mod.ts 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #972      +/-   ##
==========================================
+ Coverage   77.77%   77.85%   +0.07%     
==========================================
  Files         160      160              
  Lines       19657    19641      -16     
  Branches     1964     1969       +5     
==========================================
+ Hits        15289    15291       +2     
+ Misses       4347     4329      -18     
  Partials       21       21              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@Natoandro Natoandro merged commit 82600b5 into main Feb 4, 2025
11 of 13 checks passed
@Natoandro Natoandro deleted the response-payload branch February 4, 2025 19:35
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.

3 participants