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

Extract preferences related server handlers from main.ts to server/preferences/app.ts #4420

Merged
merged 5 commits into from
Feb 21, 2025

Conversation

joel-jeremy
Copy link
Contributor

Related to #1113

@actual-github-bot actual-github-bot bot changed the title Extract preferences related server handlers from main.ts to server/preferences/app.ts [WIP] Extract preferences related server handlers from main.ts to server/preferences/app.ts Feb 20, 2025
Copy link

netlify bot commented Feb 20, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 62f63b6
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67b8ab57f2d62700085bd2d2
😎 Deploy Preview https://deploy-preview-4420.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Feb 20, 2025

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
17 6.98 MB → 6.99 MB (+7.19 kB) +0.10%
Changeset
File Δ Size
locale/pt-BR.json 📈 +7.19 kB (+6.76%) 106.33 kB → 113.53 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/pt-BR.js 106.33 kB → 113.53 kB (+7.19 kB) +6.76%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/fr.js 73.67 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/en.js 103.19 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/en-GB.js 99.33 kB 0%
static/js/nl.js 98.45 kB 0%
static/js/de.js 111.98 kB 0%
static/js/uk.js 111.11 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 85.76 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/AppliedFilters.js 10.79 kB 0%
static/js/wide.js 102.9 kB 0%
static/js/ReportRouter.js 1.59 MB 0%
static/js/index.js 4.35 MB 0%

Copy link
Contributor

github-actions bot commented Feb 20, 2025

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.34 MB → 1.34 MB (+157 B) +0.01%
Changeset
File Δ Size
packages/loot-core/src/server/preferences/app.ts 📈 +3.2 kB (+522.29%) 628 B → 3.82 kB
packages/loot-core/src/server/main.ts 📉 -2.59 kB (-5.39%) 48.14 kB → 45.54 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.34 MB → 1.34 MB (+157 B) +0.01%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

@joel-jeremy joel-jeremy changed the title [WIP] Extract preferences related server handlers from main.ts to server/preferences/app.ts Extract preferences related server handlers from main.ts to server/preferences/app.ts Feb 20, 2025
Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Warning

Rate limit exceeded

@joel-jeremy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 66924d5 and 62f63b6.

📒 Files selected for processing (1)
  • packages/loot-core/src/server/preferences/app.ts (2 hunks)

Walkthrough

The pull request introduces significant changes to the loot-core package, particularly in the management of user preferences. In main.ts, the handlers for saving and loading global preferences (save-global-prefs and load-global-prefs) have been completely removed, indicating a shift in preference management. The getDefaultDocumentDir function has been modified to be an exported function, enhancing its accessibility. In preferences/app.ts, new asynchronous methods for managing global and metadata preferences have been added, including saveGlobalPrefs, loadGlobalPrefs, saveMetadataPrefs, and loadMetadataPrefs. The legacy handlers.d.ts file has been deleted, and the import statements in handlers.d.ts have been updated to reflect the new structure. Additionally, multiple methods related to preference handling have been removed from the ServerHandlers interface, marking a substantial change in the server's approach to managing preferences.

Possibly related PRs

Suggested labels

:sparkles: Merged

Suggested reviewers

  • MikesGlitch
  • csenel
  • jfdoming

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. (Beta)
  • @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.

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

🧹 Nitpick comments (3)
packages/loot-core/src/server/preferences/app.ts (3)

49-49: getSyncedPrefs function
Returns a map of preference IDs to values from the database. Consider minimal error-handling for missing or invalid table entries.

Also applies to: 59-59


94-134: Simplify boolean assignment at line 115
Instead of using the ternary operator, you can use a direct boolean expression, e.g.:

- floatingSidebar: floatingSidebar === 'true' ? true : false,
+ floatingSidebar: floatingSidebar === 'true',

This reduces complexity without altering behavior.

🧰 Tools
🪛 Biome (1.9.4)

[error] 115-115: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


136-157: saveMetadataPrefs function
Consider verifying if userToken is null and returning an error to match patterns used in other server calls. Currently, it’s used at line 141 without a guarantee of its presence.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d3b046 and 7e5dfc8.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4420.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • packages/loot-core/src/server/main.ts (2 hunks)
  • packages/loot-core/src/server/preferences/app.ts (2 hunks)
  • packages/loot-core/src/server/preferences/types/handlers.d.ts (0 hunks)
  • packages/loot-core/src/types/handlers.d.ts (1 hunks)
  • packages/loot-core/src/types/server-handlers.d.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • packages/loot-core/src/server/preferences/types/handlers.d.ts
  • packages/loot-core/src/types/server-handlers.d.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/loot-core/src/types/handlers.d.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/loot-core/src/server/preferences/app.ts

[error] 115-115: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (12)
packages/loot-core/src/server/preferences/app.ts (10)

1-3: Great job on the new imports
They are used appropriately, and the modules are properly referenced within the file.


5-7: Imports for preference types look correct
GlobalPrefs, MetadataPrefs, and SyncedPrefs are clearly used in their respective handlers.


11-11: Import usage for getDefaultDocumentDir
This import is used later to provide a fallback for document directories. The usage appears consistent and correct.


13-13: post import for server calls
The use of post aligns with other asynchronous server calls in the codebase. No issues found.


14-18: New metadata-pref imports
These are essential for retrieving and saving metadata preferences. The approach is consistent.


21-28: PreferencesHandlers interface
Defining this interface with new methods for both global and metadata preferences helps centralize preferences management.


32-37: Registering preference handlers
Linking methods such as saveSyncedPrefs and getSyncedPrefs under preferences/ is clear and organized.


39-39: saveSyncedPrefs function
Straightforward implementation that updates the preferences table. Glad to see it wrapped in an async context for proper DB operations.

Also applies to: 45-45, 47-47


61-92: saveGlobalPrefs logic
Each known preference field is set in asyncStorage when present. The conditional checks are appropriate, and returning 'ok' is consistent with other APIs.


159-162: loadMetadataPrefs function
This succinctly returns the metadata from _getMetadataPrefs with no extra overhead. Looks good.

packages/loot-core/src/server/main.ts (2)

19-19: Switched import to amountToInteger
No issues; this appears to be used for transaction or account-related logic.


2298-2298: Exporting getDefaultDocumentDir
Making this function exportable helps external modules retrieve default directory logic directly.

Copy link
Contributor

@matt-fidd matt-fidd left a comment

Choose a reason for hiding this comment

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

One minor cleanup tweak actually

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

🔭 Outside diff range comments (1)
packages/loot-core/src/server/preferences/app.ts (1)

49-59: 🛠️ Refactor suggestion

Add error handling for database operations.

The function should handle potential database errors to prevent uncaught exceptions from propagating.

 async function getSyncedPrefs(): Promise<SyncedPrefs> {
+  try {
     const prefs = (await db.all('SELECT id, value FROM preferences')) as Array<{
       id: string;
       value: string;
     }>;

     return prefs.reduce<SyncedPrefs>((carry, { value, id }) => {
       carry[id as keyof SyncedPrefs] = value;
       return carry;
     }, {});
+  } catch (error) {
+    console.error('Failed to get synced preferences:', error);
+    throw new Error(`Failed to retrieve preferences: ${error.message}`);
+  }
 }
🧹 Nitpick comments (1)
packages/loot-core/src/server/preferences/app.ts (1)

115-115: Simplify boolean expression.

The ternary operator for boolean conversion can be simplified.

-    floatingSidebar: floatingSidebar === 'true' ? true : false,
+    floatingSidebar: floatingSidebar === 'true',
🧰 Tools
🪛 Biome (1.9.4)

[error] 115-115: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e5dfc8 and 66924d5.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4420.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • packages/loot-core/src/server/main.ts (1 hunks)
  • packages/loot-core/src/server/preferences/app.ts (2 hunks)
  • packages/loot-core/src/server/preferences/types/handlers.d.ts (0 hunks)
  • packages/loot-core/src/types/handlers.d.ts (1 hunks)
  • packages/loot-core/src/types/server-handlers.d.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • packages/loot-core/src/server/preferences/types/handlers.d.ts
  • packages/loot-core/src/types/server-handlers.d.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/loot-core/src/types/handlers.d.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/loot-core/src/server/preferences/app.ts

[error] 115-115: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Visual regression
  • GitHub Check: Functional
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze
🔇 Additional comments (1)
packages/loot-core/src/server/main.ts (1)

1511-1520: LGTM!

The function is well-documented and properly handles platform-specific paths while maintaining backward compatibility.

Comment on lines +39 to +47
async function saveSyncedPrefs({
id,
value,
}: {
id: keyof SyncedPrefs;
value: string | undefined;
}) => {
}) {
await db.update('preferences', { id, value });
};
}
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 error handling for database operations.

The function should handle potential database errors to prevent uncaught exceptions from propagating.

 async function saveSyncedPrefs({
   id,
   value,
 }: {
   id: keyof SyncedPrefs;
   value: string | undefined;
 }) {
+  try {
     await db.update('preferences', { id, value });
+  } catch (error) {
+    console.error('Failed to save synced preferences:', error);
+    throw new Error(`Failed to save preference ${id}: ${error.message}`);
+  }
 }
📝 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
async function saveSyncedPrefs({
id,
value,
}: {
id: keyof SyncedPrefs;
value: string | undefined;
}) => {
}) {
await db.update('preferences', { id, value });
};
}
async function saveSyncedPrefs({
id,
value,
}: {
id: keyof SyncedPrefs;
value: string | undefined;
}) {
try {
await db.update('preferences', { id, value });
} catch (error) {
console.error('Failed to save synced preferences:', error);
throw new Error(`Failed to save preference ${id}: ${error.message}`);
}
}

Comment on lines +136 to +157
async function saveMetadataPrefs(prefsToSet: MetadataPrefs) {
const { cloudFileId } = _getMetadataPrefs();

// Need to sync the budget name on the server as well
if (prefsToSet.budgetName && cloudFileId) {
const userToken = await asyncStorage.getItem('user-token');

const syncServer = getServer()?.SYNC_SERVER;
if (!syncServer) {
throw new Error('No sync server set');
}

await post(syncServer + '/update-user-filename', {
token: userToken,
fileId: cloudFileId,
name: prefsToSet.budgetName,
});
}

await _saveMetadataPrefs(prefsToSet);
return 'ok';
}
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 error handling for network operations.

The function should handle potential network errors during server communication.

 async function saveMetadataPrefs(prefsToSet: MetadataPrefs) {
+  try {
     const { cloudFileId } = _getMetadataPrefs();

     // Need to sync the budget name on the server as well
     if (prefsToSet.budgetName && cloudFileId) {
       const userToken = await asyncStorage.getItem('user-token');

       const syncServer = getServer()?.SYNC_SERVER;
       if (!syncServer) {
         throw new Error('No sync server set');
       }

       await post(syncServer + '/update-user-filename', {
         token: userToken,
         fileId: cloudFileId,
         name: prefsToSet.budgetName,
       });
     }

     await _saveMetadataPrefs(prefsToSet);
     return 'ok';
+  } catch (error) {
+    if (error.message === 'No sync server set') {
+      throw error;
+    }
+    console.error('Failed to save metadata preferences:', error);
+    throw new Error(`Failed to save metadata preferences: ${error.message}`);
+  }
 }
📝 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
async function saveMetadataPrefs(prefsToSet: MetadataPrefs) {
const { cloudFileId } = _getMetadataPrefs();
// Need to sync the budget name on the server as well
if (prefsToSet.budgetName && cloudFileId) {
const userToken = await asyncStorage.getItem('user-token');
const syncServer = getServer()?.SYNC_SERVER;
if (!syncServer) {
throw new Error('No sync server set');
}
await post(syncServer + '/update-user-filename', {
token: userToken,
fileId: cloudFileId,
name: prefsToSet.budgetName,
});
}
await _saveMetadataPrefs(prefsToSet);
return 'ok';
}
async function saveMetadataPrefs(prefsToSet: MetadataPrefs) {
try {
const { cloudFileId } = _getMetadataPrefs();
// Need to sync the budget name on the server as well
if (prefsToSet.budgetName && cloudFileId) {
const userToken = await asyncStorage.getItem('user-token');
const syncServer = getServer()?.SYNC_SERVER;
if (!syncServer) {
throw new Error('No sync server set');
}
await post(syncServer + '/update-user-filename', {
token: userToken,
fileId: cloudFileId,
name: prefsToSet.budgetName,
});
}
await _saveMetadataPrefs(prefsToSet);
return 'ok';
} catch (error) {
if (error.message === 'No sync server set') {
throw error;
}
console.error('Failed to save metadata preferences:', error);
throw new Error(`Failed to save metadata preferences: ${error.message}`);
}
}

Comment on lines +61 to +92
async function saveGlobalPrefs(prefs: GlobalPrefs) {
if ('maxMonths' in prefs) {
await asyncStorage.setItem('max-months', '' + prefs.maxMonths);
}
if ('documentDir' in prefs) {
if (prefs.documentDir && (await fs.exists(prefs.documentDir))) {
await asyncStorage.setItem('document-dir', prefs.documentDir);
}
}
if ('floatingSidebar' in prefs) {
await asyncStorage.setItem('floating-sidebar', '' + prefs.floatingSidebar);
}
if ('language' in prefs) {
await asyncStorage.setItem('language', prefs.language);
}
if ('theme' in prefs) {
await asyncStorage.setItem('theme', prefs.theme);
}
if ('preferredDarkTheme' in prefs) {
await asyncStorage.setItem(
'preferred-dark-theme',
prefs.preferredDarkTheme,
);
}
if ('serverSelfSignedCert' in prefs) {
await asyncStorage.setItem(
'server-self-signed-cert',
prefs.serverSelfSignedCert,
);
}
return 'ok';
}
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 error handling for async storage operations.

The function should handle potential storage errors to prevent uncaught exceptions from propagating.

 async function saveGlobalPrefs(prefs: GlobalPrefs) {
+  try {
     if ('maxMonths' in prefs) {
       await asyncStorage.setItem('max-months', '' + prefs.maxMonths);
     }
     if ('documentDir' in prefs) {
       if (prefs.documentDir && (await fs.exists(prefs.documentDir))) {
         await asyncStorage.setItem('document-dir', prefs.documentDir);
       }
     }
     if ('floatingSidebar' in prefs) {
       await asyncStorage.setItem('floating-sidebar', '' + prefs.floatingSidebar);
     }
     if ('language' in prefs) {
       await asyncStorage.setItem('language', prefs.language);
     }
     if ('theme' in prefs) {
       await asyncStorage.setItem('theme', prefs.theme);
     }
     if ('preferredDarkTheme' in prefs) {
       await asyncStorage.setItem(
         'preferred-dark-theme',
         prefs.preferredDarkTheme,
       );
     }
     if ('serverSelfSignedCert' in prefs) {
       await asyncStorage.setItem(
         'server-self-signed-cert',
         prefs.serverSelfSignedCert,
       );
     }
     return 'ok';
+  } catch (error) {
+    console.error('Failed to save global preferences:', error);
+    throw new Error(`Failed to save global preferences: ${error.message}`);
+  }
 }
📝 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
async function saveGlobalPrefs(prefs: GlobalPrefs) {
if ('maxMonths' in prefs) {
await asyncStorage.setItem('max-months', '' + prefs.maxMonths);
}
if ('documentDir' in prefs) {
if (prefs.documentDir && (await fs.exists(prefs.documentDir))) {
await asyncStorage.setItem('document-dir', prefs.documentDir);
}
}
if ('floatingSidebar' in prefs) {
await asyncStorage.setItem('floating-sidebar', '' + prefs.floatingSidebar);
}
if ('language' in prefs) {
await asyncStorage.setItem('language', prefs.language);
}
if ('theme' in prefs) {
await asyncStorage.setItem('theme', prefs.theme);
}
if ('preferredDarkTheme' in prefs) {
await asyncStorage.setItem(
'preferred-dark-theme',
prefs.preferredDarkTheme,
);
}
if ('serverSelfSignedCert' in prefs) {
await asyncStorage.setItem(
'server-self-signed-cert',
prefs.serverSelfSignedCert,
);
}
return 'ok';
}
async function saveGlobalPrefs(prefs: GlobalPrefs) {
try {
if ('maxMonths' in prefs) {
await asyncStorage.setItem('max-months', '' + prefs.maxMonths);
}
if ('documentDir' in prefs) {
if (prefs.documentDir && (await fs.exists(prefs.documentDir))) {
await asyncStorage.setItem('document-dir', prefs.documentDir);
}
}
if ('floatingSidebar' in prefs) {
await asyncStorage.setItem('floating-sidebar', '' + prefs.floatingSidebar);
}
if ('language' in prefs) {
await asyncStorage.setItem('language', prefs.language);
}
if ('theme' in prefs) {
await asyncStorage.setItem('theme', prefs.theme);
}
if ('preferredDarkTheme' in prefs) {
await asyncStorage.setItem(
'preferred-dark-theme',
prefs.preferredDarkTheme,
);
}
if ('serverSelfSignedCert' in prefs) {
await asyncStorage.setItem(
'server-self-signed-cert',
prefs.serverSelfSignedCert,
);
}
return 'ok';
} catch (error) {
console.error('Failed to save global preferences:', error);
throw new Error(`Failed to save global preferences: ${error.message}`);
}
}

Comment on lines +159 to +161
async function loadMetadataPrefs(): Promise<MetadataPrefs> {
return _getMetadataPrefs();
}
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 error handling for metadata preferences retrieval.

The function should handle potential errors from _getMetadataPrefs.

 async function loadMetadataPrefs(): Promise<MetadataPrefs> {
+  try {
     return _getMetadataPrefs();
+  } catch (error) {
+    console.error('Failed to load metadata preferences:', error);
+    throw new Error(`Failed to load metadata preferences: ${error.message}`);
+  }
 }

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

Comment on lines 94 to 134
async function loadGlobalPrefs() {
const [
[, floatingSidebar],
[, maxMonths],
[, documentDir],
[, encryptKey],
[, language],
[, theme],
[, preferredDarkTheme],
[, serverSelfSignedCert],
] = await asyncStorage.multiGet([
'floating-sidebar',
'max-months',
'document-dir',
'encrypt-key',
'language',
'theme',
'preferred-dark-theme',
'server-self-signed-cert',
] as const);
return {
floatingSidebar: floatingSidebar === 'true' ? true : false,
maxMonths: stringToInteger(maxMonths || ''),
documentDir: documentDir || getDefaultDocumentDir(),
keyId: encryptKey && JSON.parse(encryptKey).id,
language,
theme:
theme === 'light' ||
theme === 'dark' ||
theme === 'auto' ||
theme === 'development' ||
theme === 'midnight'
? theme
: 'auto',
preferredDarkTheme:
preferredDarkTheme === 'dark' || preferredDarkTheme === 'midnight'
? preferredDarkTheme
: 'dark',
serverSelfSignedCert: serverSelfSignedCert || undefined,
};
}
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 error handling for async storage operations.

The function should handle potential storage errors to prevent uncaught exceptions from propagating.

 async function loadGlobalPrefs() {
+  try {
     const [
       [, floatingSidebar],
       [, maxMonths],
       [, documentDir],
       [, encryptKey],
       [, language],
       [, theme],
       [, preferredDarkTheme],
       [, serverSelfSignedCert],
     ] = await asyncStorage.multiGet([
       'floating-sidebar',
       'max-months',
       'document-dir',
       'encrypt-key',
       'language',
       'theme',
       'preferred-dark-theme',
       'server-self-signed-cert',
     ] as const);
     return {
       floatingSidebar: floatingSidebar === 'true',
       maxMonths: stringToInteger(maxMonths || ''),
       documentDir: documentDir || getDefaultDocumentDir(),
       keyId: encryptKey && JSON.parse(encryptKey).id,
       language,
       theme:
         theme === 'light' ||
         theme === 'dark' ||
         theme === 'auto' ||
         theme === 'development' ||
         theme === 'midnight'
           ? theme
           : 'auto',
       preferredDarkTheme:
         preferredDarkTheme === 'dark' || preferredDarkTheme === 'midnight'
           ? preferredDarkTheme
           : 'dark',
       serverSelfSignedCert: serverSelfSignedCert || undefined,
     };
+  } catch (error) {
+    console.error('Failed to load global preferences:', error);
+    throw new Error(`Failed to load global preferences: ${error.message}`);
+  }
 }
📝 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
async function loadGlobalPrefs() {
const [
[, floatingSidebar],
[, maxMonths],
[, documentDir],
[, encryptKey],
[, language],
[, theme],
[, preferredDarkTheme],
[, serverSelfSignedCert],
] = await asyncStorage.multiGet([
'floating-sidebar',
'max-months',
'document-dir',
'encrypt-key',
'language',
'theme',
'preferred-dark-theme',
'server-self-signed-cert',
] as const);
return {
floatingSidebar: floatingSidebar === 'true' ? true : false,
maxMonths: stringToInteger(maxMonths || ''),
documentDir: documentDir || getDefaultDocumentDir(),
keyId: encryptKey && JSON.parse(encryptKey).id,
language,
theme:
theme === 'light' ||
theme === 'dark' ||
theme === 'auto' ||
theme === 'development' ||
theme === 'midnight'
? theme
: 'auto',
preferredDarkTheme:
preferredDarkTheme === 'dark' || preferredDarkTheme === 'midnight'
? preferredDarkTheme
: 'dark',
serverSelfSignedCert: serverSelfSignedCert || undefined,
};
}
async function loadGlobalPrefs() {
try {
const [
[, floatingSidebar],
[, maxMonths],
[, documentDir],
[, encryptKey],
[, language],
[, theme],
[, preferredDarkTheme],
[, serverSelfSignedCert],
] = await asyncStorage.multiGet([
'floating-sidebar',
'max-months',
'document-dir',
'encrypt-key',
'language',
'theme',
'preferred-dark-theme',
'server-self-signed-cert',
] as const);
return {
floatingSidebar: floatingSidebar === 'true',
maxMonths: stringToInteger(maxMonths || ''),
documentDir: documentDir || getDefaultDocumentDir(),
keyId: encryptKey && JSON.parse(encryptKey).id,
language,
theme:
theme === 'light' ||
theme === 'dark' ||
theme === 'auto' ||
theme === 'development' ||
theme === 'midnight'
? theme
: 'auto',
preferredDarkTheme:
preferredDarkTheme === 'dark' || preferredDarkTheme === 'midnight'
? preferredDarkTheme
: 'dark',
serverSelfSignedCert: serverSelfSignedCert || undefined,
};
} catch (error) {
console.error('Failed to load global preferences:', error);
throw new Error(`Failed to load global preferences: ${error.message}`);
}
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 115-115: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

Copy link
Contributor

@matt-fidd matt-fidd left a comment

Choose a reason for hiding this comment

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

LGTM!

@joel-jeremy joel-jeremy merged commit f88b00a into master Feb 21, 2025
21 checks passed
@joel-jeremy joel-jeremy deleted the server-prefs-handlers branch February 21, 2025 17:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants