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(fa): Creating endpoint for open-api that retrieves one application from id #16490

Merged
merged 132 commits into from
Oct 22, 2024

Conversation

MargretFinnboga
Copy link
Contributor

@MargretFinnboga MargretFinnboga commented Oct 21, 2024

...

Attach a link to issue if relevant

What

  • Creating endpoint that retrieves one application and returns it

Why

  • groundwork for the upcoming to return a pdf

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced a new endpoint to retrieve an application by its ID.
    • Added functionality to fetch a specific application in PDF format.
    • Enhanced service capabilities to allow retrieval of individual applications.
  • Bug Fixes

    • None noted.
  • Documentation

    • Updated logging for new methods to improve traceability.

@MargretFinnboga MargretFinnboga requested a review from a team as a code owner October 21, 2024 13:44
Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The pull request introduces new methods across various controllers and services to enhance the application retrieval functionality. Specifically, a GET endpoint for retrieving an application by its ID is added to the OpenApiApplicationController, along with a corresponding method in the OpenApiApplicationService. Additionally, the AppController receives a method to fetch applications in PDF format, while the AppService adds functionality to retrieve a specific application using its ID. Import statements are updated to support these new functionalities.

Changes

File Change Summary
apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.controller.ts Added method async getById(@Param('id') id: string, @CurrentMunicipalityCode() municipalityCode: string) to fetch application by ID.
apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.service.ts Added method async getbyID(municipalityCodes: string, id: string): Promise<ApplicationModel> to retrieve an application based on municipality code and ID.
apps/financial-aid/open-api/src/app/app.controller.ts Added method async getPdf(apiKey: string, municipalityCode: string, id: string): Promise<ApplicationModel> to fetch application in PDF format.
apps/financial-aid/open-api/src/app/app.service.ts Added method async getApplication(apiKey: string, municipalityCode: string, id: string): Promise<ApplicationModel> to retrieve a specific application by ID.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • valurefugl
  • kksteini

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.

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

🧹 Outside diff range and nitpick comments (6)
apps/financial-aid/open-api/src/app/app.controller.ts (1)

1-1: Remove unused import Param

The Param decorator is imported but not used in this file. To maintain clean and efficient code, it's recommended to remove unused imports.

Apply this diff to remove the unused import:

-import { Controller, Get, Headers, Inject, Param, Query } from '@nestjs/common'
+import { Controller, Get, Headers, Inject, Query } from '@nestjs/common'
apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.controller.ts (1)

55-69: LGTM: New getById method is well-implemented.

The new getById method follows NestJS conventions and is consistent with the existing code style. Good use of Swagger documentation and logging.

Consider changing the service method call for consistency:

-    return this.applicationService.getbyID(municipalityCode, id)
+    return this.applicationService.getById(municipalityCode, id)

This ensures consistent naming convention (camelCase) across the codebase.

apps/financial-aid/open-api/src/app/app.service.ts (1)

65-89: Enhance error handling and logging in the new getApplication method.

The implementation of the new getApplication method is generally good and consistent with the existing code. However, there are a couple of areas for improvement:

  1. Error Handling: Consider adding try-catch block to handle potential network or API errors.
  2. Logging: The log message could be more specific to indicate it's fetching a single application.

Here's a suggested improvement:

async getApplication(
  apiKey: string,
  municipalityCode: string,
  id: string,
): Promise<ApplicationModel> {
  this.logger.info(
    `Attempting to fetch application with ID ${id} for municipality ${municipalityCode}`,
  )

  const url = new URL(
    `${this.config.backend.url}/api/financial-aid/open-api-applications/id/${id}`,
  )

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'API-Key': apiKey,
        'Municipality-Code': municipalityCode,
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    return await response.json()
  } catch (error) {
    this.logger.error(`Error fetching application with ID ${id}: ${error.message}`)
    throw error
  }
}

This implementation improves error handling and provides more specific logging.

Overall, the new method is well-implemented and follows TypeScript best practices. It's a good addition to the service.

apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.service.ts (3)

99-170: LGTM! Consider adding error handling.

The getbyID method is well-implemented and consistent with the existing getAll method. It follows TypeScript and NestJS best practices.

Consider adding error handling for cases where no application is found. For example:

const application = await this.applicationModel.findOne({
  // ... existing query ...
});

if (!application) {
  throw new NotFoundException(`Application with ID ${id} not found`);
}

return application;

This will provide a more informative response when an application is not found.


99-102: Consider using a more specific type for municipalityCodes.

If municipalityCodes is always expected to be a single code, consider using a more specific type or renaming the parameter for clarity.

async getbyID(
  municipalityCode: string,
  id: string,
): Promise<ApplicationModel>

107-109: Add a comment explaining the state filtering.

It would be helpful to add a brief comment explaining why only REJECTED or APPROVED applications are being retrieved.

// Only retrieve applications that have been fully processed (REJECTED or APPROVED)
state: {
  [Op.or]: [ApplicationState.REJECTED, ApplicationState.APPROVED],
},
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f031834 and 70a235f.

📒 Files selected for processing (4)
  • apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.controller.ts (2 hunks)
  • apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.service.ts (1 hunks)
  • apps/financial-aid/open-api/src/app/app.controller.ts (2 hunks)
  • apps/financial-aid/open-api/src/app/app.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.controller.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.service.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/financial-aid/open-api/src/app/app.controller.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/financial-aid/open-api/src/app/app.service.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (3)
apps/financial-aid/open-api/src/app/app.controller.ts (1)

38-55: ⚠️ Potential issue

Improve method implementation and documentation

The getPdf method has a few areas for improvement:

  1. The method name getPdf doesn't accurately reflect its current functionality, as it's not returning a PDF.
  2. The @ApiCreatedResponse decorator specifies an incorrect return type. It should be ApplicationModel instead of [ApplicationBackendModel].
  3. Error handling is not implemented, which could lead to unhandled exceptions.

Consider applying the following changes:

  1. Rename the method to better reflect its current functionality, e.g., getApplicationById.
  2. Update the @ApiCreatedResponse decorator to accurately reflect the return type.
  3. Implement error handling using try-catch or NestJS exception filters.

Here's a suggested implementation:

@Get('application')
@ApiCreatedResponse({
  type: ApplicationModel,
  description: 'Gets a single application by ID',
})
async getApplicationById(
  @Headers('API-Key') apiKey: string,
  @Headers('Municipality-Code') municipalityCode: string,
  @Query('id') id: string,
): Promise<ApplicationModel> {
  this.logger.info(`Fetching application with ID: ${id}`)
  try {
    const application = await this.appService.getApplication(apiKey, municipalityCode, id);
    this.logger.info(`Application fetched successfully`)
    return application;
  } catch (error) {
    this.logger.error(`Error fetching application: ${error.message}`)
    throw new NotFoundException(`Application with ID ${id} not found`);
  }
}

To ensure that the getApplication method in AppService is correctly implemented, let's verify its implementation:

apps/financial-aid/backend/src/app/modules/openApiApplications/openApiApplication.controller.ts (2)

1-8: LGTM: Import statements are correctly updated.

The addition of Param to the import statement is consistent with its usage in the new getById method and follows the existing code style.


Line range hint 1-69: Changes align well with PR objectives and maintain code quality.

The new getById endpoint successfully implements the functionality to retrieve a single application by ID, as outlined in the PR objectives. The implementation follows TypeScript and NestJS best practices, maintaining consistency with the existing codebase.

To ensure the new endpoint is properly integrated, please run the following verification script:

This script will help verify the proper implementation of the getById method in the service layer and check for appropriate error handling.

Copy link

codecov bot commented Oct 21, 2024

Codecov Report

Attention: Patch coverage is 0% with 7 lines in your changes missing coverage. Please review.

Project coverage is 36.77%. Comparing base (5411331) to head (481dbc5).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...enApiApplications/openApiApplication.controller.ts 0.00% 5 Missing ⚠️
.../openApiApplications/openApiApplication.service.ts 0.00% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16490      +/-   ##
==========================================
+ Coverage   36.76%   36.77%   +0.01%     
==========================================
  Files        6847     6845       -2     
  Lines      141884   141768     -116     
  Branches    40429    40381      -48     
==========================================
- Hits        52167    52139      -28     
+ Misses      89717    89629      -88     
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.34% <ø> (ø)
application-template-api-modules 27.80% <ø> (-0.02%) ⬇️
financial-aid-backend 56.25% <0.00%> (-0.12%) ⬇️

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

Files with missing lines Coverage Δ
.../openApiApplications/openApiApplication.service.ts 0.00% <0.00%> (ø)
...enApiApplications/openApiApplication.controller.ts 0.00% <0.00%> (ø)

... and 14 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5411331...481dbc5. Read the comment docs.

Copy link
Member

@gudjong gudjong left a comment

Choose a reason for hiding this comment

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

LGTM. However, I wonder if this new endpoint will ever be used. Wasn't the idea that the external system would call the getAll endpoint, loop through the responses form that endpoint and finally call the yet to be created endpoint to retrieve the PDF for a single application?

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 22, 2024

Datadog Report

All test runs 2644a92 🔗

4 Total Test Services: 0 Failed, 4 Passed
🔻 Test Sessions change in coverage: 2 decreased, 6 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.75s 1 no change Link
application-system-api 0 0 0 120 2 3m 47.49s 1 no change Link
application-template-api-modules 0 0 0 123 0 2m 33.46s 1 decreased (-0.01%) Link
financial-aid-backend 0 0 0 219 0 48.92s 1 decreased (-0.11%) Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • financial-aid-backend - jest 59.61% (-0.11%) - Details
  • application-template-api-modules - jest 30.04% (-0.01%) - Details

@MargretFinnboga MargretFinnboga added the automerge Merge this PR as soon as all checks pass label Oct 22, 2024
@kodiakhq kodiakhq bot merged commit a02137f into main Oct 22, 2024
41 of 50 checks passed
@kodiakhq kodiakhq bot deleted the feat/adding-pdf-endpoint-to-api branch October 22, 2024 18:17
svanaeinars pushed a commit that referenced this pull request Oct 23, 2024
…on from id (#16490)

* adding sortable feature

* Revert "adding sortable feature"

This reverts commit d9691c5.

* adding more detail for api

* removing white space break just adding html element to the db

* adding children to api

* removing extra imports

* creating pdf endpoint and returning json of application
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants