Skip to content

refactor: migrates another part of console-api to strict types#1362

Merged
stalniy merged 1 commit intomainfrom
refactor/strict-types-2
May 26, 2025
Merged

refactor: migrates another part of console-api to strict types#1362
stalniy merged 1 commit intomainfrom
refactor/strict-types-2

Conversation

@stalniy
Copy link
Contributor

@stalniy stalniy commented May 24, 2025

Summary by CodeRabbit

  • Refactor
    • Removed redundant generic type parameters from configuration and service classes for cleaner inheritance.
    • Replaced lodash functions with native JavaScript array destructuring and at() for safer, more modern array handling.
    • Simplified output transformation and null safety checks in repositories and services.
    • Updated method signatures to explicitly include Promise<Output | undefined> where applicable.
  • Bug Fixes
    • Added explicit error typing in catch blocks to improve type safety.
    • Improved null and undefined handling in external API responses and database queries to prevent runtime errors.
    • Ensured safe default values for numeric and array properties to avoid exceptions.
    • Added explicit error throwing for missing critical data to prevent runtime failures.
  • Chores
    • Broadened TypeScript strict type checking to additional source directories for improved code quality.
    • Fixed JSON syntax in build configuration for proper parsing.
  • Style
    • Updated class signatures and method annotations for clarity and consistency.

@stalniy stalniy requested a review from a team as a code owner May 24, 2025 04:16
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 24, 2025

Walkthrough

This update refactors multiple classes to remove an unnecessary generic parameter, enhances null safety and type correctness across repositories and services, replaces lodash utilities with native JavaScript, and improves error handling by adding explicit types and fallback defaults. Additionally, it broadens TypeScript strict settings to more source directories and adjusts configuration files for stricter type checks.

Changes

File(s) Change Summary
apps/api/src/auth/services/auth-config/auth-config.service.ts
apps/api/src/chain/services/chain-config/chain-config.service.ts
apps/api/src/core/services/core-config/core-config.service.ts
Removed the second generic parameter unknown from ConfigService inheritance in config service classes.
apps/api/src/core/services/config/config.service.ts Added a default generic parameter for C as {} in ConfigService; added explicit type assertion in constructor.
apps/api/src/core/repositories/base.repository.ts
apps/api/src/user/repositories/user/user.repository.ts
Replaced lodash first/last with native JS; updated method signatures for clearer return types and type safety.
apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts Removed lodash imports; used array destructuring; improved null checks and output transformation.
apps/api/src/core/services/error/error.service.ts Updated execWithErrorHandler to return `Promise<T
apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts Updated import and cast context parameter to AppContext in error handler call.
apps/api/src/core/services/tracing/tracing.service.ts
apps/api/src/services/db/userDataService.ts
apps/api/src/services/external/templatesCollector.ts
Added explicit any typing to caught error variables in catch blocks.
apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts Added explicit any type to caught error in catch block.
apps/api/src/caching/helpers.ts Simplified cache refresh logic with a single requiresRefresh boolean.
apps/api/src/healthz/services/healthz/healthz.service.ts Changed logic to return true if DB is connected or no failure timestamp exists.
apps/api/src/lib/drizzle-ability/drizzle-ability.ts Allowed whereAccessibleBy to accept `SQL
apps/api/src/services/db/blocksService.ts
apps/api/src/services/db/transactionsService.ts
apps/api/src/services/db/deploymentService.ts
apps/api/src/services/db/networkRevenueService.ts
apps/api/src/services/db/providerStatusService.ts
apps/api/src/services/db/statsService.ts
Added null/undefined safety, fallback defaults, and explicit error throws for missing data.
apps/api/src/services/external/apiNodeService.ts Applied optional chaining and fallback defaults for safer property access and parsing.
apps/api/src/services/external/templateReposService.ts Added explicit error throw if GitHub PAT is missing; passed token to gallery fetch function.
apps/api/src/services/external/templatesCollector.ts Improved type safety, null handling, and default value assignments in template collection logic.
apps/api/tsconfig.strict.json Broadened strict type-checking to additional source directories in the TypeScript config.
apps/api/tsconfig.build.json Added missing comma to fix JSON syntax in build config.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant Database

    User->>API: Request resource (e.g., user, wallet, stats)
    API->>Database: Query with improved null/undefined safety
    Database-->>API: Data or undefined/null
    API->>API: Apply fallback defaults and type-safe transformations
    API-->>User: Response with robust, type-safe data
Loading

Suggested reviewers

  • ygrishajev

Poem

🐇
With type checks tight and errors tamed,
The code now hops, robustly framed.
No lodash crumbs, just native treats,
Fallbacks guard against defeat.
From config roots to stats that grow,
This bunny’s proud—onward we go!
🥕

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-26T16_41_39_216Z-debug-0.log


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b25c64b and 2e15e68.

📒 Files selected for processing (26)
  • apps/api/src/auth/services/auth-config/auth-config.service.ts (1 hunks)
  • apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts (1 hunks)
  • apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts (3 hunks)
  • apps/api/src/caching/helpers.ts (1 hunks)
  • apps/api/src/chain/services/chain-config/chain-config.service.ts (1 hunks)
  • apps/api/src/core/repositories/base.repository.ts (3 hunks)
  • apps/api/src/core/services/config/config.service.ts (1 hunks)
  • apps/api/src/core/services/core-config/core-config.service.ts (1 hunks)
  • apps/api/src/core/services/error/error.service.ts (1 hunks)
  • apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts (2 hunks)
  • apps/api/src/core/services/tracing/tracing.service.ts (2 hunks)
  • apps/api/src/healthz/services/healthz/healthz.service.ts (1 hunks)
  • apps/api/src/lib/drizzle-ability/drizzle-ability.ts (1 hunks)
  • apps/api/src/services/db/blocksService.ts (4 hunks)
  • apps/api/src/services/db/deploymentService.ts (3 hunks)
  • apps/api/src/services/db/networkRevenueService.ts (2 hunks)
  • apps/api/src/services/db/providerStatusService.ts (1 hunks)
  • apps/api/src/services/db/statsService.ts (7 hunks)
  • apps/api/src/services/db/transactionsService.ts (4 hunks)
  • apps/api/src/services/db/userDataService.ts (3 hunks)
  • apps/api/src/services/external/apiNodeService.ts (5 hunks)
  • apps/api/src/services/external/templateReposService.ts (1 hunks)
  • apps/api/src/services/external/templatesCollector.ts (8 hunks)
  • apps/api/src/user/repositories/user/user.repository.ts (2 hunks)
  • apps/api/tsconfig.build.json (1 hunks)
  • apps/api/tsconfig.strict.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (25)
  • apps/api/tsconfig.build.json
  • apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts
  • apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts
  • apps/api/src/healthz/services/healthz/healthz.service.ts
  • apps/api/src/chain/services/chain-config/chain-config.service.ts
  • apps/api/src/services/external/templateReposService.ts
  • apps/api/src/caching/helpers.ts
  • apps/api/src/services/db/providerStatusService.ts
  • apps/api/tsconfig.strict.json
  • apps/api/src/lib/drizzle-ability/drizzle-ability.ts
  • apps/api/src/core/services/core-config/core-config.service.ts
  • apps/api/src/auth/services/auth-config/auth-config.service.ts
  • apps/api/src/services/db/userDataService.ts
  • apps/api/src/services/external/apiNodeService.ts
  • apps/api/src/services/db/deploymentService.ts
  • apps/api/src/services/db/networkRevenueService.ts
  • apps/api/src/services/db/blocksService.ts
  • apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts
  • apps/api/src/services/db/transactionsService.ts
  • apps/api/src/services/external/templatesCollector.ts
  • apps/api/src/core/services/error/error.service.ts
  • apps/api/src/core/services/tracing/tracing.service.ts
  • apps/api/src/services/db/statsService.ts
  • apps/api/src/user/repositories/user/user.repository.ts
  • apps/api/src/core/repositories/base.repository.ts
🧰 Additional context used
🧠 Learnings (1)
apps/api/src/core/services/config/config.service.ts (1)
Learnt from: stalniy
PR: akash-network/console#1362
File: apps/api/src/core/services/config/config.service.ts:8-9
Timestamp: 2025-05-24T04:25:48.198Z
Learning: In the ConfigService class in apps/api/src/core/services/config/config.service.ts, the `{}` type is used as the default for generic parameter `C` because it's intersected with `z.infer<E>` to create `C & z.infer<E>`. Using `Record<string, never>` instead would break type checking for the merged types since it represents an object that cannot have any properties.
🪛 Biome (1.9.4)
apps/api/src/core/services/config/config.service.ts

[error] 9-9: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (1)
apps/api/src/core/services/config/config.service.ts (1)

16-16: Good addition of explicit type assertion for strict typing.

The explicit type assertion as C & z.infer<E> ensures TypeScript correctly understands the merged type of the configuration object and parsed environment schema. This aligns well with the PR objective of migrating to strict types.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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

🔭 Outside diff range comments (1)
apps/api/src/healthz/services/healthz/healthz.service.ts (1)

22-22: ⚠️ Potential issue

Remove debug log message.

The debug log message "foooo" should be removed as it provides no meaningful information and appears to be leftover from development.

-    this.logger.info("foooo");
🧹 Nitpick comments (4)
apps/api/tsconfig.strict.json (1)

8-19: Simplify include patterns for maintainability
Instead of enumerating each folder, you can collapse this into a single glob. This reduces upkeep when adding new directories:

 "include": [
-    "src/utils/**/*.ts",
-    "src/verify-rsa-jwt-cloudflare-worker-main/**/*.ts",
-    "src/types/**/*.ts",
-    "src/lib/**/*.ts",
-    "src/core/**/*.ts",
-    "src/db/**/*.ts",
-    "src/healthz/**/*.ts",
-    "src/middlewares/**/*.ts",
-    "src/features/**/*.ts",
-    "src/chain/**/*.ts",
-    "src/notifications/**/*.ts",
-    "src/services/**/*.ts"
+    "src/**/*.ts"
 ]
apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts (1)

41-41: Consider using more specific error typing instead of any.

While explicitly typing the catch parameter addresses TypeScript strict mode requirements, using any bypasses type safety. Consider using a more specific approach:

-    } catch (error: any) {
+    } catch (error: unknown) {
+      const errorMessage = error instanceof Error ? error.message : String(error);
-      if (error.message === "Session is still active") {
+      if (errorMessage === "Session is still active") {

This maintains type safety while properly handling the error message access.

apps/api/src/core/services/tracing/tracing.service.ts (1)

69-69: Use Error type instead of any for better type safety.

Both catch blocks expect error objects with a message property and use span.recordException(error). The Error type is more appropriate here:

-      } catch (error: any) {
+      } catch (error: unknown) {
+        const err = error instanceof Error ? error : new Error(String(error));
         span.setStatus({
           code: SpanStatusCode.ERROR,
-          message: error.message
+          message: err.message
         });
-        span.recordException(error);
+        span.recordException(err);
         span.end();
-        throw error;
+        throw err;
       }

This ensures proper error handling while maintaining type safety.

Also applies to: 172-172

apps/api/src/services/db/userDataService.ts (1)

120-120: Consider using Sequelize error types for better type safety.

Both catch blocks handle Sequelize-specific errors. Consider using more specific error types:

-    } catch (error: any) {
-      if (error.name !== "SequelizeUniqueConstraintError") {
+    } catch (error: unknown) {
+      if (error instanceof Error && error.name !== "SequelizeUniqueConstraintError") {
         throw error;
       }

For the second catch block:

-  } catch (error: any) {
-    if (!error.message.includes("user_wallets_user_id_unique")) {
+  } catch (error: unknown) {
+    const errorMessage = error instanceof Error ? error.message : String(error);
+    if (!errorMessage.includes("user_wallets_user_id_unique")) {
       throw error;
     }

This maintains type safety while properly handling Sequelize errors.

Also applies to: 192-192

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b26d8a4 and 2e98c3b.

📒 Files selected for processing (25)
  • apps/api/src/auth/services/auth-config/auth-config.service.ts (1 hunks)
  • apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts (1 hunks)
  • apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts (3 hunks)
  • apps/api/src/caching/helpers.ts (1 hunks)
  • apps/api/src/chain/services/chain-config/chain-config.service.ts (1 hunks)
  • apps/api/src/core/repositories/base.repository.ts (3 hunks)
  • apps/api/src/core/services/config/config.service.ts (1 hunks)
  • apps/api/src/core/services/core-config/core-config.service.ts (1 hunks)
  • apps/api/src/core/services/error/error.service.ts (1 hunks)
  • apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts (2 hunks)
  • apps/api/src/core/services/tracing/tracing.service.ts (2 hunks)
  • apps/api/src/healthz/services/healthz/healthz.service.ts (1 hunks)
  • apps/api/src/lib/drizzle-ability/drizzle-ability.ts (1 hunks)
  • apps/api/src/services/db/blocksService.ts (4 hunks)
  • apps/api/src/services/db/deploymentService.ts (3 hunks)
  • apps/api/src/services/db/networkRevenueService.ts (2 hunks)
  • apps/api/src/services/db/providerStatusService.ts (1 hunks)
  • apps/api/src/services/db/statsService.ts (7 hunks)
  • apps/api/src/services/db/transactionsService.ts (4 hunks)
  • apps/api/src/services/db/userDataService.ts (3 hunks)
  • apps/api/src/services/external/apiNodeService.ts (5 hunks)
  • apps/api/src/services/external/templateReposService.ts (1 hunks)
  • apps/api/src/services/external/templatesCollector.ts (8 hunks)
  • apps/api/src/user/repositories/user/user.repository.ts (2 hunks)
  • apps/api/tsconfig.strict.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (11)
apps/api/src/billing/repositories/checkout-session/checkout-session.repository.ts (1)
packages/logging/src/servicies/logger/logger.service.ts (1)
  • error (107-109)
apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts (1)
apps/api/src/core/types/app-context.ts (1)
  • AppContext (6-6)
apps/api/src/services/db/providerStatusService.ts (1)
apps/indexer/drizzle/schema.ts (1)
  • provider (205-237)
apps/api/src/chain/services/chain-config/chain-config.service.ts (2)
apps/api/src/core/services/config/config.service.ts (1)
  • ConfigService (9-22)
apps/api/src/chain/config/env.config.ts (1)
  • envSchema (3-5)
apps/api/src/auth/services/auth-config/auth-config.service.ts (2)
apps/api/src/core/services/config/config.service.ts (1)
  • ConfigService (9-22)
apps/api/src/auth/config/env.config.ts (1)
  • envSchema (3-12)
apps/api/src/services/external/templateReposService.ts (2)
apps/api/src/services/external/templatesCollector.ts (2)
  • FinalCategory (28-28)
  • getTemplateGallery (102-130)
apps/api/src/caching/helpers.ts (2)
  • cacheResponse (40-74)
  • cacheKeys (76-96)
apps/api/src/services/db/blocksService.ts (1)
apps/indexer/drizzle/schema.ts (1)
  • message (521-567)
apps/api/src/core/services/error/error.service.ts (1)
packages/logging/src/servicies/logger/logger.service.ts (1)
  • error (107-109)
apps/api/src/services/db/networkRevenueService.ts (1)
apps/indexer/drizzle/schema.ts (1)
  • day (92-108)
apps/api/src/services/external/apiNodeService.ts (2)
apps/indexer/drizzle/schema.ts (2)
  • validator (486-513)
  • provider (205-237)
apps/deploy-web/src/utils/apiUtils.ts (3)
  • delegations (54-56)
  • rewards (48-50)
  • redelegations (51-53)
apps/api/src/services/external/templatesCollector.ts (1)
apps/api/src/utils/templateReposLogos.ts (1)
  • getLogoFromPath (1-3)
🪛 Biome (1.9.4)
apps/api/src/core/services/config/config.service.ts

[error] 9-9: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test-api-build
  • GitHub Check: validate-api
🔇 Additional comments (63)
apps/api/tsconfig.strict.json (2)

8-19: Broadened strict type-checking scope approved
Including all key subdirectories under src/ ensures that strict mode is enforced uniformly across the entire API codebase.


8-19:

Details

❓ Verification inconclusive

Verify no missing or unintended files
Run a full type-check to surface any gaps or over-inclusions:

Ensure test specs or generated artifacts are intentionally included or excluded by your patterns.


🏁 Script executed:

npx tsc --noEmit -p apps/api/tsconfig.strict.json

Length of output: 678


TypeScript compiler not found – please install and re-run type-check
I attempted to validate your include globs by running:

npx tsc --noEmit -p apps/api/tsconfig.strict.json

but npm tried to fetch tsc@2.0.4 instead of using your project’s compiler.

  1. Add TypeScript to your dev dependencies:
    npm install --save-dev typescript
  2. Re-run the type-check:
    npx tsc --noEmit -p apps/api/tsconfig.strict.json
  3. Confirm that only intended source files are covered (no test specs or generated artifacts).

Key location to review:

  • apps/api/tsconfig.strict.json (lines 8–19 – your "include" patterns)
apps/api/src/healthz/services/healthz/healthz.service.ts (1)

49-50: Excellent defensive programming improvement!

The refactoring improves both readability and robustness:

  1. Better readability: Storing the connection result in a variable makes the logic clearer
  2. Defensive programming: Adding the !this.dbFailedAt check provides a safety net in case the failure timestamp wasn't properly set

This change aligns well with the PR's objective of improving type safety and null/undefined handling throughout the codebase.

apps/api/src/core/services/config/config.service.ts (1)

16-16:

Details

✅ Verification successful

Review the type assertion for potential type safety concerns.

The type assertion as C & z.infer<E> bypasses TypeScript's type checking and could hide type safety issues. Consider whether the spread operation and optional chaining provide sufficient type safety guarantees, or if additional runtime validation is needed.

Verify that the type assertion is necessary and doesn't mask underlying type incompatibilities:


🏁 Script executed:

#!/bin/bash
# Search for other type assertions in config-related files to understand the pattern
rg -A 3 -B 3 " as " --type ts | grep -E "(config|Config)" -A 3 -B 3

Length of output: 65606


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== ConfigService implementation (apps/api/src/core/services/config/config.service.ts) ==="
sed -n '1,200p' apps/api/src/core/services/config/config.service.ts || true

echo
echo "=== Instances of ConfigService being created ==="
rg -n "new ConfigService" -n apps/api/src || true

Length of output: 1118


Type assertion in ConfigService is intentional and necessary
TypeScript currently can’t infer the precise intersection type resulting from spreading options.config and the result of envSchema.parse. The as C & z.infer<E> assertion restores your intended static type, and the call to envSchema.parse() ensures runtime validation of all environment‐derived values. If you need runtime checks for options.config, you can layer a Zod schema around it or validate it before passing it in, but no changes are required here.

apps/api/src/chain/services/chain-config/chain-config.service.ts (1)

7-7: LGTM! Clean simplification of generic parameters.

The removal of the second generic parameter unknown is a good simplification that leverages the new default parameter in the base ConfigService class. This maintains type safety while reducing boilerplate.

apps/api/src/auth/services/auth-config/auth-config.service.ts (1)

7-7: LGTM! Consistent with the refactoring pattern.

The simplification matches the pattern established in other config services, correctly utilizing the new default generic parameter while maintaining type safety.

apps/api/src/core/services/core-config/core-config.service.ts (1)

7-7: LGTM! Completes the consistent refactoring pattern.

This change aligns with the other config service simplifications, correctly leveraging the default generic parameter introduced in the base ConfigService class.

apps/api/src/caching/helpers.ts (1)

46-47: LGTM! Good refactoring for clarity.

The logic simplification effectively combines the null check and expiration check into a single, more readable condition. The behavior remains unchanged while improving code clarity.

apps/api/src/services/db/userDataService.ts (1)

93-93: LGTM! Good explicit typing.

Adding explicit UserSetting | null typing improves code clarity and ensures proper null handling throughout the function.

apps/api/src/core/services/error/error.service.ts (1)

8-8: Excellent type safety improvement!

The updated return type Promise<T | undefined> accurately reflects that the method returns undefined when an error is caught and handled. This makes the type signature consistent with the actual runtime behavior.

apps/api/src/core/services/open-api-hono-handler/open-api-hono-handler.ts (1)

7-7: Import addition looks good.

Adding AppContext to the imports is appropriate for the type casting used below.

apps/api/src/services/external/templatesCollector.ts (9)

13-13: Good type safety improvement for task tracking.

Allowing null values in the generatingTasks dictionary accurately reflects the cleanup logic where tasks are set to null after completion (line 79).


15-15: Type expansion for GitHub rate limit tracking.

Adding undefined to the type correctly handles cases where the rate limit header might not be present in API responses.


159-159: Improved API parameter handling.

Changing from null to empty string "" is more appropriate for the GitHub API path parameter, which expects a string value for the repository root.


361-361: Explicit type casting improves clarity.

Adding the type assertion as GithubDirectoryItem[] makes the expected type explicit and improves code readability.


375-375: Safe null handling with optional chaining.

The optional chaining readme?.toLowerCase() prevents potential runtime errors when readme is null or undefined.


389-390: Consistent fallback handling for template properties.

Adding fallback empty strings for logoUrl and summary ensures these required properties are always strings, preventing potential undefined values from causing issues downstream.

Also applies to: 407-407, 411-411, 478-479, 497-497


402-403: Improved boolean and optional property handling.

The explicit boolean conversion !!deploy and conditional assignment guide || undefined provide clearer intent and consistent type handling.

Also applies to: 486-487


419-419: Explicit error typing for better access.

Adding err: any enables safe access to error properties like err.message while maintaining TypeScript compatibility.

Also applies to: 505-505


425-425: Clear filtering with explicit truthiness check.

Using filter(x => !!x) is more explicit than relying on implicit truthiness, making the filtering intent clearer.

Also applies to: 511-511

apps/api/src/services/external/templateReposService.ts (1)

6-20: Excellent refactoring for better error handling and clarity!

The changes provide several improvements:

  1. Early validation: GitHub PAT is checked upfront with a clear error message
  2. Explicit dependencies: The PAT is passed as a parameter rather than accessed via closure
  3. Better error locality: Failures happen at the function entry point rather than deep in the async operation

This aligns well with the broader type safety improvements across the codebase.

apps/api/src/lib/drizzle-ability/drizzle-ability.ts (1)

44-46: LGTM! Good type safety improvement.

The widened parameter type to SQL | undefined allows for more flexible usage while maintaining correct handling of undefined values. The implementation correctly returns the original where clause when abilityClause is falsy.

apps/api/src/services/db/deploymentService.ts (2)

57-59: LGTM! Excellent null safety improvement.

The optional chaining (?.) prevents potential runtime errors when bidId or order properties are undefined or null, which is crucial when dealing with decoded protobuf messages that may have optional fields.


78-79: LGTM! Clean refactor of operator assignment.

The dynamic operator assignment (Op.is for "active", Op.ne for "closed") standardizes the Sequelize filter syntax and improves code readability while maintaining the same functionality.

Also applies to: 93-94

apps/api/src/services/db/providerStatusService.ts (1)

28-46: LGTM! Essential numeric safety improvements.

The || 0 fallback defaults prevent NaN or undefined accumulation errors when provider snapshot resource fields are missing or falsy. This defensive coding pattern ensures robust numeric calculations and aligns perfectly with the strict types migration objective.

apps/api/src/services/db/networkRevenueService.ts (3)

95-131: LGTM! Consistent numeric safety pattern.

The || 0 fallback defaults for revenue fields prevent undefined/null accumulation errors during the revenue calculations. This defensive coding approach ensures reliable numeric operations throughout the revenue aggregation logic.


198-200: LGTM! Proper null handling for database fields.

The fallback defaults for totalUAktSpent, totalUUsdcSpent, and aktPrice prevent runtime errors when these optional database fields are null or undefined, ensuring safe numeric operations downstream.


203-203: LGTM! Improved type safety with explicit typing.

The explicit type annotation for the relativeStats array in the reducer enhances type safety and makes the return type clear, which aligns well with the strict types migration objective.

apps/api/src/services/db/blocksService.ts (3)

72-76: Excellent defensive programming improvements!

The addition of null safety checks for tx.messages and message.amount prevents potential runtime errors. The fallback to an empty array and "0" string ensures safe iteration and parsing.


95-97: Good explicit error handling for missing data.

Adding an explicit error when the earlier block is not found prevents silent failures and provides clear feedback about calculation issues.


113-113: Consistent null safety for latest block checks.

Both functions now properly handle the case where no blocks are found, providing clear error messages instead of proceeding with undefined data.

Also applies to: 132-132

apps/api/src/services/db/transactionsService.ts (4)

38-42: Consistent null safety for messages array and amount parsing.

Good defensive programming by safely handling potentially null tx.messages and providing a "0" fallback for amount parsing.


83-84: Improved null handling for address references and error logging.

The null safety for tx.addressReferences and explicit null handling for the error field improve robustness and clarity.


93-93: Explicit null fallback for relatedDeploymentId.

Good practice to explicitly handle potentially missing relatedDeploymentId with a null fallback.


143-144: Comprehensive null safety for address references throughout the function.

All instances of tx.addressReferences access are now protected with null safety checks, ensuring consistent defensive programming.

Also applies to: 148-148

apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts (4)

51-53: Good migration from lodash to native JavaScript.

Using array destructuring instead of lodash first() is more idiomatic and type-safe.


67-72: Excellent explicit null safety checks.

Adding early returns for falsy userId and missing userWallet improves type safety and prevents potential runtime errors.


88-94: Improved object transformation without lodash.

Using object spreading instead of omit is more explicit and eliminates the lodash dependency while maintaining the same functionality.


76-76:

Details

✅ Verification successful

Verify the necessity of explicit type casting.

The explicit casting to string and string[] suggests potential type system gaps. Consider if the method signature could be made more type-safe to avoid manual casting.


🏁 Script executed:

#!/bin/bash
# Check if there are type definitions that could eliminate the need for casting
ast-grep --pattern 'findByUserId($PARAM) {
  $$$
}'

Length of output: 53


🏁 Script executed:

#!/bin/bash
# Locate the findByUserId method and its signature to verify parameter types
rg -n "findByUserId" apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts
rg -A3 "findByUserId" apps/api/src/billing/repositories/user-wallet/user-wallet.repository.ts

Length of output: 623


🏁 Script executed:

#!/bin/bash
# Find type/interface definition for UserWalletOutput to inspect the userId property type
rg -nE "export (type|interface) UserWalletOutput" .
rg -A5E "export (type|interface) UserWalletOutput" .

Length of output: 267


No change needed: explicit type assertions are required
TypeScript’s built-in Array.isArray() guard narrows userId to any[], not string[], so the casts to string / string[] are necessary to satisfy the signatures of eq and inArray. If you’d like to avoid these assertions, you could introduce a custom type-guard (x is string[]), but the current implementation is both correct and clear.

apps/api/src/services/external/apiNodeService.ts (4)

134-138: Comprehensive optional chaining for validator data access.

Excellent defensive programming by using optional chaining for all validator property access. This prevents runtime errors when validator objects might be undefined.

Also applies to: 154-158, 174-178, 180-184


146-146: Safe array access with proper fallbacks.

Good practice using optional chaining combined with fallback values for array find() operations and amount parsing.

Also applies to: 167-167


325-329: Robust handling of proposal tally data.

The optional chaining for final_tally_result properties with "0" fallbacks ensures safe numeric parsing even when tally data is missing.


428-444: Thorough defensive programming for deployment lease data.

The comprehensive use of optional chaining for provider properties and deeply nested group/resource data is excellent. The fallback values (0) ensure mathematical operations remain safe even when data is missing.

apps/api/src/core/repositories/base.repository.ts (8)

52-54: LGTM: Improved parameter type safety

The parameter type change from SQL to SQL | undefined better reflects the actual usage and improves type safety by explicitly handling undefined values.


58-63: LGTM: Enhanced type safety and native JavaScript usage

The explicit Promise<Output> return type and replacement of lodash first() with array destructuring improves type clarity and removes external dependencies. The implementation correctly handles the array destructuring pattern.


65-67: LGTM: Accurate return type reflecting potential undefined result

Adding undefined to the return type accurately represents that findById may not find a matching record, improving type safety for consumers of this method.


69-75: LGTM: Consistent null safety pattern

The return type update and method implementation maintain consistency with other find methods while properly handling potential undefined results.


77-87: LGTM: Comprehensive type improvements with proper null handling

The explicit typing and null checking (if (!items) return undefined;) ensure robust handling of transaction scenarios where the transaction manager might not be available. The array indexing items[0] is safe after the null check.


157-159: LGTM: Consistent array destructuring pattern

The replacement of lodash first() with array destructuring maintains consistency with other method updates in this file.


177-179: LGTM: Consistent pattern application

Same beneficial change as other methods - replacing lodash with native JavaScript array destructuring.


186-193: LGTM: Improved null safety and explicit handling

The early return for falsy queries and explicit typing enhance the method's robustness. The parameter type change to include undefined aligns with the actual usage patterns.

apps/api/src/services/db/statsService.ts (7)

18-18: LGTM: Excellent utility function for null safety

The numberOrZero utility function provides a clean, type-safe way to handle potentially undefined or null numeric values. The type guard approach is more robust than simple truthy checking.


27-29: LGTM: Proper error handling for data dependency

Adding an explicit error throw when no block stats are found prevents silent failures and makes the data dependency requirement clear. This is a good defensive programming practice.


53-80: LGTM: Comprehensive null safety improvements

The systematic application of numberOrZero() and optional chaining (?.) throughout the calculations ensures robust handling of potentially missing data. This prevents runtime errors from undefined/null arithmetic operations.


125-157: LGTM: Consistent null safety pattern in getter functions

The application of numberOrZero() to all numeric field accesses in the getter functions ensures consistent behavior across different data types. The variable type change from nullable to non-nullable reflects the actual usage after proper initialization.


174-174: LGTM: Safe property access with non-null assertion

The non-null assertion (!) is appropriate here since the query includes required: true for the lastBlock association, guaranteeing its presence.


183-183: LGTM: Explicit type annotation for reducer

Adding explicit typing to the reducer accumulator improves code clarity and helps TypeScript provide better type checking.


198-199: LGTM: Final safety layer for dashboard data

Applying numberOrZero() to the dashboard data extraction provides a final safety layer, ensuring the returned values are always numbers even if the dashboard data has unexpected structure.

apps/api/src/user/repositories/user/user.repository.ts (5)

28-31: LGTM: Enhanced type safety and native JavaScript usage

The explicit typing of input parameter and return type, combined with array destructuring instead of lodash first(), improves type safety and reduces external dependencies. The implementation correctly handles the repository pattern.


33-35: LGTM: Accurate return type for find operation

Adding undefined to the return type correctly represents that findById may not find a matching user, improving type safety for method consumers.


37-39: LGTM: Type safety improvements with appropriate assertion

The return type update improves type safety. The non-null assertion on userId! is reasonable since this method would typically be called with a valid userId parameter.


45-45: LGTM: Explicit return type annotation

Adding the explicit Promise<void> return type improves method signature clarity and type safety.


72-72: LGTM: Modern array method usage

Replacing lodash last() with the native Array.prototype.at(-1) method removes external dependencies while maintaining the same functionality. The optional chaining ensures safe access.

@stalniy stalniy force-pushed the refactor/strict-types-2 branch 2 times, most recently from b15caf0 to 12b0b0d Compare May 26, 2025 01:58
ygrishajev
ygrishajev previously approved these changes May 26, 2025
@stalniy stalniy force-pushed the refactor/strict-types-2 branch from 12b0b0d to 8b1c910 Compare May 26, 2025 08:55
@stalniy stalniy enabled auto-merge (squash) May 26, 2025 08:55
@stalniy stalniy closed this May 26, 2025
auto-merge was automatically disabled May 26, 2025 09:03

Pull request was closed

@stalniy stalniy reopened this May 26, 2025
@stalniy stalniy force-pushed the refactor/strict-types-2 branch from 8b1c910 to 131dbe0 Compare May 26, 2025 16:21
@stalniy stalniy enabled auto-merge (squash) May 26, 2025 16:21
@stalniy stalniy force-pushed the refactor/strict-types-2 branch from 131dbe0 to b25c64b Compare May 26, 2025 16:29
@codecov
Copy link

codecov bot commented May 26, 2025

Codecov Report

Attention: Patch coverage is 44.02174% with 103 lines in your changes missing coverage. Please review.

Project coverage is 35.70%. Comparing base (78b5e94) to head (2e15e68).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
apps/api/src/services/db/networkRevenueService.ts 0.00% 20 Missing ⚠️
apps/api/src/services/external/apiNodeService.ts 0.00% 20 Missing ⚠️
...ps/api/src/services/external/templatesCollector.ts 10.52% 17 Missing ⚠️
apps/api/src/services/db/providerStatusService.ts 0.00% 15 Missing ⚠️
apps/api/src/services/db/statsService.ts 72.41% 8 Missing ⚠️
apps/api/src/services/db/deploymentService.ts 0.00% 7 Missing ⚠️
apps/api/src/services/db/blocksService.ts 0.00% 3 Missing and 3 partials ⚠️
apps/api/src/services/db/transactionsService.ts 37.50% 5 Missing ⚠️
.../api/src/services/external/templateReposService.ts 25.00% 2 Missing and 1 partial ⚠️
.../api/src/user/repositories/user/user.repository.ts 75.00% 2 Missing ⚠️

❌ Your patch status has failed because the patch coverage (44.02%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1362      +/-   ##
==========================================
+ Coverage   35.63%   35.70%   +0.07%     
==========================================
  Files         808      808              
  Lines       19608    19670      +62     
  Branches     3619     3717      +98     
==========================================
+ Hits         6988     7024      +36     
- Misses      11889    11912      +23     
- Partials      731      734       +3     
Flag Coverage Δ *Carryforward flag
api 65.53% <44.02%> (-0.09%) ⬇️
deploy-web 14.76% <ø> (ø) Carriedforward from 78b5e94
notifications 88.67% <ø> (ø) Carriedforward from 78b5e94
provider-proxy 80.09% <ø> (ø) Carriedforward from 78b5e94

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
...c/auth/services/auth-config/auth-config.service.ts 100.00% <100.00%> (ø)
...es/checkout-session/checkout-session.repository.ts 50.00% <ø> (ø)
...repositories/user-wallet/user-wallet.repository.ts 93.47% <100.00%> (+0.45%) ⬆️
apps/api/src/caching/helpers.ts 97.50% <100.00%> (ø)
...hain/services/chain-config/chain-config.service.ts 100.00% <100.00%> (ø)
apps/api/src/core/repositories/base.repository.ts 80.89% <100.00%> (+2.14%) ⬆️
...pps/api/src/core/services/config/config.service.ts 100.00% <100.00%> (ø)
...c/core/services/core-config/core-config.service.ts 100.00% <100.00%> (ø)
apps/api/src/core/services/error/error.service.ts 100.00% <100.00%> (ø)
...ces/open-api-hono-handler/open-api-hono-handler.ts 100.00% <100.00%> (ø)
... and 14 more

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@stalniy stalniy disabled auto-merge May 26, 2025 16:55
@stalniy stalniy merged commit 52daada into main May 26, 2025
26 of 27 checks passed
@stalniy stalniy deleted the refactor/strict-types-2 branch May 26, 2025 16:55
@coderabbitai coderabbitai bot mentioned this pull request Jan 29, 2026
9 tasks
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

Comments