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

addedSupport for edit of AdvertisementAttachment #3333

Open
wants to merge 1 commit into
base: develop-postgres
Choose a base branch
from

Conversation

udayempire
Copy link

@udayempire udayempire commented Mar 3, 2025

What kind of change does this PR introduce?

refactoring

Issue Number:

In response to updatedPR #3293

Snapshots/Videos:
https://www.loom.com/share/7988c722116945b892a7f7ddf8cd174b?sid=fed21822-8831-41ce-9637-707ba51a4a61

If relevant, did you update the documentation?
No

Summary

Earlier we were not able to edit advertisement due to no minio client in updateAdvertisment.ts
I added the necessary changes for people to edit advertsement.

Does this PR introduce a breaking change?

No

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • New Features
    • Advertisement updates now support multiple file attachments, allowing users to include several files during the update process.
    • The file upload experience has been enhanced with improved validations to ensure only supported file types are processed.

Copy link

github-actions bot commented Mar 3, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

coderabbitai bot commented Mar 3, 2025

Walkthrough

The changes add a new attachments field to the advertisement update input in the GraphQL schema. The schema now accepts a list of file uploads for attachments, and the input processing has been modified to use a more flexible validation scheme. The mutation for updating advertisements has been updated to asynchronously resolve and validate these attachments, insert valid attachments into the database, and upload files to the storage service, while adjusting error handling accordingly.

Changes

File(s) Change Summary
schema.graphql Added a new non-nullable field attachments: [Upload!] to MutationUpdateAdvertisementInput, allowing multiple attachment uploads with advertisement updates.
src/graphql/inputs/...MutationUpdateAdvertisementInput.ts Changed the input schema to use partial() for optional fields; added attachments as an optional array of FileUpload objects with constraints (min 1, max 20); updated validation logic and error messaging.
src/graphql/types/Mutation/updateAdvertisement.ts Modified the mutation resolver to include an asynchronous transformation for attachment processing; added MIME type validation; integrated attachment insertion into the advertisement attachments table and file uploads.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant G as GraphQL Endpoint
    participant R as Mutation Resolver
    participant A as Attachment Processor
    participant S as Storage Service

    C->>G: Send updateAdvertisement mutation with attachments
    G->>R: Parse input via mutationUpdateAdvertisementInputSchema
    R->>A: Asynchronously validate and process attachments
    A-->>R: Return validated attachment files
    R->>S: Upload attachments to storage
    S-->>R: Confirm uploads
    R->>G: Return updated advertisement with attachments
    G-->>C: Response with updated advertisement
Loading

Possibly related PRs

  • Fixing advertisment #3557 #3293: Adds the attachments field to the MutationUpdateAdvertisementInput input type, aligning closely with the changes in this PR.

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes
  • gautam-divyanshu
  • varshith257
✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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

codecov bot commented Mar 3, 2025

Codecov Report

Attention: Patch coverage is 20.00000% with 76 lines in your changes missing coverage. Please review.

Project coverage is 49.38%. Comparing base (4f56a53) to head (c997245).

Files with missing lines Patch % Lines
src/graphql/types/Mutation/updateAdvertisement.ts 7.14% 65 Missing ⚠️
...graphql/inputs/MutationUpdateAdvertisementInput.ts 56.00% 11 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3333      +/-   ##
====================================================
- Coverage             49.45%   49.38%   -0.08%     
====================================================
  Files                   462      462              
  Lines                 34776    34856      +80     
  Branches               1038     1038              
====================================================
+ Hits                  17199    17212      +13     
- Misses                17577    17644      +67     

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

Copy link

@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: 5

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4f56a53 and c997245.

📒 Files selected for processing (3)
  • schema.graphql (1 hunks)
  • src/graphql/inputs/MutationUpdateAdvertisementInput.ts (2 hunks)
  • src/graphql/types/Mutation/updateAdvertisement.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
🔇 Additional comments (10)
src/graphql/inputs/MutationUpdateAdvertisementInput.ts (4)

1-2: Imports look coherent
The usage of FileUpload from "graphql-upload-minimal" and z from "zod" aligns well with the rest of the codebase.


10-10: Confirm correctness of making all fields optional
Using .partial() makes every advertisement field optional. Verify that this is intentional, especially if some fields should remain mandatory.


39-41: Time range validation
Checking endAt > startAt correctly prevents invalid time ranges. If your setup involves different time zones, confirm this logic remains valid across them.


45-45: Clearer error message
The updated error message precisely states that endAt must be greater than startAt. This improves clarity for end users.

src/graphql/types/Mutation/updateAdvertisement.ts (6)

2-3: New import usage
Adding FileUpload and ulid references is aligned with the new attachment-handling workflow.


5-6: Additional advertisement attachment references
Importing advertisementAttachmentMimeTypeEnum and advertisementAttachmentsTable is crucial for validating and storing attachments. Confirm that the enum covers all acceptable file types.


17-17: Asynchronous transform for input
Applying an async transform is a clean way to validate and normalize attachments before proceeding with the remaining logic.


77-77: Asynchronous input parsing
Using safeParseAsync matches your async validation approach. This ensures the final parsed object is accurate before proceeding.


249-252: Handle unexpected database behavior
Logging and throwing an error when the update unexpectedly returns an empty array helps with debugging.


293-293: Final advertisement return
Returning the updated advertisement immediately provides clients with the latest data, ensuring they can confirm their changes.

Comment on lines +2054 to +2056
"""Attachments of the advertisement."""
attachments: [Upload!]

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add clarifying documentation on optional attachments
Currently, the schema indicates a list of non-null Uploads, yet it is also treated as an optional field. Consider making it explicit in the docstring or adjusting the schema to clarify how and when attachments may be omitted entirely.

Comment on lines +16 to +22
id: advertisementsTableInsertSchema.shape.id.unwrap(),
attachments: z
.custom<Promise<FileUpload>>()
.array()
.min(1)
.max(20)
.optional(),
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Ensure alignment of ID unwrapping and attachments constraints
The id field is now mandatory (unwrap()), while attachments is optional but must contain at least one entry when provided. This approach is consistent. However, you might also consider specifying file size or other limits here (as opposed to solely downstream).

Comment on lines +24 to +31
.superRefine(({ attachments, ...remainingArgs }, ctx) => {
if (Array.isArray(attachments) && attachments.length === 0) {
attachments = undefined;
}
if (
!Object.values(remainingArgs).some((value) => value !== undefined) &&
attachments === undefined
) {
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Validate behavior for empty updates
Your superRefine requires at least one non-empty field, preventing no-op updates. However, this also prevents passing an empty attachments array (e.g., for removals). If removing attachments is desirable, consider a dedicated strategy for that.

Comment on lines +18 to +51
let attachments:
| (FileUpload & {
mimetype: z.infer<typeof advertisementAttachmentMimeTypeEnum>;
})[]
| undefined;
if (arg.attachments !== undefined) {
const rawAttachments = await Promise.all(arg.attachments);
const { data, error, success } = advertisementAttachmentMimeTypeEnum
.array()
.safeParse(rawAttachments.map((attachment) => attachment.mimetype));

if (!success) {
for (const issue of error.issues) {
if (typeof issue.path[0] === "number") {
ctx.addIssue({
code: "custom",
path: ["attachments", issue.path[0]],
message: `Mime type "${rawAttachments[issue.path[0]]?.mimetype}" is not allowed.`,
});
}
}
} else {
attachments = rawAttachments.map((attachment, index) =>
Object.assign(attachment, {
mimetype: data[index],
}),
);
}
}
return {
...arg,
attachments,
};
}),
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Asynchronous attachment normalization
Gathering and validating the attachments’ MIME types in a single pass is effective. Consider adding safeguards for:

  • Large file sizes (resource exhaustion).
  • Partial success scenarios (e.g., if only some attachments fail).

Comment on lines +260 to +292
if (parsedArgs.input.attachments !== undefined) {
const attachments = parsedArgs.input.attachments;
const updatedAdvertisementAttachments = await ctx.drizzleClient
.insert(advertisementAttachmentsTable)
.values(
attachments.map((attachment) => ({
advertisementId: updatedAdvertisement.id,
creatorId: currentUserId,
mimeType: attachment.mimetype,
name: ulid(),
})),
)
.onConflictDoNothing()
.returning();

if (Array.isArray(updatedAdvertisementAttachments)) {
await Promise.all(
updatedAdvertisementAttachments.map((attachment, index) => {
if (attachments[index] !== undefined) {
return ctx.minio.client.putObject(
ctx.minio.bucketName,
attachment.name,
attachments[index].createReadStream(),
undefined,
{
"content-type": attachments[index].mimetype,
},
);
}
}),
);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Parallel object uploads
While uploading attachments in parallel is typically faster, consider:

  1. Handling partial failures if individual uploads fail.
  2. Checking resource limits (e.g., large files).
  3. Logging errors from each upload to improve observability.

@Cioppolo14
Copy link
Contributor

Please fix the first comment so that each issue listed automatically closes. The PR_GUIDELINES.md file has details.

Please also fill in the template for the pull request as completely as you can. It greatly helps others searching for code changes in future and helps others understand the summarized rationale for the work you have done

Also make sure the title is easily searchable for terms related to what the PR is about.

The related issue also needs to be stated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants