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/linting in ci #534

Merged
merged 13 commits into from
Nov 12, 2024
Merged

Fix/linting in ci #534

merged 13 commits into from
Nov 12, 2024

Conversation

martijnvdbrug
Copy link
Member

@martijnvdbrug martijnvdbrug commented Nov 12, 2024

Description

  • Lint all packages in CI.
  • Dynamically include all plugins in the CI tests, instead of manually having to add them to the list in test.yml

Checklist

📌 Always:

  • I have set a clear title
  • My PR is small and contains a single feature
  • I have checked my own PR

👍 Most of the time:

  • I have added or updated test cases for important functionality
  • I have updated the README if needed

📦 For publishable packages:

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Walkthrough

The changes in this pull request involve modifications to several files, primarily focusing on enhancing error handling and logging practices, refining test coverage for specific functions, and simplifying code structures. Notable adjustments include updates to ESLint configuration to ignore certain files, the addition of unit tests for the campaign-util module, and improvements in the InvoiceService class's methods for better error management and user input validation.

Changes

File Change Summary
eslint-base.config.js Added **/src/ui/** to the ignores array to exclude UI files from linting checks.
packages/vendure-plugin-campaign-tracker/src/services/campaign-util.spec.ts Introduced a test suite for calculateRevenuePerCampaign, validateAttributions, and isOlderThan functions, enhancing test coverage.
packages/vendure-plugin-invoices/src/services/invoice.service.ts Refined error handling in generatePdfFile, updated downloadMultiple to limit downloads, and improved logging in createInvoicesForOrder.
packages/vendure-plugin-primary-collection/src/util/export-primary-collections.ts Removed ProductPrimaryCollectionPartial type, simplified product query, and streamlined data access.
packages/vendure-plugin-shipping-extensions/src/config/distance-based-shipping-calculator.ts Updated error handling in calculate method to use a specific Error type for better type safety.

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@martijnvdbrug martijnvdbrug marked this pull request as draft November 12, 2024 11:04
@martijnvdbrug martijnvdbrug marked this pull request as ready for review November 12, 2024 11:34
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: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 24b8850 and b132f69.

⛔ Files ignored due to path filters (4)
  • .github/workflows/test.yaml is excluded by !**/*.yaml
  • packages/test/package.json is excluded by !**/*.json
  • packages/util/package.json is excluded by !**/*.json
  • packages/vendure-scripts/package.json is excluded by !**/*.json
📒 Files selected for processing (5)
  • eslint-base.config.js (1 hunks)
  • packages/vendure-plugin-campaign-tracker/src/services/campaign-util.spec.ts (0 hunks)
  • packages/vendure-plugin-invoices/src/services/invoice.service.ts (1 hunks)
  • packages/vendure-plugin-primary-collection/src/util/export-primary-collections.ts (1 hunks)
  • packages/vendure-plugin-shipping-extensions/src/config/distance-based-shipping-calculator.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/vendure-plugin-campaign-tracker/src/services/campaign-util.spec.ts
🔇 Additional comments (1)
eslint-base.config.js (1)

18-18: Verify if excluding all UI code from linting is intentional

Adding **/src/ui/** excludes all UI-related code from linting, which seems to conflict with the PR objective of implementing linting for all packages. Consider:

  1. Using a more specific pattern if only certain UI files need exclusion
  2. Adding a comment explaining why UI code is excluded

Let's check what UI files would be excluded:

Comment on lines +15 to +23
const allProducts = await productRepo
.createQueryBuilder('product')
.innerJoin(
Collection,
'primaryCollection',
'primaryCollection.id = product.customFieldsPrimarycollectionId'
)
.select(['product.id', 'primaryCollection.id'])
.getRawMany()) as ProductPrimaryCollectionPartial[];
.getRawMany();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety to raw query results

The raw query results lack type information, which necessitates unsafe type assertions later in the code.

Consider adding a type for the raw query result:

type RawProductCollection = {
  product_id: string;
  primaryCollection_id: string;
}

And then use it in the query:

.getRawMany() as RawProductCollection[];

Comment on lines +27 to 31
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
productId: product.product_id,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
primaryCollectionId: product.primaryCollection_id,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for raw query results

The code assumes the raw query always returns valid data, which could lead to runtime errors.

Add property checks before assignment:

 data.push({
-  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
-  productId: product.product_id,
-  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
-  primaryCollectionId: product.primaryCollection_id,
+  productId: product.product_id ?? null,
+  primaryCollectionId: product.primaryCollection_id ?? null,
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
productId: product.product_id,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
primaryCollectionId: product.primaryCollection_id,
});
data.push({
productId: product.product_id ?? null,
primaryCollectionId: product.primaryCollection_id ?? null,
});

Comment on lines +114 to +120
} catch (e) {
//eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
Logger.error(
//eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
`Failed to calculate shipping for ${method.name}: ${e.message}`,
`Failed to calculate shipping for ${method.name}: ${
(e as Error)?.message
}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify error handling and remove eslint bypasses

The error handling can be simplified while maintaining type safety.

-    } catch (e) {
-      //eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
-      Logger.error(
-        //eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
-        `Failed to calculate shipping for ${method.name}: ${
-          (e as Error)?.message
-        }`,
-        loggerCtx
-      );
+    } catch (error: unknown) {
+      Logger.error(
+        `Failed to calculate shipping for ${method.name}: ${error instanceof Error ? error.message : 'Unknown error'}`,
+        loggerCtx
+      );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (e) {
//eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
Logger.error(
//eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
`Failed to calculate shipping for ${method.name}: ${e.message}`,
`Failed to calculate shipping for ${method.name}: ${
(e as Error)?.message
}`,
} catch (error: unknown) {
Logger.error(
`Failed to calculate shipping for ${method.name}: ${error instanceof Error ? error.message : 'Unknown error'}`,
loggerCtx
);

Comment on lines +582 to +587
browser.close().catch((e: Error) => {
Logger.error(
`Failed to close puppeteer browser: ${e?.message}`,
loggerCtx
);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent potential memory leak in browser cleanup.

The browser cleanup could fail silently and leak memory if an error occurs during closure. Consider using finally block for cleanup.

-browser.close().catch((e: Error) => {
-  Logger.error(
-    `Failed to close puppeteer browser: ${e?.message}`,
-    loggerCtx
-  );
-});
+try {
+  await browser.close();
+} catch (e) {
+  Logger.error(
+    `Failed to close puppeteer browser: ${e?.message}`,
+    loggerCtx
+  );
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
browser.close().catch((e: Error) => {
Logger.error(
`Failed to close puppeteer browser: ${e?.message}`,
loggerCtx
);
});
try {
await browser.close();
} catch (e) {
Logger.error(
`Failed to close puppeteer browser: ${e?.message}`,
loggerCtx
);
}

path: tmpFilePath,
format: 'A4',
margin: { bottom: 100, top: 100, left: 50, right: 50 },
});
} catch (e) {
// Warning, because this will be retried, or is returned to the user
Logger.warn(
`Failed to generate invoice: ${JSON.stringify((e as any)?.message)}`,
`Failed to generate invoice: ${JSON.stringify((e as Error)?.message)}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix error serialization to handle circular references.

The JSON.stringify on the error object could fail if the error contains circular references. Use util.inspect instead for safer error serialization.

-`Failed to generate invoice: ${JSON.stringify((e as Error)?.message)}`,
+`Failed to generate invoice: ${util.inspect((e as Error)?.message, false, 2)}`,

Committable suggestion skipped: line range outside the PR's diff.

@martijnvdbrug martijnvdbrug merged commit fddf1c4 into main Nov 12, 2024
40 checks passed
@martijnvdbrug martijnvdbrug deleted the fix/linting-in-ci branch November 12, 2024 11:44
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.

1 participant