Skip to content

refactor: update return types and error handling across various use cases#1807

Merged
Artuomka merged 2 commits into
mainfrom
backend_typescript_improvements
May 28, 2026
Merged

refactor: update return types and error handling across various use cases#1807
Artuomka merged 2 commits into
mainfrom
backend_typescript_improvements

Conversation

@Artuomka
Copy link
Copy Markdown
Collaborator

@Artuomka Artuomka commented May 28, 2026

  • Updated findTableSettingsOrReturnEmpty to return a more specific type.
  • Changed middleware configuration methods to return void instead of any.
  • Enhanced error handling in multiple use cases by utilizing getErrorMessage for consistent error messages.
  • Improved type safety in helper functions and entities.
  • Added type definitions for Express request to include decoded Cognito data.
  • Adjusted TypeScript configuration to extend from tsconfig.src.json.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error message handling across the application for more consistent and informative user-facing error text.
    • Improved logger formatting to handle various error types more robustly.
  • Refactor

    • Strengthened TypeScript type safety throughout authorization middleware and core utilities.
    • Standardized error extraction patterns across the codebase for consistency.

Review Change Stack

Artuomka added 2 commits May 28, 2026 08:46
…ases

- Updated `findTableSettingsOrReturnEmpty` to return a more specific type.
- Changed middleware configuration methods to return `void` instead of `any`.
- Enhanced error handling in multiple use cases by utilizing `getErrorMessage` for consistent error messages.
- Improved type safety in helper functions and entities.
- Added type definitions for Express request to include decoded Cognito data.
- Adjusted TypeScript configuration to extend from `tsconfig.src.json`.
Copilot AI review requested due to automatic review settings May 28, 2026 09:14
@Artuomka Artuomka enabled auto-merge May 28, 2026 09:14
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR systematically improves TypeScript type safety across the codebase by replacing loose any typing with specific types, introducing a centralized error-message extraction helper, standardizing Express middleware signatures, and aligning NestJS module contracts. The changes span authorization middleware, request interfaces, error handling, logging, helpers, and module signatures.

Changes

Type Safety and Error Handling Standardization

Layer / File(s) Summary
Express middleware NextFunction typing
backend/src/authorization/{auth-with-api,auth,basic-auth,non-scoped-auth,saas-auth,temporary-auth}.middleware.ts
Updates 7 middleware files to use Express's NextFunction type instead of inline generic callback signatures for the next parameter, aligning with Express typing conventions.
Request interface narrowing and type augmentation
backend/src/authorization/cognito-decoded.interface.ts, backend/src/types/express.d.ts
Narrows IRequestWithCognitoInfo query/params types from any to Record<string, string | undefined> and adds Express module augmentation for optional decoded field on the base Request interface.
Error message extraction standardization
backend/src/entities/**/use-cases/*.ts, backend/src/entities/**/utils/*.ts, backend/src/helpers/*.ts, backend/src/exceptions/all-exceptions.filter.ts
Introduces and applies a centralized getErrorMessage helper across ~40 files, replacing unsafe (err as Error).message casting patterns with consistent, safe error-message extraction in error handlers across use cases, utilities, and exception filters.
Logger and exception handling improvements
backend/src/entities/logging/winston-logger.ts, backend/src/exceptions/all-exceptions.filter.ts
Enhances WinstonLogger with a formatMessage helper to safely normalize log inputs from any to unknown, updates all logger methods to use formatted messages, and improves AllExceptionsFilter with typed exception coercion and safer property access.
Decorator parameter type narrowing
backend/src/decorators/{body-email,gclid,master-password,user-id}.decorator.ts
Updates 5 NestJS parameter decorators to narrow _data parameter from any to unknown, improving type safety for decorator implementations.
Helper function generic typing improvements
backend/src/helpers/{compare-array-elements,enum-to-string,get-property-value-by-descriptor,is-object-empty}.ts, backend/src/helpers/slack/slack-post-message.ts
Improves type safety in helper functions by introducing generics and narrowing parameter types from any to specific types: compareArrayElements uses ReadonlyArray<T>, enumToString constrains to Record<string, string | number>, getPropertyValueByDescriptor returns unknown, and slackPostMessage returns Promise<unknown>.
NestJS module configure return type standardization
backend/src/entities/*/\*.module.ts (~20 files)
Updates ~20 NestJS module configure methods to return void instead of any, aligning with the proper NestModule interface contract for middleware configuration.
Controller method return type refinement
backend/src/entities/{api-key,convention,user}/*
Refines controller return types: ApiKeyController.checkApiKey to Promise<{result: boolean, message: string}>, ConversionController.getConversions to Promise<void>, and UserController methods to Promise<boolean> and Promise<ITokenExp>.
Repository method return type specificity
backend/src/entities/table-settings/common-table-settings/repository/*.ts
Refines ITableSettingsRepository.findTableSettingsOrReturnEmpty return type from Promise<any> to Promise<TableSettingsEntity | Record<string, never>> in both interface and implementation.
Template string value type coercion
backend/src/entities/table/utils/process-found-rows-util.ts
Coerces template substitution values to string via String(...) wrapper for consistent string types in URL/text template generation.
TypeScript build configuration alignment
backend/tsconfig.build.json
Updates build configuration to extend tsconfig.src.json instead of tsconfig.json.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • lyubov-voloshko
  • gugu

Poem

🐰 With NextFunction typed, we've tightened the reins,
No more any lurking in middleware chains!
Errors now safely extracted by helper so kind,
Type-safe logging and classes refined.
A rabbit salutes this cohesive sprint—
where safety and clarity now plainly print! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Check ⚠️ Warning MasterPassword decorator return type mismatch: declares 'string' but returns 'null'; demo-data service error handling swallows errors without throwing. Fix MasterPassword return type to 'string | null' and throw errors in demo-data service instead of silently returning undefined.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately reflects the main objective: refactoring return types and error handling across various use cases, which aligns with the comprehensive changes in middleware configuration, error message extraction, and type safety improvements throughout the codebase.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch backend_typescript_improvements

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.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot requested review from gugu and lyubov-voloshko May 28, 2026 09:15
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors backend TypeScript typing and error-message handling to reduce any usage, centralize caught-error formatting, and align build/type-checking behavior with stricter source settings.

Changes:

  • Replaces many (error as Error).message usages with getErrorMessage(...).
  • Tightens return types, helper signatures, middleware next typing, and request typings.
  • Adds Express request augmentation for Cognito data and updates build config to extend stricter source config.

Reviewed changes

Copilot reviewed 81 out of 82 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
backend/tsconfig.build.json Builds now extend tsconfig.src.json.
backend/src/types/express.d.ts Adds Express Request.decoded augmentation.
backend/src/helpers/validators/is-action-url-host-allowed.ts Uses shared error-message helper.
backend/src/helpers/slack/slack-post-message.ts Narrows Slack return type to unknown.
backend/src/helpers/is-object-empty.ts Narrows helper input type.
backend/src/helpers/get-property-value-by-descriptor.ts Narrows object/value types and handles missing descriptors.
backend/src/helpers/enum-to-string.ts Adds generic enum-like constraint.
backend/src/helpers/compare-array-elements.ts Adds generic readonly array typing.
backend/src/exceptions/all-exceptions.filter.ts Handles unknown exceptions with typed metadata extraction.
backend/src/entities/logging/winston-logger.ts Formats unknown log messages before logging/slack posting.
backend/src/authorization/cognito-decoded.interface.ts Narrows request query/params and documents Cognito request type.
backend/src/authorization/*.middleware.ts Uses Express NextFunction.
backend/src/decorators/*.ts Replaces decorator data any with unknown.
backend/src/entities/**/*.module.ts Changes Nest module configure return types to void.
backend/src/entities/**/*use*.ts Standardizes caught-error message extraction.
backend/src/entities/**/*service.ts Standardizes caught-error message extraction.
backend/src/entities/**/*entity.ts Standardizes JSON parse/stringify error logging.
backend/src/entities/table/utils/process-found-rows-util.ts Coerces descriptor values to strings for template replacement.
backend/src/entities/table-settings/**/repository/* Narrows table-settings repository return type.
backend/src/entities/*/controller.ts Narrows controller method return types.
backend/src/entities/table-schema/**/*.ts Standardizes validation/tooling error messages.
backend/src/entities/connection/**/*.ts Standardizes DDL/diagram error messages.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

return message.stack ?? message.message;
}
try {
return JSON.stringify(message);
}
} catch (err) {
const message = (err as Error).message ?? 'validation error';
const message = getErrorMessage(err) ?? 'validation error';
@Artuomka Artuomka merged commit 6927ca0 into main May 28, 2026
18 of 20 checks passed
@Artuomka Artuomka deleted the backend_typescript_improvements branch May 28, 2026 09:23
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