Skip to content

Conversation

@yamcodes
Copy link
Contributor

@yamcodes yamcodes commented Jun 8, 2025

Description

Misc refactor to Layered Architecture

Closes #168


PR Checklist

  • Read the Developer's Guide in CONTRIBUTING.md
  • Use a concise title to represent the changes introduced in this PR
  • Provide a detailed description of the changes introduced in this PR, and, if necessary, some screenshots
  • Reference an issue or discussion where the feature or changes have been previously discussed
  • Add a failing test that passes with the changes introduced in this PR, or explain why it's not feasible
  • Add documentation for the feature or changes introduced in this PR to the docs; you can run them with bun docs

Summary by CodeRabbit

  • New Features

    • Introduced standardized error handling with a new RealWorldError class and structured error responses.
    • Added utility modules for error formatting, date operations, and validation tasks.
    • Added reusable interface types for API responses, pagination, and common entities.
    • Centralized and expanded constants for pagination and error messages.
  • Refactor

    • Unified and simplified error handling across services, replacing custom error classes with standardized errors and HTTP status codes.
    • Updated import paths throughout the codebase for consistency using a single alias pattern.
    • Reorganized and clarified project structure documentation and code organization.
    • Improved and centralized constants and utility exports for easier access.
  • Bug Fixes

    • Fixed broken Markdown links and standardized code block formatting in documentation.
  • Chores

    • Simplified TypeScript path aliases in configuration.
    • Cleaned up whitespace and improved formatting in all documentation files.
  • Documentation

    • Expanded and clarified project structure, usage guidelines, and added new documentation for utilities and interfaces.

yamcodes added 30 commits April 17, 2025 19:09
…ethods

- Updated article response DTO to encapsulate article details within an 'article' object.
- Refactored articles service methods to improve type handling and ensure consistent article data mapping.
- Removed unused query parameters in article fetching logic for cleaner service calls.
- Enhanced error handling in article creation and update methods to ensure articles are found post-operation.
- Cleaned up comments and organized imports for better code readability.
- Introduced a new mapping function `toFeedResponse` for transforming article data into the feed response format.
- Updated the articles controller to utilize `toFeedResponse` for article data mapping.
- Modified DTO exports to include `article-feed-response.dto` and reorganized existing exports for clarity.
- Changed the author type in the article feed interface to `ProfileFeed` for better alignment with the new response structure.
…handling

- Replaced `articlesPlugin` with `articlesController` in the app module for improved structure.
- Updated article schema imports across various files to maintain consistency.
- Refactored `CommentsRepository` to use a new `CreateCommentDto` type for better clarity and type safety.
- Cleaned up unused imports and comments for enhanced code readability.
- Modified summary descriptions in the articles controller for clarity, changing 'Article Feed' to 'Feed Articles', 'Add Comment to Article' to 'Add Comments to an Article', and 'Get Comments from Article' to 'Get Comments from an Article'.
- Updated the tags plugin summary from 'List Tags' to 'Get Tags' for consistency.
- Adjusted user plugin summaries, changing 'Register' to 'Registeration', 'Login' to 'Authentication', and 'Current User' to 'Get Current User' for improved clarity.
- Moved the article creation endpoint to a new position within the articles controller for improved readability and structure.
- Ensured the endpoint retains its functionality, including user authentication and response formatting.
- Updated the endpoint's summary details to maintain consistency with other routes.
- Replaced `ListArticlesQueryDto` with `ArticleFeedQueryDto` in the articles controller to enhance query handling for the article feed.
- Added a detailed description for the feed articles endpoint, specifying additional query parameters.
- Removed the now obsolete `article-feed-response.dto.ts` file to streamline the DTO structure.
- Updated DTO exports in the index file to reflect the changes.
- Added a detailed description to the 'List Articles' endpoint, outlining the default behavior and available query parameters for filtering results.
- Clarified that authentication is optional and specified the ordering of returned articles.
- Upgraded TypeScript version in package.json from 5.7.2 to ^5.8.3 for enhanced features and compatibility.
- Updated bun.lockb to reflect the changes in package dependencies.
@yamcodes yamcodes mentioned this pull request Jun 11, 2025
4 tasks
yamcodes added 11 commits June 11, 2025 23:31
…arity

- Updated the follower check in ProfilesService to explicitly define the type of the follower parameter, improving type safety and code readability.
… and type consistency

- Refactored createUser and updateUser methods in UsersService to utilize CreateUserInput and UpdateUserInput for better clarity and type safety.
- Enhanced mappers to convert input DTOs to database rows, ensuring consistent handling of user data.
- Updated index.ts to export new interfaces for create and update user operations, improving module accessibility.
- Deleted CreateUserInput and UpdateUserInput interfaces from the user module, streamlining the codebase and eliminating redundancy. This change enhances maintainability and focuses on the current user input handling structure.
…or improved clarity

- Removed duplicate import of ProfileRow in article-row.interface.ts, enhancing code clarity.
- Updated import statements in profiles.repository.ts to maintain consistency and eliminate redundancy, improving overall maintainability.
- Deleted profiles.schema.ts and users.schema.legacy.ts files to eliminate outdated code and streamline the schema structure.
- This change enhances maintainability by removing redundancy and focusing on current schema definitions.
- Eliminated redundant import of ProfileRow in article-row.interface.ts, enhancing code clarity and maintainability.
…clarity

- Updated the error key for invalid password in UsersService to 'user.password' for better specificity and clarity in error handling. This change enhances the readability of error responses during user authentication.
…ame checks

- Added methods to check if the email and username are already taken during user creation and updates, improving error handling and user feedback.
- Updated error messages to provide more specific feedback when email or username conflicts occur, enhancing clarity in user interactions.
…or handling

- Updated the ArticlesRepository to include followedAuthorIds in the FindFilters, allowing for more precise article queries based on user follow relationships.
- Adjusted the ArticlesService to streamline the passing of filters, ensuring clarity and consistency in the article retrieval process.
- Improved conditional checks for tag and favorited filters to only apply when followedAuthorIds are not present, enhancing query efficiency.
- Updated conditional checks in ArticlesRepository to explicitly compare against undefined for followedAuthorIds, author, tag, and favorited filters, enhancing clarity and preventing potential errors in article queries.
- This change improves the robustness of the filtering logic, ensuring that filters are applied correctly based on user input.
- Changed the error status property in RealWorldError from statusCode to status for consistency across error handling.
- Updated AuthService to check for RealWorldError instances instead of using isHttpError, improving clarity in error handling logic.
- Removed the isHttpError utility function as it was no longer needed, streamlining the error utilities.
yamcodes added 6 commits June 13, 2025 21:41
…178)

### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->
- Modified the users schema to allow for default values in bio and image
fields, enhancing data consistency.
- Updated the toNewUserRow and toUpdateUserRow mappers to handle null
values for bio and image, improving input handling and ensuring
compatibility with the updated schema.
---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->

Closes #161 

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Improved API responses to use explicit HTTP status codes for resource
creation (201) and deletion (204) across articles, comments, and user
registration endpoints.

- **Bug Fixes**
- Updated error status codes to use 409 Conflict for slug and user
uniqueness conflicts, and clarified error messages for comment deletion
mismatches.

- **Chores**
- Upgraded dependencies and added a new package for enhanced
functionality.
	- Minor code style improvements for configuration syntax.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->

Make TypeScript stricter (and more useful) by turning on
`noUncheckedIndexedAccess` and fixing the resulting types.

- Updated ArticlesRepository to safely access article counts with
optional chaining and provide a default value of 0.
- Added null checks when inserting and updating articles to ensure
consistent handling of non-existent articles.
- Refactored ArticleFeedRow and IArticleFeed interfaces to replace the
ProfileFeed type with a more detailed author structure and updated
import paths.
- Removed the obsolete ProfileFeed interface to streamline the codebase.

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved error handling for missing or failed database operations in
articles, comments, profiles, and users, ensuring null is returned or
appropriate errors are thrown when expected results are absent.
- Enhanced token validation in authentication to explicitly handle
missing tokens.

- **Refactor**
- Simplified and standardized handling of nullable fields and query
results across articles, comments, profiles, and users.
- Updated several type definitions to allow `bio` and `image` fields to
be `null` or `string` for authors in articles and comments.

- **Chores**
- Enabled stricter TypeScript compiler checks for safer indexed access.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->

Increase data integrity by returning the deleted entity / a boolean for
each deleted entity in the repository layer.

This fixes a data integrity issue we had when the repository would not
tell the service if the entity was actually deleted in some cases.

Closes #137 

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved reliability of article and comment deletion by providing
clear success or failure feedback and explicit error handling if
deletion fails.
- Enhanced unfollow functionality to clearly indicate whether the
unfollow action was successful.

- **Refactor**
- Updated several deletion-related methods to return boolean values,
making their outcomes more transparent to users.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->

Infer rows from schema instead of manually defining them

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Refactor**
- Updated several data type definitions to use new utility types for
improved consistency with database schemas.
- Replaced explicit interfaces with inferred types for articles,
comments, tags, and users.
  - Removed unused or redundant type definitions and exports.

- **Chores**
- Updated dependencies by removing an unused package and reordering
another in the dependency list.

- **Style**
- Simplified and unified type definitions for new and update operations
across multiple modules.

- **Bug Fixes**
- Removed default values for certain user profile fields, ensuring
explicit values are required where necessary.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
### Description

<!-- Provide a comprehensive description here about what your PR aims to
solve. -->

<!-- You may also add additional context -->

Direct use of `Elysia.t` instead of TypeBox whenever possible, for
simplicity

---

### PR Checklist

<!-- Please do not remove this section -->

<!-- Mark each item with an "x" ([ ] becomes [x]) -->

- [x] Read the Developer's Guide in
[CONTRIBUTING.md](https://github.com/agnyz/bedstack/blob/main/CONTRIBUTING.md)
- [x] Use a concise title to represent the changes introduced in this PR
- [x] Provide a detailed description of the changes introduced in this
PR, and, if necessary, some screenshots
- [x] Reference an issue or discussion where the feature or changes have
been previously discussed
- [x] Add a failing test that passes with the changes introduced in this
PR, or explain why it's not feasible
- [x] Add documentation for the feature or changes introduced in this PR
to the docs; you can run them with `bun docs`


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Refactor**
- Migrated all data transfer object (DTO) schemas from the previous
validation library to a new schema validation system, with no changes to
their structure or validation rules.
- Updated type extraction methods for DTOs to align with the new schema
library.
- Enhanced error handling in authentication to provide more structured
and descriptive error messages.

- **Chores**
- Updated dependency versions and configuration for improved consistency
and security.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Copy link
Collaborator

@aruaycodes aruaycodes left a comment

Choose a reason for hiding this comment

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

this is such a cool code. I want to able to write code like this

.onError(({ error, code, set }) => {
set.status = getErrorStatusFromCode(code);
const errorType = 'type' in error ? error.type : 'internal';
// Manually thrown errors
Copy link
Collaborator

Choose a reason for hiding this comment

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

why do we need so many types of errors?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We want to be able to throw an error and not think about its formatting.

We need to follow the RealWorld error handling format:

{
  "errors":{
    "body": [
      "can't be empty"
    ]
  }
}

Reference

So now, in your code, you can do this:

throw new RealWorldError(StatusCodes.UNAUTHORIZED, {
  Authorization: ['is missing'],
});

Instead of this:

throw new Error({
  statusCode: StatusCodes.UNAUTHORIZED,
  errors: {
    "Authorization":['is missing']
}

And more things are "figured out" for you, like remembering the errors field.

Also, some errors are automatically thrown by Elysia, like ValidationError, so this is a way to format them to this structure. There are also NotFoundError which are built in Elysia errors, that we can throw easily:

throw new NotFoundError('article');

Which will output:

{
  "errors":{
    "article": [
      "not found"
    ]
  }
}

This is all thanks to the error handler in app.module.ts.

Base automatically changed from layered-phase5-profiles to layered June 20, 2025 13:44
@yamcodes yamcodes merged commit 6f79af6 into layered Jun 20, 2025
1 check passed
@yamcodes yamcodes deleted the layered-phase6-misc branch June 20, 2025 14:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactor Code changes that do not alter end functionality, or fix a bug.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Layered Phase 6 - misc

3 participants