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

Nc fix/attachments #8478

Merged
merged 3 commits into from
May 15, 2024
Merged

Nc fix/attachments #8478

merged 3 commits into from
May 15, 2024

Conversation

pranavxc
Copy link
Member

Change Summary

Provide summary of changes with issue number if any.

Change type

  • feat: (new feature for the user, not a new feature for build script)
  • fix: (bug fix for the user, not a fix to a build script)
  • docs: (changes to the documentation)
  • style: (formatting, missing semi colons, etc; no production code change)
  • refactor: (refactoring production code, eg. renaming a variable)
  • test: (adding missing tests, refactoring tests; no production code change)
  • chore: (updating grunt tasks etc; no production code change)

Test/ Verification

Provide summary of changes.

Additional information / screenshots (optional)

Anything for maintainers to be made aware of

Copy link
Contributor

coderabbitai bot commented May 15, 2024

Walkthrough

Walkthrough

The recent updates focus on improving attachment error handling in the NocoDB SDK. This includes introducing a new error type, INVALID_ATTACHMENT_JSON, enhancing attachment processing in the BaseModelSqlv2 class, and refining error management in the catchError.ts file.

Changes

Files/Paths Change Summary
packages/nocodb-sdk/src/lib/globals.ts Added INVALID_ATTACHMENT_JSON to NcErrorType enum.
packages/nocodb/src/db/BaseModelSqlv2.ts Enhanced attachment handling by parsing and sanitizing attachments.
packages/nocodb/src/helpers/catchError.ts Introduced INVALID_ATTACHMENT_JSON error type with message and code.
Added static method in NcError class for throwing this error.
packages/nocodb/src/services/attachments.service.ts Updated path construction using path.join for attachment.path.

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>.
    • 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 show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

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: 3

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between af48ec4 and 65e3466.
Files selected for processing (3)
  • packages/nocodb-sdk/src/lib/globals.ts (1 hunks)
  • packages/nocodb/src/db/BaseModelSqlv2.ts (2 hunks)
  • packages/nocodb/src/helpers/catchError.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • packages/nocodb-sdk/src/lib/globals.ts
Additional comments not posted (2)
packages/nocodb/src/helpers/catchError.ts (2)

528-532: Add INVALID_ATTACHMENT_JSON error type to errorHelpers.

The addition of the INVALID_ATTACHMENT_JSON error type to the errorHelpers object looks good. The message function and the code 400 are appropriate for this error type.


696-701: Add invalidAttachmentJson static method to NcError class.

The new invalidAttachmentJson static method in the NcError class is correctly implemented. It throws an NcBaseErrorv2 with the appropriate error type and parameters.

Comment on lines +5494 to +5500
for (let i = 0; i < d[col.id].length; i++) {
if (typeof d[col.id][i] === 'string') {
d[col.id][i] = JSON.parse(d[col.id][i]);
}

const attachment = d[col.id][i];

Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure safe JSON parsing.

The current code assumes that the JSON string is always valid. To prevent potential crashes due to malformed JSON, consider wrapping the JSON.parse call in a try-catch block.

-  if (typeof d[col.id][i] === 'string') {
-    d[col.id][i] = JSON.parse(d[col.id][i]);
+  try {
+    if (typeof d[col.id][i] === 'string') {
+      d[col.id][i] = JSON.parse(d[col.id][i]);
+    }
+  } catch (e) {
+    NcError.invalidAttachmentJson(d[col.id][i]);
+  }

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.

Suggested change
for (let i = 0; i < d[col.id].length; i++) {
if (typeof d[col.id][i] === 'string') {
d[col.id][i] = JSON.parse(d[col.id][i]);
}
const attachment = d[col.id][i];
for (let i = 0; i < d[col.id].length; i++) {
try {
if (typeof d[col.id][i] === 'string') {
d[col.id][i] = JSON.parse(d[col.id][i]);
}
} catch (e) {
NcError.invalidAttachmentJson(d[col.id][i]);
}
const attachment = d[col.id][i];

Comment on lines +6486 to +6493
try {
if (typeof data[column.column_name] === 'string') {
data[column.column_name] = JSON.parse(data[column.column_name]);
}
} catch (e) {
NcError.invalidAttachmentJson(data[column.column_name]);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure safe JSON parsing.

The current code correctly wraps the JSON.parse call in a try-catch block. However, it would be beneficial to log the error for debugging purposes.

-  } catch (e) {
-    NcError.invalidAttachmentJson(data[column.column_name]);
+  } catch (e) {
+    console.error('Failed to parse attachment JSON:', e);
+    NcError.invalidAttachmentJson(data[column.column_name]);

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.

Suggested change
try {
if (typeof data[column.column_name] === 'string') {
data[column.column_name] = JSON.parse(data[column.column_name]);
}
} catch (e) {
NcError.invalidAttachmentJson(data[column.column_name]);
}
try {
if (typeof data[column.column_name] === 'string') {
data[column.column_name] = JSON.parse(data[column.column_name]);
}
} catch (e) {
console.error('Failed to parse attachment JSON:', e);
NcError.invalidAttachmentJson(data[column.column_name]);
}

Comment on lines +6497 to +6501
if (!('url' in attachment) && !('path' in attachment)) {
NcError.unprocessableEntity(
'Attachment object must contain either url or path',
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Clarify error message for missing URL or path.

The error message could be more descriptive to help users understand what went wrong.

-  'Attachment object must contain either url or path',
+  'Each attachment object must contain either a "url" or a "path" property',

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.

Suggested change
if (!('url' in attachment) && !('path' in attachment)) {
NcError.unprocessableEntity(
'Attachment object must contain either url or path',
);
}
if (!('url' in attachment) && !('path' in attachment)) {
NcError.unprocessableEntity(
'Each attachment object must contain either a "url" or a "path" property',
);
}

Copy link
Contributor

github-actions bot commented May 15, 2024

Uffizzi Preview deployment-51744 was deleted.

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: 1

Out of diff range and nitpick comments (4)
packages/nocodb/src/services/attachments.service.ts (4)

Line range hint 121-121: Ensure consistent error handling for all attachment processing steps.

The attachmentPath assignment block should be wrapped in a try-catch to handle potential errors from PresignedUrl.getSignedUrl.

- attachmentPath = `download/${filePath.join('/')}/${fileName}`;
+ try {
+   attachmentPath = `download/${filePath.join('/')}/${fileName}`;
+ } catch (e) {
+   errors.push(e);
+ }

Line range hint 162-162: Optimize the mime type extraction.

The mime type extraction can be simplified by using path.extname directly.

- const type =
-   mimetypes[path.extname(param.path).split('/').pop().slice(1)] ||
-   'text/plain';
+ const type = mimetypes[path.extname(param.path).slice(1)] || 'text/plain';

Line range hint 170-174: Simplify the preview availability check.

The previewAvailable method can be simplified by using Array.includes.

- const available = ['image', 'pdf', 'text/plain'];
- if (available.some((type) => mimetype.includes(type))) {
-   return true;
- }
- return false;
+ return ['image', 'pdf', 'text/plain'].some((type) => mimetype.includes(type));

Line range hint 177-179: Ensure the sanitizeUrlPath method handles edge cases.

The sanitizeUrlPath method should handle empty strings and null values to avoid potential errors.

- return paths.map((url) => url.replace(/[/.?#]+/g, '_'));
+ return paths.map((url) => (url ? url.replace(/[/.?#]+/g, '_') : ''));
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 65e3466 and 5b85181.
Files selected for processing (4)
  • packages/nocodb-sdk/src/lib/globals.ts (1 hunks)
  • packages/nocodb/src/db/BaseModelSqlv2.ts (2 hunks)
  • packages/nocodb/src/helpers/catchError.ts (2 hunks)
  • packages/nocodb/src/services/attachments.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • packages/nocodb-sdk/src/lib/globals.ts
  • packages/nocodb/src/db/BaseModelSqlv2.ts
  • packages/nocodb/src/helpers/catchError.ts

Comment on lines +76 to +80
attachment.path = path.join(
'download',
filePath.join('/'),
fileName,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure consistent error handling for all attachment processing steps.

The attachment.path assignment block should be wrapped in a try-catch to handle potential errors from PresignedUrl.getSignedUrl.

- attachment.path = path.join(
-   'download',
-   filePath.join('/'),
-   fileName,
- );

- attachment.signedPath = await PresignedUrl.getSignedUrl({
-   path: attachment.path.replace(/^download\//, ''),
- });
+ try {
+   attachment.path = path.join(
+     'download',
+     filePath.join('/'),
+     fileName,
+   );

+   attachment.signedPath = await PresignedUrl.getSignedUrl({
+     path: attachment.path.replace(/^download\//, ''),
+   });
+ } catch (e) {
+   errors.push(e);
+ }

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.

Suggested change
attachment.path = path.join(
'download',
filePath.join('/'),
fileName,
);
try {
attachment.path = path.join(
'download',
filePath.join('/'),
fileName,
);
attachment.signedPath = await PresignedUrl.getSignedUrl({
path: attachment.path.replace(/^download\//, ''),
});
} catch (e) {
errors.push(e);
}

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 5b85181 and 28a5eb9.
Files selected for processing (4)
  • packages/nocodb-sdk/src/lib/globals.ts (1 hunks)
  • packages/nocodb/src/db/BaseModelSqlv2.ts (2 hunks)
  • packages/nocodb/src/helpers/catchError.ts (2 hunks)
  • packages/nocodb/src/services/attachments.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • packages/nocodb-sdk/src/lib/globals.ts
  • packages/nocodb/src/db/BaseModelSqlv2.ts
  • packages/nocodb/src/helpers/catchError.ts
  • packages/nocodb/src/services/attachments.service.ts

@dstala dstala merged commit 5b2ba2c into develop May 15, 2024
17 of 21 checks passed
@dstala dstala deleted the nc-fix/attachments branch May 15, 2024 09:21
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.

None yet

3 participants