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

feat(api-client): Added API Client package #346

Merged
merged 3 commits into from
Jul 10, 2024

Conversation

rajdip-b
Copy link
Member

@rajdip-b rajdip-b commented Jul 10, 2024

PR Type

Enhancement, Tests, Configuration changes


Description

  • Implemented APIClient class with HTTP methods and error handling.
  • Added EnvironmentController for environment CRUD operations.
  • Defined TypeScript interfaces for environment-related requests and responses.
  • Added tests for EnvironmentController CRUD operations.
  • Configured Jest, ESLint, and TypeScript for api-client package.
  • Added GitHub Actions workflow for validating api-client package.
  • Updated pre-commit hook to include tests for api-client package.
  • Updated environment variable for backend URL.
  • Updated dependencies and lockfile for api-client package.

Changes walkthrough 📝

Relevant files
Enhancement
3 files
client.ts
Implement API Client with HTTP methods and error handling

packages/api-client/src/client.ts

  • Added APIClient class with methods for GET, POST, PUT, and DELETE
    requests.
  • Implemented singleton pattern for APIClient instance.
  • Included error handling for HTTP responses.
  • +116/-0 
    environment.ts
    Add EnvironmentController for environment CRUD operations

    packages/api-client/src/controllers/environment/environment.ts

  • Added EnvironmentController class with methods for environment CRUD
    operations.
  • Integrated APIClient for making HTTP requests.
  • +74/-0   
    environment.types.d.ts
    Define TypeScript interfaces for environment API                 

    packages/api-client/src/types/environment.types.d.ts

  • Defined TypeScript interfaces for environment-related requests and
    responses.
  • +76/-0   
    Tests
    1 files
    environment.spec.ts
    Add tests for EnvironmentController CRUD operations           

    packages/api-client/tests/environment.spec.ts

  • Added tests for environment CRUD operations using
    EnvironmentController.
  • Included setup and teardown logic for test environments.
  • +220/-0 
    Configuration changes
    10 files
    jest.config.ts
    Add Jest configuration for API Client package                       

    packages/api-client/jest.config.ts

    • Added Jest configuration for api-client package.
    +20/-0   
    setup.ts
    Add setup script for test environment initialization         

    packages/api-client/tests/config/setup.ts

    • Added setup script for initializing test environment.
    +56/-0   
    teardown.ts
    Add teardown script for test environment cleanup                 

    packages/api-client/tests/config/teardown.ts

    • Added teardown script for cleaning up test environment.
    +21/-0   
    .eslintrc.js
    Add ESLint configuration for API Client package                   

    packages/api-client/.eslintrc.js

    • Added ESLint configuration for api-client package.
    +26/-0   
    package.json
    Add package.json for API Client package                                   

    packages/api-client/package.json

  • Added package.json for api-client package with scripts for build,
    test, lint, and format.
  • +16/-0   
    tsconfig.json
    Add TypeScript configuration for API Client package           

    packages/api-client/tsconfig.json

    • Added TypeScript configuration for api-client package.
    +26/-0   
    tsconfig.spec.json
    Add TypeScript configuration for Jest tests                           

    packages/api-client/tsconfig.spec.json

  • Added TypeScript configuration for Jest tests in api-client package.
  • +14/-0   
    validate-api-client.yaml
    Add GitHub Actions workflow for API Client validation       

    .github/workflows/validate-api-client.yaml

    • Added GitHub Actions workflow for validating api-client package.
    +62/-0   
    pre-commit
    Update pre-commit hook to include API Client tests             

    .husky/pre-commit

    • Updated pre-commit hook to include tests for api-client package.
    +1/-1     
    .env.example
    Update environment variable for backend URL                           

    .env.example

    • Updated NEXT_PUBLIC_BACKEND_URL to BACKEND_URL.
    +1/-1     
    Dependencies
    1 files
    pnpm-lock.yaml
    Update dependencies and lockfile for API Client                   

    pnpm-lock.yaml

    • Updated dependencies and lockfile for api-client package.
    +113/-125

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Copy link
    Contributor

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Error Handling
    The use of process.exit(1) within test cases (e.g., lines 40, 52, 148, 178, 217) is not recommended as it can terminate the test runner abruptly, preventing other tests from running. Consider throwing an error or using other Jest mechanisms for handling errors.

    Error Handling
    The error handling in the request method (lines 24-28) might not handle non-JSON responses gracefully, which could lead to unhandled promise rejections if the response is not in JSON format.

    Singleton Pattern
    The implementation of the singleton pattern in the APIClient class (lines 9-20) does not ensure thread safety, which might lead to issues in a concurrent environment.

    Copy link
    Contributor

    codiumai-pr-agent-free bot commented Jul 10, 2024

    CI Failure Feedback 🧐

    (Checks updated until commit d1ecda8)

    Action: Validate API Client

    Failed stage: Test [❌]

    Failed test name: tests/environment.spec.ts

    Failure summary:

    The action failed due to the following reasons:

  • The api:start command failed because the environment variable JWT_SECRET was expected to be a string
    but was received as undefined. This caused a ZodError to be thrown.
  • The api-client test failed because it could not connect to the backend URL http://localhost:4200,
    resulting in a TypeError: fetch failed with the error code ECONNREFUSED.
  • The process.exit was called with exit code 1 in the tests/environment.spec.ts file, indicating a
    failure in the test execution.

  • Relevant error logs:
    1:  ##[group]Operating System
    2:  Ubuntu
    ...
    
    398:  api:build: 
    399:  api:start: cache miss, executing 5c4a64c337bf7528
    400:  api:start: 
    401:  api:start: > api@1.0.0 start /home/runner/work/keyshade/keyshade/apps/api
    402:  api:start: > node dist/main
    403:  api:start: 
    404:  api:start: secp256k1 unavailable, reverting to browser version
    405:  api:start: /home/runner/work/keyshade/keyshade/node_modules/.pnpm/zod@3.23.8/node_modules/zod/lib/types.js:160
    406:  api:start:         throw result.error;
    407:  api:start:         ^
    408:  api:start: 
    409:  api:start: ZodError: [
    ...
    
    421:  api:start:     "expected": "string",
    422:  api:start:     "received": "undefined",
    423:  api:start:     "path": [
    424:  api:start:       "JWT_SECRET"
    425:  api:start:     ],
    426:  api:start:     "message": "Required"
    427:  api:start:   }
    428:  api:start: ]
    429:  api:start:     at get error [as error] (/home/runner/work/keyshade/keyshade/node_modules/.pnpm/zod@3.23.8/node_modules/zod/lib/types.js:55:31)
    ...
    
    449:  api:start:       expected: 'string',
    450:  api:start:       received: 'undefined',
    451:  api:start:       path: [ 'JWT_SECRET' ],
    452:  api:start:       message: 'Required'
    453:  api:start:     }
    454:  api:start:   ],
    455:  api:start:   addIssue: [Function (anonymous)],
    456:  api:start:   addIssues: [Function (anonymous)],
    457:  api:start:   errors: [
    ...
    
    468:  api:start:       received: 'undefined',
    469:  api:start:       path: [ 'JWT_SECRET' ],
    470:  api:start:       message: 'Required'
    471:  api:start:     }
    472:  api:start:   ]
    473:  api:start: }
    474:  api:start: 
    475:  api:start: Node.js v20.15.0
    476:  api:start:  ELIFECYCLE  Command failed with exit code 1.
    477:  API Error: api:start: ERROR: command finished with error: command (/home/runner/work/keyshade/keyshade/apps/api) /home/runner/setup-pnpm/node_modules/.bin/pnpm run start exited (1)
    478:  API Error: api#start: command (/home/runner/work/keyshade/keyshade/apps/api) /home/runner/setup-pnpm/node_modules/.bin/pnpm run start exited (1)
    479:  Tasks:    1 successful, 2 total
    480:  Cached:    1 cached, 2 total
    481:  Time:    1.356s 
    482:  Failed:    api#start
    483:  API Error:  ERROR  run failed: command  exited (1)
    484:  ELIFECYCLE  Command failed with exit code 1.
    485:  API launched
    486:  console.error
    487:  TypeError: fetch failed
    488:  at node:internal/deps/undici/undici:12502:13
    489:  at processTicksAndRejections (node:internal/process/task_queues:95:5)
    490:  at async APIClient.request (/home/runner/work/keyshade/keyshade/packages/api-client/src/client.ts:23:22)
    491:  at async Object.<anonymous> (/home/runner/work/keyshade/keyshade/packages/api-client/tests/environment.spec.ts:13:34) {
    492:  [cause]: AggregateError
    493:  at internalConnectMultiple (node:net:1117:18)
    494:  at afterConnectMultiple (node:net:1684:7) {
    495:  code: 'ECONNREFUSED',
    496:  [errors]: [ [Error], [Error] ]
    497:  }
    498:  }
    499:  �[0m �[90m 37 |�[39m       projectId �[33m=�[39m projectResponse�[33m.�[39mid
    500:  �[90m 38 |�[39m     } �[36mcatch�[39m (error) {
    501:  �[31m�[1m>�[22m�[39m�[90m 39 |�[39m       console�[33m.�[39merror(error)
    502:  �[90m    |�[39m               �[31m�[1m^�[22m�[39m
    503:  �[90m 40 |�[39m       process�[33m.�[39mexit(�[35m1�[39m)
    504:  �[90m 41 |�[39m     }
    505:  �[90m 42 |�[39m   })�[0m
    506:  at Object.<anonymous> (tests/environment.spec.ts:39:15)
    507:  ●  process.exit called with "1"
    508:  �[0m �[90m 38 |�[39m     } �[36mcatch�[39m (error) {
    509:  �[90m 39 |�[39m       console�[33m.�[39merror(error)
    510:  �[31m�[1m>�[22m�[39m�[90m 40 |�[39m       process�[33m.�[39mexit(�[35m1�[39m)
    511:  �[90m    |�[39m               �[31m�[1m^�[22m�[39m
    512:  �[90m 41 |�[39m     }
    513:  �[90m 42 |�[39m   })
    514:  �[90m 43 |�[39m�[0m
    515:  at Object.<anonymous> (tests/environment.spec.ts:40:15)
    516:  /home/runner/work/keyshade/keyshade/packages/api-client:
    517:  ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  api-client@1.0.0 test: `BACKEND_URL=http://localhost:4200 jest`
    518:  Exit status 1
    519:  WARN   Local package.json exists, but node_modules missing, did you mean to install?
    520:  ELIFECYCLE  Command failed with exit code 1.
    521:  ##[error]Process completed with exit code 1.
    

    ✨ CI feedback usage guide:

    The CI feedback tool (/checks) automatically triggers when a PR has a failed check.
    The tool analyzes the failed checks and provides several feedbacks:

    • Failed stage
    • Failed test name
    • Failure summary
    • Relevant error logs

    In addition to being automatically triggered, the tool can also be invoked manually by commenting on a PR:

    /checks "https://github.com/{repo_name}/actions/runs/{run_number}/job/{job_number}"
    

    where {repo_name} is the name of the repository, {run_number} is the run number of the failed check, and {job_number} is the job number of the failed check.

    Configuration options

    • enable_auto_checks_feedback - if set to true, the tool will automatically provide feedback when a check is failed. Default is true.
    • excluded_checks_list - a list of checks to exclude from the feedback, for example: ["check1", "check2"]. Default is an empty list.
    • enable_help_text - if set to true, the tool will provide a help message with the feedback. Default is true.
    • persistent_comment - if set to true, the tool will overwrite a previous checks comment with the new feedback. Default is true.
    • final_update_message - if persistent_comment is true and updating a previous checks message, the tool will also create a new message: "Persistent checks updated to latest commit". Default is true.

    See more information about the checks tool in the docs.

    Copy link
    Contributor

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Error handling
    Add error handling for JSON parsing to enhance robustness

    Add error handling for JSON parsing within the request method to prevent crashes due
    to unexpected response formats.

    packages/api-client/src/client.ts [32]

    -return (await response.json()) as T
    +try {
    +  return (await response.json()) as T
    +} catch (error) {
    +  throw new Error('Failed to parse JSON response')
    +}
     
    • Apply this suggestion
    Suggestion importance[1-10]: 10

    Why: Adding error handling for JSON parsing prevents potential crashes due to unexpected response formats, significantly enhancing the robustness of the code.

    10
    Best practice
    Replace process termination with error throwing for better error handling

    Replace the use of process.exit(1) with throwing an error to allow for better error
    handling and testability in asynchronous operations.

    packages/api-client/tests/environment.spec.ts [40-41]

     console.error(error)
    -process.exit(1)
    +throw new Error('Failed operation')
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Replacing process.exit(1) with throwing an error improves testability and error handling in asynchronous operations, which is a best practice.

    9
    Lock dependency versions to prevent unexpected behavior from version updates

    Consider locking the versions of your dependencies to ensure consistent behavior
    across different environments and deployments. Using exact versions instead of
    version ranges can help prevent unexpected updates that might introduce bugs or
    breaking changes.

    apps/platform/package.json [12-48]

    -"@radix-ui/react-accordion": "^1.2.0",
    -"@radix-ui/react-avatar": "^1.0.4",
    -"@radix-ui/react-checkbox": "^1.0.4",
    +"@radix-ui/react-accordion": "1.2.0",
    +"@radix-ui/react-avatar": "1.0.4",
    +"@radix-ui/react-checkbox": "1.0.4",
     ...
    -"zod": "^3.23.8"
    +"zod": "3.23.8"
     
    Suggestion importance[1-10]: 8

    Why: Locking dependency versions can prevent unexpected behavior due to version updates, which is a good practice for maintaining stability across different environments and deployments.

    8
    Security
    Ensure integrity hashes are correct for security

    Verify and update the integrity hashes for all newly added or updated packages to
    ensure they match the actual files downloaded, enhancing security and integrity of
    the project dependencies.

    pnpm-lock.yaml [3090]

    +resolution: {integrity: sha512-MdiXf+nDuMvY0gJKxyfZ7/6UFsETO7mGKF54MVD/ekJS6HdFtpZFBgrh6Pseu64XTb2MLyFPlbW6hj8HYRQNOQ==}
     
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Verifying and updating integrity hashes for all newly added or updated packages is crucial for enhancing the security and integrity of the project dependencies. This suggestion addresses a significant security concern.

    9
    Maintainability
    Align TypeScript versions across all dependencies

    Consider using a consistent version of TypeScript across all dependencies to avoid
    potential compatibility issues. The version typescript@5.5.3 is used in multiple
    places, but typescript@4.9.5 appears in some dependencies. Aligning them may prevent
    runtime errors and improve maintainability.

    pnpm-lock.yaml [264]

    +version: 29.1.5(@babel/core@7.24.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.24.7))(jest@29.7.0(@types/node@20.14.10)(ts-node@10.9.2(@types/node@20.14.10)(typescript@5.5.3)))(typescript@5.5.3)
     
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Aligning TypeScript versions across all dependencies can prevent potential compatibility issues and improve maintainability. This suggestion addresses a significant maintainability concern.

    8
    Refactor repeated code into a helper function for headers

    Refactor repeated header object creation into a helper function to reduce code
    duplication and improve maintainability.

    packages/api-client/tests/environment.spec.ts [19-20]

    -{
    -  'x-e2e-user-email': email
    -}
    +getTestHeaders(email)
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Refactoring repeated header object creation into a helper function reduces code duplication and improves maintainability, though it is a minor improvement.

    7
    Standardize lint command structure for better consistency

    It is recommended to use a consistent command structure across different linting
    scripts to improve maintainability and readability. Consider using a uniform prefix
    for all lint-related scripts.

    package.json [102-105]

    -"lint:api": "turbo run lint --filter=api",
    -"lint:web": "turbo run lint --filter=web",
    -"lint:platform": "turbo run lint --filter=platform",
    -"lint:api-client": "pnpm run --filter=api-client lint",
    +"lint:api": "pnpm run lint --filter=api",
    +"lint:web": "pnpm run lint --filter=web",
    +"lint:platform": "pnpm run lint --filter=platform",
    +"lint:api-client": "pnpm run lint --filter=api-client",
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Standardizing the command structure improves maintainability and readability, making it easier for developers to understand and manage the scripts.

    7
    Compatibility
    Ensure @types/node version is compatible with the used TypeScript version

    Update the @types/node version to match the latest TypeScript version used in the
    project to ensure type definitions are up-to-date and compatible.

    pnpm-lock.yaml [243]

    +version: 29.7.0(@types/node@20.14.10)(ts-node@10.9.2(@types/node@20.14.10)(typescript@5.5.3))
     
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Ensuring that @types/node version matches the TypeScript version used in the project helps maintain compatibility and reduces the risk of type definition conflicts. This is a good practice for maintaining type safety.

    7
    Performance
    Reduce complexity by consolidating dependency versions

    Consider removing redundant dependencies or consolidating versions to reduce the
    complexity and size of the dependency tree, which can lead to faster installation
    times and less maintenance overhead.

    pnpm-lock.yaml [243]

    +version: 29.7.0(@types/node@20.14.10)(ts-node@10.9.2(@types/node@20.14.10)(typescript@5.5.3))
     
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Consolidating dependency versions can reduce the complexity and size of the dependency tree, leading to faster installation times and less maintenance overhead. However, the suggestion is somewhat redundant with the previous one.

    6
    Combine lint and test steps to streamline the CI process

    To optimize the CI pipeline, consider merging the lint and test steps into a single
    step. This can reduce the overhead of multiple steps and make the pipeline more
    efficient.

    .github/workflows/validate-api-client.yaml [49-55]

    -- name: Lint
    +- name: Lint and Test
       run: |
    -    pnpm run lint:api-client
    -- name: Test
    -  run: |
    -    pnpm run test:api-client
    +    pnpm run lint:api-client && pnpm run test:api-client
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Combining the lint and test steps can streamline the CI process, reducing overhead and potentially speeding up the pipeline. However, it may reduce the granularity of feedback in case of failures.

    6

    Copy link

    codecov bot commented Jul 10, 2024

    Codecov Report

    All modified and coverable lines are covered by tests ✅

    Project coverage is 88.10%. Comparing base (ce50743) to head (d1ecda8).
    Report is 60 commits behind head on develop.

    Additional details and impacted files
    @@             Coverage Diff             @@
    ##           develop     #346      +/-   ##
    ===========================================
    - Coverage    91.71%   88.10%   -3.61%     
    ===========================================
      Files          111      107       -4     
      Lines         2510     2329     -181     
      Branches       469      357     -112     
    ===========================================
    - Hits          2302     2052     -250     
    - Misses         208      277      +69     
    Flag Coverage Δ
    api-e2e-tests 88.10% <100.00%> (-3.61%) ⬇️

    Flags with carried forward coverage won't be shown. Click here to find out more.

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

    @rajdip-b rajdip-b merged commit 8dc0da9 into develop Jul 10, 2024
    6 checks passed
    @rajdip-b rajdip-b deleted the feat/create-api-client-package branch July 10, 2024 16:45
    rajdip-b pushed a commit that referenced this pull request Jul 11, 2024
    ## [2.2.0](v2.1.0...v2.2.0) (2024-07-11)
    
    ### 🚀 Features
    
    * **api-client:** Added API Client package ([#346](#346)) ([6734e1e](6734e1e))
    * **api:** Updated API key ([fbac312](fbac312))
    * **platform:** View [secure]s ([#313](#313)) ([97c4541](97c4541))
    * **web:** Add Pricing Page ([#243](#243)) ([2c7f1d6](2c7f1d6))
    
    ### 📚 Documentation
    
    * **cli:** Added docs for the CLI package ([#329](#329)) ([edad166](edad166))
    * **cli:** Added usage docs ([#330](#330)) ([b6963d5](b6963d5))
    * Update Discord link ([871b6cd](871b6cd))
    * Update README.md ([e66fcd2](e66fcd2))
    * **web:** Add documentation about our web package ([#268](#268)) ([3d848e7](3d848e7))
    
    ### 🔧 Miscellaneous Chores
    
    * **api:** Updated response types in environment service ([b8a3ddd](b8a3ddd))
    * **ci:** Added release scripts for platform and api ([02dae60](02dae60))
    * **CI:** Updated action plugin versions ([88bb317](88bb317))
    * **CI:** Updated pnpm version in CI file ([2692e88](2692e88))
    * **platform:** Fixed env parsing in platform ([d6ffafa](d6ffafa))
    * **web:** Update Terms and Conditions and Privacy Policy ([#282](#282)) ([d621dcb](d621dcb))
    
    ### 🔨 Code Refactoring
    
    * **api:** Update [secure] and variable fetching endpoints ([7d9acd0](7d9acd0))
    * **cli:** Refactored profile commands into readable blocks ([#331](#331)) ([4a8a089](4a8a089))
    * **cli:** Updated configuration commands and mechanism ([#310](#310)) ([9079b6d](9079b6d))
    rajdip-b pushed a commit that referenced this pull request Jul 11, 2024
    ## [2.2.0](v2.1.0...v2.2.0) (2024-07-11)
    
    ### 🚀 Features
    
    * **api-client:** Added API Client package ([#346](#346)) ([6734e1e](6734e1e))
    * **api:** Updated API key ([fbac312](fbac312))
    * **platform:** View [secure]s ([#313](#313)) ([97c4541](97c4541))
    * **web:** Add Pricing Page ([#243](#243)) ([2c7f1d6](2c7f1d6))
    
    ### 📚 Documentation
    
    * **cli:** Added docs for the CLI package ([#329](#329)) ([edad166](edad166))
    * **cli:** Added usage docs ([#330](#330)) ([b6963d5](b6963d5))
    * Update Discord link ([871b6cd](871b6cd))
    * Update README.md ([e66fcd2](e66fcd2))
    * **web:** Add documentation about our web package ([#268](#268)) ([3d848e7](3d848e7))
    
    ### 🔧 Miscellaneous Chores
    
    * **api:** Updated response types in environment service ([b8a3ddd](b8a3ddd))
    * **ci:** Added release scripts for platform and api ([02dae60](02dae60))
    * **CI:** Updated action plugin versions ([88bb317](88bb317))
    * **CI:** Updated pnpm version in CI file ([2692e88](2692e88))
    * **platform:** Fixed env parsing in platform ([d6ffafa](d6ffafa))
    * **web:** Update Terms and Conditions and Privacy Policy ([#282](#282)) ([d621dcb](d621dcb))
    
    ### 🔨 Code Refactoring
    
    * **api:** Update [secure] and variable fetching endpoints ([7d9acd0](7d9acd0))
    * **cli:** Refactored profile commands into readable blocks ([#331](#331)) ([4a8a089](4a8a089))
    * **cli:** Updated configuration commands and mechanism ([#310](#310)) ([9079b6d](9079b6d))
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant