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(application-system): using aws-sdkv3 instead of v2 and refactoring #15842

Draft
wants to merge 49 commits into
base: main
Choose a base branch
from

Conversation

HjorturJ
Copy link
Member

@HjorturJ HjorturJ commented Sep 2, 2024

...

Attach a link to issue if relevant

What

Refactor usages of s3 clients into a single service class within the template-api-modules backend.

Why

To consolidate s3 useage to make it easier to pinpoint bugs in the future and hopefully make it easier to make new stuff with predefined functions for common use cases of s3 buckets.

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

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

    • Updated the header's background color for improved visibility.
    • Introduced new methods in the attachment service for better handling of file content and URLs.
    • Added a new AWS service to streamline interactions with Amazon S3.
    • Enhanced various services to utilize the new AWS service for improved file operations.
    • Comprehensive unit tests for AWS service functionalities, including file retrieval and presigned URL generation.
  • Bug Fixes

    • Improved error handling and file content processing in several services.
  • Chores

    • Updated dependencies in package.json to enhance AWS functionality.

Copy link
Contributor

coderabbitai bot commented Sep 2, 2024

Walkthrough

The pull request introduces substantial changes across multiple components of the application, primarily focusing on the integration and refactoring of AWS S3-related services. Key modifications include the adoption of a new AwsService for managing S3 interactions, updates to existing services to utilize this new service, and enhancements in dependency injection practices. Additionally, several methods for handling attachments have been added or modified, and the project structure has been adjusted to centralize shared services and improve maintainability.

Changes

Files Change Summary
apps/application-system/form/src/components/Header/Header.tsx Changed background color of the Box component from "white" to "red600".
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts Enhanced AttachmentS3Service constructor with dependency injection for AwsService, ConfigService, and BaseTemplateApiApplicationService. Updated method signatures to use ApplicationWithAttachments. Introduced new methods for retrieving attachment content and generating signed URLs.
libs/application/template-api-modules/src/lib/modules/shared/shared.module.ts Added AwsService to the module, modifying the exports to include AwsService.
libs/application/template-api-modules/src/lib/modules/templates/children-residence-change/children-residence-change.service.ts, libs/application/template-api-modules/src/lib/modules/templates/estate/estate.service.ts, libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts, libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.service.ts, libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.service.ts, libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.service.ts Various modules updated to include AwsService dependencies, replacing direct S3 interactions. Imports and providers were modified accordingly.
libs/nest/aws/src/lib/aws.service.ts Refactored AwsService to use AWS SDK v3, updating methods for file retrieval and upload, and adding error handling and new methods for file existence checks.
package.json Added new dependencies related to AWS S3 services, including @aws-sdk/client-s3, @aws-sdk/lib-storage, and others.

Sequence Diagram(s)

sequenceDiagram
    participant A as Application
    participant S3 as AwsService
    participant AS3 as AttachmentS3Service

    A->>AS3: Request to add attachment
    AS3->>S3: Upload file to S3
    S3-->>AS3: Confirmation of upload
    AS3-->>A: Attachment added confirmation

    A->>AS3: Request to get attachment
    AS3->>S3: Retrieve file from S3
    S3-->>AS3: File data
    AS3-->>A: Return attachment data
Loading

Possibly related PRs

Suggested labels

automerge


Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 30a68c5 and 794fc87.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (4)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts (0 hunks)
  • libs/message-queue/src/lib/nest/client.service.ts (2 hunks)
  • libs/message-queue/src/lib/nest/worker.service.ts (1 hunks)
  • package.json (3 hunks)
Files not reviewed due to no reviewable changes (1)
  • apps/services/user-notification/src/app/modules/notifications/notificationsWorker/notificationsWorker.service.spec.ts
Files skipped from review as they are similar to previous changes (1)
  • package.json
Additional context used
Path-based instructions (2)
libs/message-queue/src/lib/nest/worker.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/message-queue/src/lib/nest/client.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
Additional comments not posted (2)
libs/message-queue/src/lib/nest/worker.service.ts (1)

80-80: Verify the presence of the institution attribute.

The change looks good and aligns with the updated structure of the message object. However, please ensure that the institution attribute is consistently present under MessageAttributes for all messages to avoid logging undefined values.

Run the following script to verify the presence of the institution attribute:

Verification successful

Change verified, manual check recommended

The modification to access institution from MessageAttributes instead of Attributes is consistent with the rest of the codebase. Our search found no conflicting usages of Attributes.institution, confirming that this change aligns with the updated message structure.

However, we recommend a manual check to ensure that:

  • The institution attribute is present under MessageAttributes for all expected messages.
  • There are no edge cases where this attribute might be missing, which could lead to undefined values being logged.

This verification will help prevent potential issues with logging undefined values and ensure the robustness of the message processing.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of the `institution` attribute under `MessageAttributes` for all messages.

# Test: Search for the usage of `MessageAttributes.institution`. Expect: No occurrences of accessing `institution` under `Attributes`.
rg --type typescript $'Attributes\\.institution'

Length of output: 83


Script:

#!/bin/bash
# Description: Verify the presence of the `institution` attribute under `MessageAttributes` and `Attributes` for all messages.

# Search for MessageAttributes.institution
echo "Searching for MessageAttributes.institution:"
rg -C 2 'MessageAttributes.*institution'

echo -e "\n---\n"

# Search for Attributes.institution
echo "Searching for Attributes.institution:"
rg -C 2 'Attributes\.institution'

Length of output: 700

libs/message-queue/src/lib/nest/client.service.ts (1)

84-84: Type assertion enhances type safety and clarity.

The type assertion as QueueAttributeName[] explicitly casts the attributes array to the expected QueueAttributeName enum type for the AttributeNames property of GetQueueAttributesCommand. This change provides a more precise type definition, ensuring that the attributes array conforms to the expected type.

Benefits of the type assertion:

  • Enhances type safety by explicitly specifying the expected type.
  • Improves code clarity by making the type expectation more evident.
  • Helps catch potential type-related issues during development.

Overall, this change is a good practice to ensure type consistency and improve code maintainability.


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 generate interesting stats about this repository and render them as a table.
    -- @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.

@HjorturJ HjorturJ changed the title fix(financial-statement-*): using aws-sdkv3 instead of v3 and minor refactoring fix(financial-statement-*): using aws-sdkv3 instead of v2 and minor refactoring Sep 2, 2024
@HjorturJ HjorturJ added the deploy-feature Deploys features to dev label Sep 2, 2024
@datadog-island-is
Copy link

datadog-island-is bot commented Sep 2, 2024

Datadog Report

All test runs 398e784 🔗

101 Total Test Services: 0 Failed, 99 Passed
🔻 Test Sessions change in coverage: 2 decreased, 11 increased, 150 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-backend 0 0 0 81 0 31.78s N/A Link
air-discount-scheme-web 0 0 0 2 0 9.3s N/A Link
api 0 0 0 4 0 2.91s N/A Link
api-catalogue-services 0 0 0 23 0 12.19s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 20.89s N/A Link
api-domains-assets 0 0 0 3 0 13.8s N/A Link
api-domains-auth-admin 0 0 0 18 0 13.92s N/A Link
api-domains-communications 0 0 0 5 0 34.1s N/A Link
api-domains-criminal-record 0 0 0 5 0 10.77s N/A Link
api-domains-driving-license 0 0 0 23 0 33.45s N/A Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • nest-feature-flags - jest 57.3% (-0.47%) - Details
  • services-auth-delegation-api - jest 60.11% (-0.26%) - Details

Copy link

codecov bot commented Sep 2, 2024

Codecov Report

Attention: Patch coverage is 60.79545% with 69 lines in your changes missing coverage. Please review.

Project coverage is 36.86%. Comparing base (128e557) to head (794fc87).
Report is 24 commits behind head on main.

Files with missing lines Patch % Lines
...b/modules/shared/services/attachment-s3.service.ts 23.52% 26 Missing ⚠️
libs/nest/aws/src/lib/aws.service.ts 74.19% 16 Missing ⚠️
...atements-inao/financial-statements-inao.service.ts 37.50% 5 Missing ⚠️
...t-cemetery/financial-statement-cemetery.service.ts 40.00% 3 Missing ⚠️
...mplates/health-insurance/health-insurance.utils.ts 0.00% 3 Missing ⚠️
libs/application/api/files/src/lib/file.service.ts 81.81% 2 Missing ⚠️
...src/lib/modules/templates/estate/estate.service.ts 50.00% 2 Missing ⚠️
...tes/p-sign-submission/p-sign-submission.service.ts 50.00% 2 Missing ⚠️
...templates/parental-leave/parental-leave.service.ts 50.00% 2 Missing ⚠️
...tration/social-insurance-administration.service.ts 50.00% 2 Missing ⚠️
... and 6 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #15842      +/-   ##
==========================================
+ Coverage   36.84%   36.86%   +0.01%     
==========================================
  Files        6716     6719       +3     
  Lines      137707   137770      +63     
  Branches    39154    39191      +37     
==========================================
+ Hits        50741    50784      +43     
- Misses      86966    86986      +20     
Flag Coverage Δ
air-discount-scheme-backend 54.07% <ø> (-0.02%) ⬇️
air-discount-scheme-web 0.00% <ø> (ø)
api 3.39% <ø> (ø)
api-catalogue-services 77.85% <ø> (ø)
api-domains-air-discount-scheme 36.85% <ø> (-0.04%) ⬇️
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 49.89% <ø> (ø)
api-domains-communications 40.42% <ø> (-0.01%) ⬇️
api-domains-criminal-record 47.77% <ø> (-0.04%) ⬇️
api-domains-driving-license 44.27% <ø> (-0.02%) ⬇️
api-domains-education 31.22% <ø> (-0.04%) ⬇️
api-domains-health-insurance 34.58% <ø> (-0.05%) ⬇️
api-domains-mortgage-certificate 35.73% <ø> (-0.03%) ⬇️
api-domains-payment-schedule 41.14% <ø> (-0.03%) ⬇️
application-api-files 56.17% <22.97%> (-1.32%) ⬇️
application-core 72.00% <ø> (-0.34%) ⬇️
application-system-api 41.72% <33.90%> (+0.04%) ⬆️
application-template-api-modules 23.51% <12.26%> (+0.02%) ⬆️
application-templates-accident-notification 22.26% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.96% <ø> (ø)
application-templates-driving-license 18.75% <ø> (ø)
application-templates-estate 12.55% <ø> (ø)
application-templates-example-payment 25.72% <ø> (ø)
application-templates-financial-aid 14.39% <ø> (ø)
application-templates-general-petition 23.95% <ø> (ø)
application-templates-health-insurance 26.88% <ø> (ø)
application-templates-inheritance-report 6.45% <ø> (-0.03%) ⬇️
application-templates-marriage-conditions 15.35% <ø> (ø)
application-templates-mortgage-certificate 44.15% <ø> (ø)
application-templates-parental-leave 29.38% <ø> (+0.07%) ⬆️
application-types 6.74% <ø> (ø)
application-ui-components 1.52% <ø> (ø)
application-ui-shell 21.74% <ø> (-0.02%) ⬇️
auth-admin-web 2.43% <ø> (ø)
auth-nest-tools 30.83% <ø> (ø)
auth-react 22.82% <ø> (ø)
auth-shared 75.00% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.56% <ø> (-0.05%) ⬇️
clients-driving-license-book 43.85% <ø> (-0.03%) ⬇️
clients-financial-statements-inao 49.10% <ø> (-0.04%) ⬇️
clients-license-client 1.83% <ø> (ø)
clients-middlewares 72.40% <ø> (-0.35%) ⬇️
clients-regulations 42.54% <ø> (-0.05%) ⬇️
clients-rsk-company-registry 29.76% <ø> (ø)
clients-rsk-personal-tax-return 38.00% <ø> (ø)
clients-smartsolutions 12.77% <ø> (ø)
clients-syslumenn 49.75% <ø> (-0.03%) ⬇️
clients-zendesk 55.65% <ø> (ø)
cms 0.42% <ø> (ø)
cms-translations 39.57% <ø> (-0.01%) ⬇️
content-search-index-manager 95.65% <ø> (ø)
content-search-toolkit 8.50% <ø> (ø)
contentful-apps 5.76% <ø> (-0.29%) ⬇️
dokobit-signing 62.85% <ø> (-0.09%) ⬇️
download-service 44.55% <ø> (-0.02%) ⬇️
email-service 60.65% <ø> (-0.09%) ⬇️
feature-flags 90.69% <ø> (-0.08%) ⬇️
file-storage 53.01% <ø> (-0.12%) ⬇️
financial-aid-backend 56.52% <ø> (-0.02%) ⬇️
financial-aid-shared 19.03% <ø> (ø)
icelandic-names-registry-backend 54.64% <ø> (ø)
infra-nest-server 48.95% <ø> (ø)
infra-tracing 43.24% <ø> (ø)
island-ui-core 28.59% <ø> (ø)
judicial-system-api 19.35% <ø> (ø)
judicial-system-audit-trail 68.53% <ø> (-0.09%) ⬇️
judicial-system-formatters 79.83% <ø> (ø)
judicial-system-message 66.79% <ø> (-0.07%) ⬇️
judicial-system-message-handler 47.61% <ø> (-0.10%) ⬇️
judicial-system-scheduler 68.98% <ø> (-0.03%) ⬇️
judicial-system-types 48.34% <ø> (ø)
judicial-system-web 28.71% <ø> (+<0.01%) ⬆️
license-api 42.84% <ø> (-0.09%) ⬇️
localization 10.15% <ø> (ø)
logging 48.43% <ø> (ø)
message-queue 68.42% <100.00%> (+0.70%) ⬆️
nest-audit 68.20% <ø> (ø)
nest-aws 56.61% <73.01%> (?)
nest-config 78.07% <ø> (-0.07%) ⬇️
nest-feature-flags 51.91% <ø> (-0.07%) ⬇️
nest-problem 46.48% <ø> (ø)
nest-sequelize 94.44% <ø> (ø)
nest-swagger 51.71% <ø> (ø)
nova-sms 62.18% <ø> (-0.10%) ⬇️
portals-admin-regulations-admin 1.96% <ø> (ø)
portals-core 16.14% <ø> (ø)
reference-backend 50.57% <ø> (ø)
regulations 16.78% <ø> (ø)
residence-history 85.00% <ø> (ø)
services-auth-admin-api 52.83% <ø> (-0.01%) ⬇️
services-auth-delegation-api 61.31% <ø> (-0.01%) ⬇️
services-auth-ids-api 54.02% <ø> (-0.03%) ⬇️
services-auth-personal-representative 47.98% <ø> (-0.01%) ⬇️
services-auth-personal-representative-public 43.86% <ø> (-0.06%) ⬇️
services-auth-public-api 51.81% <ø> (-0.01%) ⬇️
services-documents 61.26% <ø> (ø)
services-endorsements-api 54.42% <14.06%> (-0.58%) ⬇️
services-sessions 65.79% <ø> (-0.02%) ⬇️
services-university-gateway 48.42% <ø> (-0.02%) ⬇️
services-user-notification 47.58% <100.00%> (-0.01%) ⬇️
services-user-profile 62.26% <ø> (-0.01%) ⬇️
shared-components 27.65% <ø> (ø)
shared-form-fields 31.58% <ø> (ø)
shared-mocking 64.62% <ø> (ø)
shared-pii 92.85% <ø> (ø)
shared-problem 87.50% <ø> (ø)
shared-utils 29.26% <ø> (ø)
skilavottord-ws 24.34% <ø> (ø)
web 1.84% <ø> (+<0.01%) ⬆️

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

Files with missing lines Coverage Δ
...rc/app/modules/application/template-api.service.ts 70.96% <ø> (ø)
...pi-modules/src/lib/modules/shared/shared.module.ts 100.00% <100.00%> (ø)
...i-modules/src/lib/modules/shared/shared.service.ts 56.89% <ø> (+12.45%) ⬆️
...ident-notification/accident-notification.module.ts 100.00% <100.00%> (ø)
...ation/attachments/applicationAttachment.service.ts 91.30% <100.00%> (ø)
...chments/providers/applicationAttachmentProvider.ts 27.77% <100.00%> (ø)
...tion-complaint/data-protection-complaint.module.ts 100.00% <ø> (ø)
.../src/lib/modules/templates/estate/estate.module.ts 100.00% <100.00%> (ø)
...alth-insurance-declaration/attachments/provider.ts 44.44% <100.00%> (ø)
...plates/health-insurance/health-insurance.module.ts 100.00% <100.00%> (ø)
... and 25 more

... and 31 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 128e557...794fc87. Read the comment docs.

Copy link
Contributor

github-actions bot commented Sep 2, 2024

Affected services are: air-discount-scheme-api,air-discount-scheme-backend,api,application-system-api,download-service,financial-aid-api,financial-aid-backend,financial-aid-open-api,github-actions-cache,icelandic-names-registry-backend,judicial-system-api,judicial-system-digital-mailbox-api,judicial-system-backend,judicial-system-message-handler,judicial-system-robot-api,judicial-system-scheduler,judicial-system-xrd-api,license-api,reference-backend,regulations-admin-backend,services-auth-admin-api,services-auth-ids-api,services-auth-delegation-api,services-auth-personal-representative,services-auth-personal-representative-public,services-auth-public-api,services-contentful-entry-tagger,services-documents,services-endorsements-api,services-form-system,services-search-indexer,services-sessions,services-university-gateway,services-user-notification,services-user-profile,services-xroad-collector,skilavottord-ws,air-discount-scheme-web,auth-admin-web,consultation-portal,contentful-apps,financial-aid-web-osk,financial-aid-web-veita,judicial-system-web,skilavottord-web,web,application-system-form,island-ui-storybook,portals-admin,service-portal,system-e2e,external-contracts-tests,
Feature deployment of your services will begin shortly. Your feature will be accessible here:
https://fixattachment-and-s3--consolidation-api-catalogue.dev01.devland.is/api
https://fixattachment-and-s3--consolidation-api.dev01.devland.is/download
https://fixattachment-and-s3--consolidation-application-callback-xrd.internal.dev01.devland.is/application-payment
https://fixattachment-and-s3--consolidation-application-callback-xrd.internal.dev01.devland.is/applications
https://fixattachment-and-s3--consolidation-application-payment-callback-xrd.internal.dev01.devland.is/application-payment
https://fixattachment-and-s3--consolidation-application-payment-callback-xrd.internal.dev01.devland.is/applications
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/api
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/app/skilavottord/
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/app/skilavottord/api/graphql
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/minarsidur
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/samradsgatt
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/stjornbord
https://fixattachment-and-s3--consolidation-beta.dev01.devland.is/umsoknir
https://fixattachment-and-s3--consolidation-license-api-xrd.internal.dev01.devland.is/
https://fixattachment-and-s3--consolidation-loftbru-cf.dev01.devland.is/
https://fixattachment-and-s3--consolidation-loftbru-cf.dev01.devland.is/api/graphql
https://fixattachment-and-s3--consolidation-loftbru-cf.dev01.devland.is/api/public
https://fixattachment-and-s3--consolidation-loftbru-cf.dev01.devland.is/api/swagger
https://fixattachment-and-s3--consolidation-loftbru.dev01.devland.is/
https://fixattachment-and-s3--consolidation-loftbru.dev01.devland.is/api/graphql
https://fixattachment-and-s3--consolidation-loftbru.dev01.devland.is/api/public
https://fixattachment-and-s3--consolidation-loftbru.dev01.devland.is/api/swagger
https://fixattachment-and-s3--consolidation-service-portal-api.internal.dev01.devland.is/
https://fixattachment-and-s3--consolidation-services-university-gateway.internal.dev01.devland.is/api
https://fixattachment-and-s3--consolidation-sessions-api.internal.dev01.devland.is/
https://fixattachment-and-s3--consolidation-ui.dev01.devland.is/

Deployed services: application-system-api,application-system-form,service-portal,service-portal-api,portals-admin,consultation-portal,api,web,xroad-collector,skilavottord-web,skilavottord-ws,services-documents,island-ui-storybook,download-service,icelandic-names-registry-backend,endorsement-system-api,air-discount-scheme-web,air-discount-scheme-backend,air-discount-scheme-api,regulations-admin-backend,external-contracts-tests,application-system-api-worker,license-api,services-sessions,services-sessions-worker,services-sessions-cleanup,services-university-gateway,services-university-gateway-worker.
Excluded services: search-indexer-service,github-actions-cache,user-notification,user-notification-worker,user-notification-cleanup-worker,contentful-entry-tagger-service,contentful-apps

@HjorturJ HjorturJ added deploy-feature Deploys features to dev and removed deploy-feature Deploys features to dev labels Sep 3, 2024
@HjorturJ HjorturJ changed the title fix(financial-statement-*): using aws-sdkv3 instead of v2 and minor refactoring fix(template-api-modules): using aws-sdkv3 instead of v2 and minor refactoring Sep 4, 2024
@HjorturJ HjorturJ changed the title fix(template-api-modules): using aws-sdkv3 instead of v2 and minor refactoring fix(template-api-modules): using aws-sdkv3 instead of v2 an refactoring Sep 4, 2024
@HjorturJ HjorturJ changed the title fix(template-api-modules): using aws-sdkv3 instead of v2 an refactoring fix(template-api-modules): using aws-sdkv3 instead of v2 and refactoring Sep 4, 2024
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 (5)
libs/nest/aws/src/lib/aws.service.ts (5)

33-39: LGTM, but consider adding a default value for the encoding parameter.

The getFileContent method is a useful addition to the class as it provides a convenient way to get the content of a file as a string.

The method handles the case where the file is not found by returning undefined instead of throwing an error, which is a good practice.

Consider adding a default value for the encoding parameter. For example:

public async getFileContent(
  BucketKeyPairOrFilename: BucketKeyPair | string,
  encoding: string = 'utf-8',
): Promise<string | undefined> {
  // ...
}

42-75: LGTM, but consider adding a timeout to the upload operation.

The changes to the uploadFile method are approved.

The use of the Upload class is a good practice as it provides a higher-level abstraction for uploading files to S3.

The method logs errors using the injected Logger instance, which is a good practice.

Consider adding a timeout to the upload operation to prevent the method from hanging indefinitely. For example:

const parallelUploads3 = new Upload({
  client: this.s3Client,
  params: uploadParams,
  tags: [], // Add tags to the upload operation
  queueSize: 4, // Increase the queue size to improve performance
  partSize: 5 * 1024 * 1024, // Increase the part size to improve performance
  leavePartsOnError: false, // Delete parts on error to avoid incurring additional costs
});

await parallelUploads3.done({ timeout: 60 * 1000 }); // Add a timeout of 60 seconds

78-93: LGTM, but consider adding a check for the expirationOverride parameter.

The changes to the getPresignedUrl method are approved.

The use of the getSignedUrl function is a good practice as it provides a more secure way to generate presigned URLs.

The method accepts an optional expirationOverride parameter to override the default expiration time of 120 minutes, which is a good practice.

Consider adding a check to ensure that the expirationOverride parameter is a positive number. For example:

const expiration = expirationOverride && expirationOverride > 0 ? expirationOverride : oneMinute * 120;

96-123: LGTM, but consider adding a timeout to the HeadObjectCommand.

The fileExists method is a useful addition to the class as it provides a convenient way to check if a file exists in S3.

The method handles the case where the file does not exist by returning false instead of throwing an error, which is a good practice.

The method logs errors using the injected Logger instance, which is a good practice.

Consider adding a timeout to the HeadObjectCommand to prevent the method from hanging indefinitely. For example:

const command = new HeadObjectCommand({
  Bucket: bucket,
  Key: key,
});

const results = await this.s3Client.send(command, { timeout: 5000 }); // Add a timeout of 5 seconds

125-145: LGTM, but consider adding a check to ensure that the file exists before attempting to delete it.

The deleteObject method is a useful addition to the class as it provides a convenient way to delete a file from S3.

The method logs errors using the injected Logger instance, which is a good practice.

Consider adding a check to ensure that the file exists before attempting to delete it. For example:

public async deleteObject(BucketKeyPairOrFilename: BucketKeyPair | string) {
  try {
    const { bucket, key } = this.getBucketKey(BucketKeyPairOrFilename);
    
    const exists = await this.fileExists(BucketKeyPairOrFilename);
    if (!exists) {
      this.logger.warn(`File ${key} does not exist in bucket ${bucket}`);
      return;
    }
    
    const result = await this.s3Client.send(
      new DeleteObjectCommand({
        Bucket: bucket,
        Key: key,
      }),
    );

    // ...
  } catch (error) {
    // ...
  }
}
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 624f471 and 5235604.

Files selected for processing (12)
  • apps/application-system/api/src/app/modules/application/template-api.service.ts (1 hunks)
  • apps/services/endorsements/api/src/app/modules/endorsementList/endorsementList.service.ts (2 hunks)
  • libs/application/api/files/src/lib/file.service.ts (6 hunks)
  • libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (3 hunks)
  • libs/application/template-api-modules/src/lib/modules/shared/shared.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/children-residence-change/children-residence-change.service.ts (7 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/estate/estate.service.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.utils.ts (4 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.service.ts (3 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.service.ts (5 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.service.ts (3 hunks)
  • libs/nest/aws/src/lib/aws.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (7)
  • apps/application-system/api/src/app/modules/application/template-api.service.ts
  • apps/services/endorsements/api/src/app/modules/endorsementList/endorsementList.service.ts
  • libs/application/api/files/src/lib/file.service.ts
  • libs/application/template-api-modules/src/lib/modules/shared/shared.module.ts
  • libs/application/template-api-modules/src/lib/modules/templates/children-residence-change/children-residence-change.service.ts
  • libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.service.ts
  • libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.service.ts
Additional context used
Path-based instructions (5)
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/aws/src/lib/aws.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/estate/estate.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.utils.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
Additional comments not posted (18)
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (6)

22-28: Excellent use of dependency injection!

Injecting the dependencies (AwsService, ConfigService, and BaseTemplateApiApplicationService) in the constructor is a great improvement. It promotes better separation of concerns, facilitates testing, and makes the code more maintainable.


31-31: Good use of a more specific type!

Updating the method signature to use ApplicationWithAttachments instead of Application is a good change. It improves type safety and makes the code more expressive by indicating that the application object includes attachment-related properties.


71-80: Great improvements in type safety and abstraction!

The changes in the getAttachmentContentAsBase64 method are excellent:

  1. Using ApplicationWithAttachments improves type safety.
  2. Using awsService.getFile abstracts the S3 client usage, making the code more maintainable and less coupled to the specific AWS SDK version.

82-94: Excellent addition of the getAttachmentContentAsBlob method!

Adding this method enhances the service's capabilities by providing functionality to retrieve attachment content as a Blob. It follows a similar pattern to the getAttachmentContentAsBase64 method, using awsService.getFile for a more maintainable and less coupled implementation.


96-113: Great addition of the getAttachmentUrl method!

Adding this method enhances the service's capabilities by providing functionality to generate signed URLs for attachments. The error handling for invalid expiration values and missing bucket configurations improves the robustness of the method.


115-131: Excellent addition of the addAttachment method!

Adding this method enhances the service's capabilities by providing functionality to add attachments to the application. Using the applicationService.saveAttachmentToApplicaton method abstracts the saving logic, making the code more maintainable and less coupled to the specific implementation.

libs/application/template-api-modules/src/lib/modules/templates/estate/estate.service.ts (2)

35-35: LGTM!

The import statement for AwsService is correct and necessary.


44-44: Refactoring approved!

The refactoring of the EstateTemplateService to use the injected AwsService for retrieving file content is a positive change that enhances modularity, testability, and code clarity. The error handling remains intact.

Key improvements:

  • Decoupling S3 operations by injecting AwsService into the constructor.
  • Streamlining file content retrieval by using the getFileContent method of AwsService.
  • Maintaining error handling.

Great job on this refactoring! It aligns well with best practices for dependency injection and separation of concerns.

Also applies to: 273-277

libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.utils.ts (2)

16-16: LGTM!

The import statement is correctly importing the AwsService from the specified path.


37-37: LGTM!

The changes in the insuranceToXML function look good:

  • The bucketService parameter has been correctly replaced with awsService of type AwsService in the function signature.
  • The getFileContent method is now correctly called on the awsService instance to retrieve file content from S3.
  • The error handling ensures that an error is thrown if the file content retrieval fails, improving the robustness of the code.

Also applies to: 96-102, 106-106

libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.service.ts (8)

118-118: LGTM!

The addition of the awsService dependency in the constructor promotes dependency injection and modularity. It's a good practice to use a dedicated service for AWS operations.


Line range hint 407-584:


Line range hint 586-633:


Line range hint 635-1104:


Line range hint 1106-1247:


Line range hint 1249-1277:


Line range hint 1279-1296:


389-395: LGTM, but verify the getFileContent implementation.

The change to use this.awsService.getFileContent() aligns with the shift towards using the AwsService for AWS operations. It's a good practice to centralize AWS-related functionality in a dedicated service.

However, ensure that the getFileContent method of AwsService is implemented correctly to handle the retrieval of file content from S3. Verify that it returns the file content in the expected format (base64 in this case) and handles errors appropriately.

Run the following script to verify the getFileContent implementation:

Verification successful

The getFileContent method is correctly implemented in the AwsService class.

The method is located in libs/nest/aws/src/lib/aws.service.ts and handles S3 operations to retrieve file content, returning it in the specified encoding format. This aligns with the intended functionality and centralizes AWS-related operations within the AwsService.

  • File: libs/nest/aws/src/lib/aws.service.ts
  • Method: getFileContent
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of `AwsService.getFileContent()`.

# Test: Search for the method implementation. Expect: The method should handle S3 operations and return the file content in base64 format.
ast-grep --lang typescript --pattern $'class AwsService {
  $$$
  getFileContent($_,$_) {
    $$$
  }
  $$$
}'

Length of output: 111


Script:

#!/bin/bash
# Locate files containing the AwsService class
fd -e ts 'AwsService' --exec rg 'class AwsService' -l

# Search for the getFileContent method within the located files
fd -e ts 'AwsService' --exec rg 'getFileContent' -A 5

Length of output: 105


Script:

#!/bin/bash
# Search for the AwsService class definition across the entire codebase
rg 'class AwsService' -t ts -A 5

# Search for the getFileContent method across the entire codebase
rg 'getFileContent' -t ts -A 5

Length of output: 10672

@kodiakhq kodiakhq bot removed the automerge Merge this PR as soon as all checks pass label Sep 11, 2024
Copy link
Contributor

kodiakhq bot commented Sep 11, 2024

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

libs/nest/aws/src/lib/aws.service.ts Outdated Show resolved Hide resolved
libs/nest/aws/src/lib/aws.service.ts Outdated Show resolved Hide resolved
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 (2)
libs/nest/aws/src/lib/aws.service.ts (2)

77-92: LGTM with a minor suggestion!

The getPresignedUrl method is correctly implemented and follows the best practices for generating presigned URLs using the AWS SDK v3. The method extracts the bucket and key using the getBucketKey method, constructs a GetObjectCommand, and uses the getSignedUrl function from @aws-sdk/s3-request-presigner to generate the presigned URL.

Consider moving the default expiration time (oneMinute * 120) to a constant or configuration value to improve readability and maintainability.


123-142: LGTM with a minor suggestion!

The deleteObject method is correctly implemented and provides a straightforward way to delete an object from the S3 bucket. The method extracts the bucket and key using the getBucketKey method, constructs a DeleteObjectCommand, and sends the command using the s3Client. The error handling ensures that unexpected HTTP status codes are caught and logged appropriately.

Consider throwing an error instead of just logging it when an unexpected HTTP status code is encountered during object deletion. This would allow the caller to handle the error more effectively.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5235604 and 6bc5086.

Files selected for processing (4)
  • libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (3 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/data-protection-complaint/attachments/providers/applicationAttachmentProvider.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts (2 hunks)
  • libs/nest/aws/src/lib/aws.service.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • libs/application/template-api-modules/src/lib/modules/templates/data-protection-complaint/attachments/providers/applicationAttachmentProvider.ts
Additional context used
Path-based instructions (3)
libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/aws/src/lib/aws.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
Additional comments not posted (17)
libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts (3)

19-19: LGTM!

The import statement is necessary and correctly added.


67-67: LGTM!

The change to use awsService instead of bucketService in the insuranceToXML function call is consistent with the updated constructor and the transition to using AwsService. The change looks good.


26-26: Verify that all usages of bucketService have been replaced with awsService.

The change in the constructor to inject AwsService instead of BucketService is consistent with the updated import statement. This change suggests a transition to utilizing AWS services for storage, which may enhance functionality or performance.

Please ensure that all usages of bucketService have been replaced with awsService in the rest of the file to maintain consistency and avoid any potential issues.

Run the following script to verify the usage of bucketService and awsService:

Verification successful

All usages of bucketService have been replaced with awsService.

The verification confirms that bucketService is no longer used in the file, and awsService is correctly utilized. This ensures consistency with the constructor change and suggests a successful transition to using AWS services.

  • No occurrences of bucketService found.
  • awsService is used as expected.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `bucketService` is not used and `awsService` is used instead.

# Test 1: Search for the usage of `bucketService`. Expect: No occurrences.
rg --type typescript $'bucketService' libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts

# Test 2: Search for the usage of `awsService`. Expect: At least one occurrence.
rg --type typescript $'awsService' libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts

Length of output: 358


Script:

#!/bin/bash
# Description: Verify that `bucketService` is not used and `awsService` is used instead.

# Test 1: Search for the usage of `bucketService`. Expect: No occurrences.
rg 'bucketService' libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts

# Test 2: Search for the usage of `awsService`. Expect: At least one occurrence.
rg 'awsService' libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.service.ts

Length of output: 311

libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (6)

22-28: LGTM!

The use of dependency injection in the constructor is a good practice. It promotes better separation of concerns and facilitates more flexible testing and configuration.


31-31: LGTM!

The change to use ApplicationWithAttachments instead of Application in the method signature is appropriate as it likely includes additional attachment-related properties.


69-78: LGTM!

The changes to the getAttachmentContentAsBase64 method are an improvement:

  • The use of ApplicationWithAttachments is consistent with other method signature changes.
  • The use of AmazonS3URI and awsService.getFile provides a more robust way to retrieve the file content.

80-92: LGTM!

The addition of the getAttachmentContentAsBlob method is a useful enhancement:

  • It provides the functionality to retrieve the attachment content as a Blob object.
  • The implementation is correct and follows a similar pattern to the getAttachmentContentAsBase64 method.

94-111: LGTM!

The addition of the getAttachmentUrl method is a valuable enhancement:

  • It provides the functionality to generate signed URLs for accessing attachments.
  • The error handling for invalid expiration values and missing bucket configurations is appropriate.
  • The use of awsService.getPresignedUrl is the correct way to generate signed URLs.

113-129: LGTM!

The addition of the addAttachment method is a helpful enhancement:

  • It provides a convenient way to add attachments to the application.
  • The use of applicationService.saveAttachmentToApplicaton is appropriate for saving the attachment.
libs/nest/aws/src/lib/aws.service.ts (8)

1-12: LGTM!

The imports from the AWS SDK v3 and other dependencies are correctly added and necessary for the refactored code.


14-17: LGTM!

The BucketKeyPair interface is correctly defined and will be useful for the refactored code.


21-24: LGTM!

The constructor is correctly defined and the dependencies (S3Client and logger) are properly injected.


26-30: LGTM!

The getFile method is correctly implemented and handles the input parameter (BucketKeyPairOrFilename) flexibly by accepting either a BucketKeyPair object or a string. The method extracts the bucket and key using the getBucketKey method and calls the getFileResponse method to fetch the file.


33-39: LGTM!

The getFileContent method is correctly implemented and provides a convenient way to fetch the file content as a string. The method extracts the bucket and key using the getBucketKey method, calls the getFileResponse method to fetch the file, and transforms the response body to a string using the transformToString method with the optional encoding parameter.


42-74: LGTM!

The uploadFile method is correctly implemented and leverages the Upload class from @aws-sdk/lib-storage for efficient parallel uploads. The method extracts the bucket and key using the getBucketKey method, constructs the upload parameters, and performs the upload. The error handling and logging are also properly implemented, ensuring that any errors during the upload process are caught and logged appropriately.


95-121: LGTM!

The fileExists method is correctly implemented and provides a reliable way to check if a file exists in the S3 bucket. The method extracts the bucket and key using the getBucketKey method, constructs a HeadObjectCommand, and sends the command using the s3Client. The error handling covers different scenarios (404 and 403 status codes) and ensures proper logging of unexpected errors.


144-168: LGTM!

The private methods getFileResponse and getBucketKey are correctly implemented and provide reusable functionality for the other methods in the AwsService class.

The getFileResponse method encapsulates the logic for fetching a file from S3 by accepting a bucket and key, constructing a GetObjectCommand, sending the command using the s3Client, and returning the response or undefined if an error occurs.

The getBucketKey method handles the parsing of the input parameter (BucketKeyPairOrFilename) to extract the bucket and key. It either directly returns the BucketKeyPair object or parses the string using the AmazonS3URI function.

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 (1)
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (1)

58-64: Consider renaming getFilenameFromApplication to a more appropriate name.

The changes are correctly implemented. However, as mentioned in the past review comment, the naming of getFilenameFromApplication is a bit confusing as it returns a URL. Consider renaming it to a more appropriate name, such as getAttachmentUrlFromApplication, to improve code readability.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6bc5086 and 6aaaaa6.

Files selected for processing (2)
  • libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (3 hunks)
  • libs/nest/aws/src/lib/aws.service.ts (1 hunks)
Additional context used
Path-based instructions (2)
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/aws/src/lib/aws.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
Additional comments not posted (17)
libs/application/template-api-modules/src/lib/modules/shared/services/attachment-s3.service.ts (7)

22-28: LGTM!

The updated constructor using dependency injection for AwsService, ConfigService, and BaseTemplateApiApplicationService is a good architectural improvement. It promotes better separation of concerns and facilitates more flexible testing and configuration.


31-31: LGTM!

The updated method signature using ApplicationWithAttachments instead of Application is a good change. It indicates a more specific type that likely includes additional attachment-related properties.


54-54: LGTM!

The updated method signature using ApplicationWithAttachments instead of Application is a good change. It indicates a more specific type that likely includes additional attachment-related properties.


70-79: LGTM!

The getAttachmentContentAsBase64 method is correctly implemented. It uses the AmazonS3URI library to parse the S3 URI and retrieve the bucket and key, and then uses the awsService.getFile method to retrieve the file content and transform it to a base64 string.


81-93: LGTM!

The getAttachmentContentAsBlob method is correctly implemented. It uses the AmazonS3URI library to parse the S3 URI and retrieve the bucket and key, and then uses the awsService.getFile method to retrieve the file content and transform it to a byte array. Finally, it creates a new Blob object using the byte array and the content type of the file.


95-112: LGTM!

The getAttachmentUrl method is correctly implemented. It checks if the expiration value is positive and rejects the promise if it's not. It also retrieves the S3 bucket name from the configuration service and rejects the promise if it's not found. Finally, it uses the awsService.getPresignedUrl method to generate a signed URL for the specified bucket and key. The error handling for invalid expiration values and missing bucket configurations is a good addition.


114-130: LGTM!

The addAttachment method is correctly implemented. It uses the applicationService.saveAttachmentToApplicaton method to save the attachment and accepts optional upload parameters for specifying the content type, disposition, and encoding.

libs/nest/aws/src/lib/aws.service.ts (10)

1-12: LGTM!

The imports are correctly updated to use the AWS SDK v3 and other necessary modules.


14-17: LGTM!

The BucketKeyPair interface is correctly defined and improves the type safety of the code.


21-24: LGTM!

The constructor correctly uses dependency injection to inject an instance of S3Client and a logger, which improves the testability and maintainability of the code.


26-30: LGTM!

The getFile method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the getFileResponse method to fetch the file from S3, which centralizes the logic for fetching files.


33-39: LGTM!

The getFileContent method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the getFileResponse method to fetch the file from S3, which centralizes the logic for fetching files. The method then transforms the response body to a string using the transformToString method, which is a useful utility method.


42-74: LGTM!

The uploadFile method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the Upload class from the AWS SDK v3 to upload the file to S3, which is a more efficient and flexible way to upload files compared to the AWS SDK v2. The method also catches any errors that occur during the upload and logs them using the logger, which improves the error handling of the method.


77-92: LGTM!

The getPresignedUrl method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the getSignedUrl function from the AWS SDK v3 to generate a presigned URL for the file, which is a more efficient and flexible way to generate presigned URLs compared to the AWS SDK v2. The method also allows the expiration time of the presigned URL to be overridden using the expirationOverride parameter, which is a useful feature.


95-124: LGTM!

The fileExists method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the HeadObjectCommand class from the AWS SDK v3 to check if the file exists, which is a more efficient and flexible way to check if a file exists compared to the AWS SDK v2. The method also handles any errors that occur during the check based on the httpStatusCode of the error, which improves the error handling of the method.


126-145: LGTM!

The deleteObject method is correctly defined and uses the getBucketKey method to extract the bucket and key from the parameter, which improves the flexibility of the method. The method also uses the DeleteObjectCommand class from the AWS SDK v3 to delete the file, which is a more efficient and flexible way to delete files compared to the AWS SDK v2. The method also checks the httpStatusCode of the response to determine if the file was deleted successfully, which improves the error handling of the method. The method also catches any errors that occur during the deletion and logs them using the logger, which further improves the error handling of the method.


147-162: LGTM!

The getFileResponse method is correctly defined and uses the `Get

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 (1)
libs/nest/aws/src/lib/aws.service.ts (1)

79-94: LGTM with a suggestion!

The changes to the getPresignedUrl method look good. However, consider removing the TODO comment and deciding on a default expiration time for the presigned URLs.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6aaaaa6 and c6b20f0.

Files selected for processing (11)
  • libs/application/api/files/src/lib/file.service.spec.ts (8 hunks)
  • libs/application/template-api-modules/src/lib/modules/shared/shared.module.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/estate/estate.module.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.module.ts (1 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/operating-license/operatingLicense.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.module.ts (2 hunks)
  • libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.module.ts (2 hunks)
  • libs/nest/aws/src/lib/aws.service.spec.ts (1 hunks)
  • libs/nest/aws/src/lib/aws.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • libs/application/template-api-modules/src/lib/modules/shared/shared.module.ts
  • libs/application/template-api-modules/src/lib/modules/templates/health-insurance/health-insurance.module.ts
Additional context used
Path-based instructions (9)
libs/application/template-api-modules/src/lib/modules/templates/estate/estate.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/operating-license/operatingLicense.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/aws/src/lib/aws.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/aws/src/lib/aws.service.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/api/files/src/lib/file.service.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
Additional comments not posted (41)
libs/application/template-api-modules/src/lib/modules/templates/estate/estate.module.ts (2)

9-9: LGTM!

The AwsModule import is correctly written and suggests that AWS services will be integrated into this module.


17-17: Verify the adherence to the additional instructions.

The addition of AwsModule to the imports array is syntactically correct and enhances the module's functionality by integrating AWS services. However, please ensure that the following points from the additional instructions are addressed:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices.
libs/application/template-api-modules/src/lib/modules/templates/p-sign-submission/p-sign-submission.module.ts (1)

6-6: LGTM!

The AwsModule is correctly added to the imports array of the PSignSubmissionModule. This change enhances the module's functionality by integrating AWS services, which is consistent with the PR objectives and the AI-generated summary.

The change also adheres to the additional instructions for files matching the libs/**/* pattern:

  • The module is reusable across different NextJS apps.
  • TypeScript is used for defining the module configuration.
  • The module is effectively tree-shaken and bundled.

Also applies to: 15-15

libs/application/template-api-modules/src/lib/modules/templates/operating-license/operatingLicense.module.ts (2)

9-9: LGTM!

The AwsModule import is correctly added, following the project's import style. This change suggests that AWS services will be integrated into the OperatingLicenseModule.


18-18: Verify the usage of AWS services in the OperatingLicenseService.

Adding the AwsModule to the imports array is the correct way to integrate it into the module's dependency injection system. This change will make AWS services available for injection in the OperatingLicenseService and other providers of this module, facilitating cloud-related operations or features in the context of operating licenses.

Please ensure that the injected AWS services are being used correctly in the OperatingLicenseService and other relevant parts of the codebase.

Run the following script to verify the usage of AWS services:

Verification successful

AWS services are correctly used in the OperatingLicenseService.

The AwsService is properly imported and injected into the OperatingLicenseService, confirming that AWS services are being utilized as intended. This pattern is consistent across other services in the codebase, indicating correct integration of the AwsModule.

  • OperatingLicenseService imports and uses AwsService.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of AWS services in the `OperatingLicenseService` and other relevant parts of the codebase.

# Test 1: Search for the usage of AWS services in the `OperatingLicenseService`. Expect: At least one occurrence.
rg --type typescript -A 5 $'AwsService|S3Client' libs/application/template-api-modules/src/lib/modules/templates/operating-license/operatingLicense.service.ts

# Test 2: Search for the usage of AWS services in other relevant parts of the codebase. Expect: At least one occurrence.
rg --type typescript -A 5 $'AwsService|S3Client' $(fd --type file --extension ts libs/application/template-api-modules/src/lib/modules/templates/operating-license)

Length of output: 1024


Script:

#!/bin/bash
# Description: Verify the usage of AWS services in the `OperatingLicenseService` and other relevant parts of the codebase.

# Test 1: Search for the usage of AWS services in the `OperatingLicenseService`. Expect: At least one occurrence.
rg --type ts -A 5 $'AwsService|S3Client' libs/application/template-api-modules/src/lib/modules/templates/operating-license/operatingLicense.service.ts

# Test 2: Search for the usage of AWS services in other relevant parts of the codebase. Expect: At least one occurrence.
fd --type file --extension ts libs/application/template-api-modules/src/lib/modules/templates/operating-license | xargs rg --type ts -A 5 $'AwsService|S3Client'

Length of output: 41061

libs/application/template-api-modules/src/lib/modules/templates/social-insurance-administration/social-insurance-administration.module.ts (2)

12-12: LGTM!

The import statement for AwsModule is correct. It is likely needed for utilizing AWS services or functionalities within the SocialInsuranceAdministrationModule.


23-23: Looks good!

Adding AwsModule to the imports array of the SocialInsuranceAdministrationModule is the correct way to make it available for dependency injection. This change aligns with the PR objective of refactoring the usage of S3 clients by consolidating them into a single service class.

libs/application/template-api-modules/src/lib/modules/templates/parental-leave/parental-leave.module.ts (2)

14-14: LGTM!

The import statement for AwsModule is correctly added.


26-26: Verify the proper configuration and usage of AwsModule.

The addition of AwsModule to the imports array is correct and will provide the ParentalLeaveModule with access to AWS-related functionalities. However, please ensure that the AwsModule is properly configured and utilized within the ParentalLeaveModule to leverage the AWS capabilities effectively.

Run the following script to verify the usage of AwsModule:

libs/application/template-api-modules/src/lib/modules/templates/accident-notification/accident-notification.module.ts (2)

9-9: LGTM!

The import statement for AwsModule is correct and follows the expected syntax.


28-28: Verify the usage of AwsModule and the removal of S3Service and S3 provider.

The addition of AwsModule to the imports array is correct and aligns with the objective of refactoring the usage of S3 clients. However, please ensure that:

  1. The AwsModule provides the necessary S3 service that was previously provided by the S3Service and S3 provider.
  2. The removal of S3Service and S3 provider from the providers array does not introduce any issues or break any existing functionality.

Run the following script to verify the usage of AwsModule and the removal of S3Service and S3 provider:

libs/nest/aws/src/lib/aws.service.ts (9)

23-26: LGTM!

The constructor changes improve dependency injection and logging practices.


28-32: LGTM!

The new getFile method provides a convenient way to fetch files from S3 and follows good practices by centralizing the logic in a separate method.


35-41: LGTM!

The new getFileContent method is a useful addition that provides a convenient way to fetch file content as a string.


44-76: LGTM!

The changes to the uploadFile method, including the use of the Upload class for parallel uploads and the improved error handling and logging, are great improvements.


97-126: LGTM!

The new fileExists method is a useful addition, and the robust error handling for different HTTP status codes is a good practice.


128-147: LGTM!

The new deleteObject method is a necessary addition, and the error handling and logging are good practices.


149-156: LGTM!

Extracting the getBucketKey method is a good practice to avoid code duplication, as it is used in multiple methods.


158-172: LGTM!

Extracting the logic for fetching files into a separate getFileResponse method is a good practice, and the error handling and logging are beneficial for diagnostics.


1-12: LGTM!

Updating the imports to use the new AWS SDK v3 modules is necessary for the transition.

libs/nest/aws/src/lib/aws.service.spec.ts (8)

45-59: LGTM!

The test case is well-written and covers the positive scenario of retrieving a file from an S3 bucket. It mocks the necessary dependencies, calls the getFile method of AwsService, and asserts that the returned result matches the expected value.


61-67: LGTM!

The test case is well-written and covers the negative scenario of handling an error when retrieving a file from an S3 bucket. It mocks the GetObjectCommand to reject with an error, calls the getFile method of AwsService, and asserts that the returned result is undefined.


69-82: LGTM!

The test case is well-written and covers various encoding scenarios for retrieving file content from an S3 bucket. It uses it.each to test multiple encoding values, mocks the GetObjectCommand to return a specific result, calls the getFileContent method of AwsService, and asserts that the returned result matches the expected value based on the provided encoding.


84-93: LGTM!

The test case is well-written and covers the scenario of retrieving a presigned URL for an S3 object. It mocks the getSignedUrl function to return a specific result, calls the getPresignedUrl method of AwsService, and asserts that the returned result matches the expected value.


95-103: LGTM!

The test case is well-written and covers the scenario of checking if an object exists in an S3 bucket. It mocks the HeadObjectCommand to resolve with a specific metadata, calls the fileExists method of AwsService, and asserts that the returned result is true.


105-113: LGTM!

The test case is well-written and covers various scenarios where the object doesn't exist in an S3 bucket. It uses it.each to test multiple HTTP status codes, mocks the HeadObjectCommand to resolve with specific metadata based on the status code, calls the fileExists method of AwsService, and asserts that the returned result is false.


115-135: LGTM!

The test cases are well-written and cover various scenarios related to deleting an object from an S3 bucket. They use it.each to test multiple HTTP status codes, mock the DeleteObjectCommand to resolve with specific metadata based on the status code, call the deleteObject method of AwsService, and assert the expected behavior.

The first test case asserts that the method resolves without an error for successful status codes, while the second test case asserts that an error is logged for unexpected status codes.


137-149: LGTM!

The test case is well-written and covers the scenario of extracting bucket and key information from different input formats. It calls the getBucketKey method of AwsService with a bucket-key pair and a file URI, and asserts that the returned bucket and key values match the expected values.

libs/application/api/files/src/lib/file.service.spec.ts (13)

8-8: LGTM!

The import statement for AwsModule and AwsService is correct and follows the proper syntax.


16-16: LGTM!

The import statement for GetObjectCommandOutput is correct and follows the proper syntax.


17-17: LGTM!

The import statement for Readable is correct and follows the proper syntax.


120-120: LGTM!

The addition of AwsModule to the list of imports in the testing module is correct and necessary for using the AwsService in the tests.


130-130: LGTM!

The addition of FileService to the list of providers in the testing module is correct and necessary for testing the FileService.


136-137: LGTM!

The mocking of the getFileContent method of AwsService is correct and necessary for testing the FileService without making actual calls to AWS. The mock implementation returns a string value, which is likely the expected type of the file content.


180-181: LGTM!

The change in the method signature of uploadFile to use an object containing bucket and key properties is consistent with the alterations mentioned in the AI-generated summary. The object destructuring syntax is correct and improves the readability of the code.


189-189: LGTM!

The change in the method signature of getPresignedUrl to use an object containing bucket and key properties is consistent with the alterations mentioned in the AI-generated summary. The object destructuring syntax is correct and improves the readability of the code.


201-203: LGTM!

The change in the method signature of getFileContent to use an object containing bucket and key properties is consistent with the alterations mentioned in the AI-generated summary. The object destructuring syntax is correct and improves the readability of the code. The addition of the 'binary' argument is likely necessary for the correct handling of the file content.


227-228: LGTM!

The mocking of the getFileContent method of AwsService to return an empty string is likely done to test the error handling scenario when the file content is missing. The mock implementation is correct and necessary for testing the error handling in the FileService.


238-240: LGTM!

The change in the method signature of getFileContent to use an object containing bucket and key properties is consistent with the alterations mentioned in the AI-generated summary. The object destructuring syntax is correct and improves the readability of the code. The addition of the 'binary' argument is likely necessary for the correct handling of the file content.


274-274: LGTM!

The change in the method signature of getPresignedUrl to use an object containing bucket and key properties is consistent with the alterations mentioned in the AI-generated summary. The object destructuring syntax is correct and improves the readability of the code.


Line range hint 1-346: Overall assessment: The changes in the file are well-structured and improve the code quality.

The changes in the file.service.spec.ts file are primarily focused on updating the usage of the AwsService methods to align with the new method signatures. The changes are consistent with the alterations mentioned in the AI-generated summary and improve the readability of the code by using object destructuring syntax.

The addition of the AwsModule to the list of imports in the testing module is necessary for using the AwsService in the tests. The mocking of the AwsService methods is done correctly and is necessary for testing the FileService without making actual calls to AWS.

Overall, the changes in the file are well-structured, follow best practices, and improve the code quality.

package.json Show resolved Hide resolved
@HjorturJ HjorturJ requested a review from a team as a code owner September 16, 2024 12:17
@HjorturJ HjorturJ removed the deploy-feature Deploys features to dev label Oct 2, 2024
@HjorturJ HjorturJ marked this pull request as draft October 2, 2024 14:32
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.

5 participants