-
-
Notifications
You must be signed in to change notification settings - Fork 4
feat: new features, reusable schema validator, DTO implementation and update template generation #861
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
base: main
Are you sure you want to change the base?
Conversation
|
🚨 gitStream Monthly Automation Limit Reached 🚨 Your organization has exceeded the number of pull requests allowed for automation with gitStream. To continue automating your PR workflows and unlock additional features, please contact LinearB. |
WalkthroughThis update introduces new DTO schemas, an in-memory product repository, and a refactored product service with improved structure, validation, and documentation. Code generation templates and documentation were enhanced for validation, OpenAPI, and TypeScript typing. Node.js requirements were raised to v20, and supporting configurations, utility exports, and test imports were updated accordingly. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ProductService
participant ProductRepository
Client->>ProductService: POST /api/product (create)
ProductService->>ProductRepository: create(data)
ProductRepository-->>ProductService: Product
ProductService-->>Client: 201 Created (product details)
Client->>ProductService: GET /api/product
ProductService->>ProductRepository: findAll()
ProductRepository-->>ProductService: [Product]
ProductService-->>Client: 200 OK (list of products)
sequenceDiagram
participant ServiceAction
participant ValidationUtils
ServiceAction->>ValidationUtils: validateParams(ctx, schema)
alt Valid
ValidationUtils-->>ServiceAction: Success (params validated)
else Invalid
ValidationUtils-->>ServiceAction: Throws ValidationError
end
Poem
✨ Finishing Touches
🧪 Generate Unit Tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @devalexanderdaza, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a suite of enhancements to the Moleculer TypeScript template, focusing on modernizing the development workflow and improving code quality. It integrates robust validation mechanisms, standardizes API responses and documentation, and provides new tools for efficient code generation, all while updating core dependencies to newer versions.
Highlights
- Node.js Version Upgrade: Updated the Node.js runtime requirement across the project, including GitHub Actions workflows and
deta.json, from v18 to v20 to ensure compatibility with the latest features and security updates. - Comprehensive Documentation Enhancements: Significantly expanded and updated the
README.mdto provide detailed instructions on code generation, validation, and architectural patterns, including examples of generated code, structured JSON responses, and Swagger documentation. Markdown URL syntax was also standardized. - Advanced Code Generation Templates: Improved
hygentemplates for generating new actions and CRUD services. These now automatically includevalidateParamshooks for Zod-based validation, enforce a structured JSON response format (success,message,data), and generate comprehensive Swagger documentation for endpoints, including error handling and response schemas. - New DTO Generation Feature: Introduced a new
hygentemplate (pnpm generate:dto) for creating Data Transfer Objects (DTOs). This feature generates Zod schemas with OpenAPI annotations and automatically produces corresponding Swagger YAML files, promoting type-safe validation and consistent API documentation. - Reusable Schema Validator: Added a new shared utility module (
services/common/validation.utils.ts) that provides a centralizedvalidateParamsfunction. This function leverages Zod to ensure consistent and robust parameter validation across all services, throwingErrors.ValidationErroron failure. - Repository Pattern Implementation Example: Included an
InMemoryProductRepositoryand a genericIRepositoryinterface to demonstrate the repository pattern. This promotes better separation of concerns between business logic and data access, enhancing maintainability and testability. - VS Code Editor Configuration: Added a
.vscode/extensions.jsonfile to recommend thepavittarx.moleculer-snippetsextension, aiming to improve the developer experience for contributors using VS Code.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Caution
Changes requested ❌
Reviewed everything up to e987de5 in 2 minutes and 1 seconds. Click for details.
- Reviewed
2614lines of code in26files - Skipped
2files when reviewing. - Skipped posting
12draft comments. View those below. - Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. package.json:38
- Draft comment:
The 'typecheck' script runs 'generate:sdk' every time. Consider caching or refining this step to avoid unnecessary regeneration during type checking. - Reason this comment was not posted:
Confidence changes required:50%<= threshold50%None
2. public/index.html:24
- Draft comment:
Inline CSS styling is heavy in this template. Consider externalizing styles for better maintainability and separation of concerns. - Reason this comment was not posted:
Confidence changes required:50%<= threshold50%None
3. public/docs/open-api.json:109
- Draft comment:
Typographical/naming issue: The POST endpoint for '/api/product' references the schema 'addCartDTO'. This name seems inconsistent with a product endpoint and might be a copy-paste error. Please verify if it should be renamed (e.g., to 'addProductDTO') for clarity. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% While the name 'addCartDTO' might seem inconsistent at first glance, the actual schema structure matches what's needed for product creation. The fields (name, qty, price, billing) are valid for both cart items and products. The schema is being reused rather than duplicated. This is actually a good practice to avoid schema duplication when the data structure is the same. The schema name could be more generic to reflect its dual use. However, this is a minor naming issue and the schema works correctly as is. While better naming would be nice, the comment is suggesting a change that isn't strictly necessary since the schema is functionally correct and reusable. The comment should be deleted because it's suggesting a change that isn't strictly necessary - the schema works correctly despite its name, and schema reuse is a valid pattern.
4. public/docs/open-api.json:283
- Draft comment:
Typo? The example string 'Iphone' might be intended to be 'iPhone'. Consider revising for consistency. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% While technically "iPhone" is the correct spelling of Apple's product, this is just an example value in API documentation. The spelling doesn't affect functionality, and the current spelling still clearly communicates the intent. The same spelling is used consistently throughout the file in multiple places. Changing it would require changing all instances for consistency. The spelling correction would make the documentation more professional and accurate. Incorrect product name spelling could be seen as unprofessional. However, this is purely cosmetic feedback about an example value that has no functional impact. Per the rules, we should not comment on purely informative or unimportant issues. Delete the comment as it's a purely cosmetic suggestion about example data that doesn't impact functionality.
5. public/docs/open-api.json:344
- Draft comment:
Typo? The example string 'Iphone' might be intended to be 'iPhone'. Consider revising for consistency. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% While technically correct that "iPhone" is the proper spelling of Apple's product, this is just an example value in API documentation. Example values are meant to be illustrative, not prescriptive. The spelling difference doesn't impact the API functionality or understanding. This feels like an overly pedantic comment that doesn't add real value. The spelling correction could improve consistency with official branding. If this is a real product API that deals with actual iPhones, proper spelling could be important. This is clearly just example data in API documentation, not actual product data. The slight misspelling doesn't impact understanding or functionality. Delete the comment as it's an unnecessarily pedantic correction of an example value that doesn't impact API functionality or understanding.
6. services/dtos/product-dto.swagger.yaml:73
- Draft comment:
Typo: The product example value "Iphone" might be a typo. Consider using proper capitalization (e.g., "iPhone") if that is the intended product name. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% While this is technically correct (iPhone is the proper spelling), this is just an example value in a schema definition. Example values are meant to illustrate the data type and structure, not enforce specific product names. The actual spelling of product names would be handled by the actual data, not the schema. This feels like an unnecessary nitpick that doesn't impact functionality. The proper spelling could matter for consistency in documentation. Also, if this is used for generating example requests/responses, having the correct spelling could be important. While consistency is good, this is just example data in a schema definition. The comment doesn't highlight a real technical or functional issue that needs to be fixed. Delete the comment as it's focusing on a trivial spelling issue in example data that doesn't impact functionality or code quality.
7. services/dtos/product-dto.swagger.yaml:117
- Draft comment:
Typo: The product example value "Iphone" appears again. Consider using "iPhone" for consistency and accuracy. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% This is a very minor cosmetic issue in an example field. Examples are meant to be illustrative, not prescriptive. The spelling difference doesn't affect functionality. While technically correct that "iPhone" is Apple's official spelling, this kind of nitpick about example values doesn't warrant a PR comment. The example still clearly communicates its intent. The comment is technically correct about Apple's trademark spelling. Consistency in documentation could be considered important for professionalism. While correct, this is an extremely minor issue about an example value that doesn't affect functionality or understanding. Our rules specifically say not to make purely informative comments or unimportant ones. Delete this comment as it's too minor and doesn't affect functionality. Example values are illustrative only.
8. services/greeter.service.ts:23
- Draft comment:
Typographical concern: The variable name 'getterValidator' appears to be incorrect in the context of a greeter service. Consider renaming it to 'greeterValidator' for improved clarity and consistency. - Reason this comment was not posted:
Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% While the variable name does appear to have a typo, this is a relatively minor issue. The variable is only used in one place for type information, and its name doesn't impact functionality. The suggestion is technically correct but not critically important. According to the rules, we should not make comments that are obvious or unimportant. The typo could potentially cause confusion for future developers. The variable is part of the public API type definition which makes it more significant than a purely internal variable. While the typo is real, it's still a very minor issue that doesn't affect functionality or maintainability in a meaningful way. The variable's scope and usage is limited. Delete the comment as it points out a minor typographical issue that doesn't significantly impact code quality or maintainability.
9. services/greeter.service.ts:122
- Draft comment:
Typographical error: The log message in the welcome action hook says "Validating parameters for hello action". It appears this should reference the welcome action instead. - Reason this comment was not posted:
Marked as duplicate.
10. services/greeter.service.ts:94
11. services/product/product.service.ts:125
- Draft comment:
Typo: The logger message in the 'create' action hook mentions "addToCart" instead of "create". Please update it to accurately reflect the action (e.g., "Validating parameters for create action"). - Reason this comment was not posted:
Marked as duplicate.
12. test/unit/services/product.spec.ts:31
- Draft comment:
Typographical suggestion: Consider replacing 'an ValidationError' with 'a ValidationError' for grammatical correctness. - Reason this comment was not posted:
Comment was on unchanged code.
Workflow ID: wflow_XbsL8J9wn6PKcuQf
You can customize by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces significant enhancements to the Moleculer TypeScript template, including an upgrade to Node.js 20, improved documentation, and new DTO and service generation capabilities with built-in validation and Swagger documentation. The changes are well-structured and add a lot of value for developers using this template. I've identified a few areas for improvement, primarily related to the new code generation templates and TypeScript typings in the new services. These changes will enhance the robustness and maintainability of the generated code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
🧹 Nitpick comments (19)
services/interfaces/repository.interface.ts (1)
2-16: Well-designed repository interface with comprehensive CRUD operations.The interface follows excellent design patterns:
- Proper use of generics for reusability
Omit<T, "id">correctly excludes ID from creation- Appropriate nullable return types
- Comprehensive method coverage for common repository operations
Consider making the aggregate method more type-safe:
- aggregate(pipeline: any[]): Promise<any[]>; + aggregate<R = any>(pipeline: any[]): Promise<R[]>;services/common/validation.utils.ts (2)
12-31: Consider returning validated parameters and adjusting logging level.The validation utility is well-structured but has a few areas for improvement:
- Logging level: Info-level logging for every validation might be too verbose for production environments
- Return value: The function doesn't return the validated parameters, missing an opportunity to provide type-safe, validated data to the caller
- Strict validation: Using
.strict()prevents additional properties, which might be too restrictiveConsider this enhanced implementation:
-export const validateParams = <T extends z.ZodRawShape>( - ctx: Context<unknown, Record<string, unknown>, GenericObject>, - schema: T -): void => { +export const validateParams = <T extends z.ZodRawShape>( + ctx: Context<unknown, Record<string, unknown>, GenericObject>, + schema: T +): z.infer<z.ZodObject<T, "strict">> => { const compiled = z.object(schema).strict(); try { const parsedParams = compiled.parse(ctx.params); - logger.info("Validated parameters: %o", parsedParams); + logger.debug("Validated parameters: %o", parsedParams); + return parsedParams; } catch (err) { if (err instanceof z.ZodError) { throw new Errors.ValidationError( "Parameters validation error!", "VALIDATION_ERROR", err.issues ); } throw err; } };This provides type-safe validated parameters and uses debug-level logging.
16-16: Consider making strict validation configurable.The
.strict()method prevents additional properties, which might be too restrictive for some use cases where additional metadata or context properties are expected.Consider adding an optional parameter to control strict validation:
export const validateParams = <T extends z.ZodRawShape>( ctx: Context<unknown, Record<string, unknown>, GenericObject>, - schema: T + schema: T, + options?: { strict?: boolean } ): void => { - const compiled = z.object(schema).strict(); + const compiled = options?.strict !== false + ? z.object(schema).strict() + : z.object(schema);services/dtos/greeter-dto.swagger.yaml (1)
18-18: Consider removing empty parameters object.The empty
parameters: {}object appears to be unnecessary and could be removed to keep the schema file cleaner.parameters: {} + # parameters: {} - Remove if not needed_templates/service/new/hello.ejs.t (1)
100-106: Fix the logging message and consider enabling validation.The before hook logs "Validating parameters for hello action" but should reference the "welcome action". Also, the validation is commented out - consider providing guidance on when to enable it.
- this.logger.info("Validating parameters for hello action"); + this.logger.info("Validating parameters for welcome action");services/greeter.service.ts (2)
1-1: Use import type for type-only imports.The static analysis tool correctly identifies that some imports are only used as types. This should be fixed for better tree-shaking and build optimization.
-import { type Context, type Service, type ServiceSchema } from "moleculer"; +import type { Context, Service, ServiceSchema } from "moleculer";
122-122: Fix incorrect action name in validation log message.The log message references "hello action" but should reference "welcome action" since this is the welcome action's before hook.
- logger.info("Validating parameters for hello action"); + logger.info("Validating parameters for welcome action");_templates/service/crud/create.ejs.t (1)
86-92: Clarify the validation implementation approach.The validation hook structure is well-designed, but the actual validation call is commented out. Consider either:
- Providing a working example with a sample schema
- Adding documentation about where/how to define the validation schema
- Including a reference to the DTO generation process
hooks: { before(ctx) { this.logger.info('Validating parameters for create<%= h.capitalize(name) %> action'); - // Add your validation schema here - // validateParams(ctx, your<%= h.capitalize(name) %>Schema); + // Example: validateParams(ctx, Create<%= h.capitalize(name) %>Schema); + // Define your schema in services/dtos/<%= name %>.dto.ts + // and import it at the top of this file }, },services/dtos/product.dto.ts (2)
13-33: Consider extracting the billing schema to reduce duplication.The billing object schema is repeated across multiple DTOs. Consider extracting it to a reusable schema to follow DRY principles.
+const billingSchema = z.object({ + address: z.string().optional(), + city: z.string().openapi({ + description: "City of the billing address", + example: "New York", + }), + zip: z.number().openapi({ + description: "ZIP code of the billing address", + example: 10001, + }), + country: z.string().openapi({ + description: "Country of the billing address", + example: "USA", + }), +}).optional(); export const addCartSchema = { name: z .string() .openapi({ description: "Name of the product", example: "Iphone" }), qty: z.number().openapi({ description: "Quantity of the product", example: 1, }), price: z.number().optional().openapi({ description: "Price of the product", example: 1000, }), - billing: z - .object({ - address: z.string().optional(), - city: z.string(), - zip: z.number(), - country: z.string(), - }) - .optional(), + billing: billingSchema, };
65-99: Schema structure looks good but consider consistency.The nested product object in
CreateProductResponseSchemaDTOduplicates much of theProductSchemadefinition. Consider reusing theProductSchemafor consistency.const CreateProductResponseSchemaDTO = z .object({ success: z.boolean().openapi({ description: "Success flag", example: true, }), message: z.string().openapi({ description: "Message", example: "Product created successfully", }), - product: z.object({ - id: z.string().openapi({ - description: "ID of the created product", - example: "12345", - }), - name: z.string().openapi({ - description: "Name of the product", - example: "Iphone", - }), - // ... rest of product fields - }), + product: ProductSchema.extend({ + id: z.string().openapi({ + description: "ID of the created product", + example: "12345", + }), + }), })_templates/dto/new/hello.ejs.t (1)
27-28: Use relative path instead of__dirnamefor better portability.The template uses
__dirnamewhich may not work correctly in all environments, especially when the generated code is moved or executed from different locations.-// Write to same folder with the DTO file -const outputDirectory = __dirname; +// Write to same folder with the DTO file +const outputDirectory = import.meta.dirname || __dirname;services/product/product.service.ts (3)
14-14: Remove unused validator instance.The
orderItemValidatoris created but never used in the service. This creates unnecessary overhead.-const orderItemValidator = new ZodParams(addCartSchema);
121-121: Fix comment language consistency.There's a Spanish comment mixed with English codebase documentation.
- create: { - // Nueva acción como ejemplo + create: { + // New action as example
132-134: Fix inconsistent context typing.The context type declaration doesn't match the Zod schema pattern used elsewhere in the codebase.
async handler( this: ServiceThis, - ctx: Context<typeof addCartSchema> + ctx: Context<typeof orderItemValidator.context> ) {However, since
orderItemValidatorshould be removed, consider using a proper type:async handler( this: ServiceThis, - ctx: Context<typeof addCartSchema> + ctx: Context<{ name: string; qty: number; price?: number; billing?: any }> ) {README.md (1)
160-167: Fix code example formatting.The TypeScript code example has inconsistent indentation and could be improved for readability.
```typescript // Generated validation hook in every action hooks: { before(ctx) { this.logger.info('Validating parameters for [action] action'); - validateParams(ctx, yourSchema); // Automatically included + validateParams(ctx, yourSchema); // Automatically included }, -} +},</blockquote></details> <details> <summary>public/docs/open-api.json (1)</summary><blockquote> `157-162`: **Consider adding array size limits for security.** The static analysis tool suggests adding maximum items for arrays. While not critical, this is a good security practice to prevent potential DoS attacks. ```diff "schema": { "type": "array", + "maxItems": 1000, "items": { "$ref": "#/components/schemas/ProductSchemaDTO" } }services/product/product.repository.ts (3)
2-2: Useimport typefor type-only imports.The static analysis tool correctly identifies that
IRepositoryis only used as a type. Usingimport typeimproves compilation performance and makes the intent clearer.-import { IRepository } from "../interfaces"; +import type { IRepository } from "../interfaces";
4-4: Use English for code comments.The Spanish comment should be in English for consistency with the codebase.
-// Suponiendo que tienes una interfaz para el producto +// Product interface definition
138-138: Move private field declaration to the top of the class.Private fields should be declared at the beginning of the class for better readability and organization.
export class InMemoryProductRepository implements IRepository<Product> { + private products: Map<string, Product> = new Map(); + public async update(Then remove the declaration from line 138.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (27)
.github/workflows/deploy.yml(3 hunks).vscode/extensions.json(1 hunks)README.md(12 hunks)_templates/action/new/hello.ejs.t(3 hunks)_templates/dto/new/hello.ejs.t(1 hunks)_templates/service/crud/create.ejs.t(4 hunks)_templates/service/crud/list.ejs.t(3 hunks)_templates/service/crud/service.ejs.t(4 hunks)_templates/service/new/hello.ejs.t(3 hunks)deta.json(1 hunks)package.json(2 hunks)public/docs/open-api.json(7 hunks)public/index.html(6 hunks)services/common/index.ts(1 hunks)services/common/validation.utils.ts(1 hunks)services/dtos/greeter-dto.swagger.yaml(1 hunks)services/dtos/greeter.dto.ts(1 hunks)services/dtos/index.ts(1 hunks)services/dtos/product-dto.swagger.yaml(1 hunks)services/dtos/product.dto.ts(1 hunks)services/greeter.service.ts(2 hunks)services/interfaces/index.ts(1 hunks)services/interfaces/repository.interface.ts(1 hunks)services/product.service.ts(0 hunks)services/product/product.repository.ts(1 hunks)services/product/product.service.ts(1 hunks)test/unit/services/product.spec.ts(1 hunks)
💤 Files with no reviewable changes (1)
- services/product.service.ts
🧰 Additional context used
🧬 Code Graph Analysis (5)
services/common/validation.utils.ts (1)
logger.ts (1)
logger(4-7)
services/greeter.service.ts (3)
services/dtos/greeter.dto.ts (1)
welcomeSchema(12-17)logger.ts (1)
logger(4-7)services/common/validation.utils.ts (1)
validateParams(12-31)
services/product/product.service.ts (3)
services/dtos/product.dto.ts (1)
addCartSchema(13-33)services/common/validation.utils.ts (1)
validateParams(12-31)services/product/product.repository.ts (1)
InMemoryProductRepository(11-154)
services/interfaces/repository.interface.ts (1)
services/product/product.repository.ts (1)
update(12-23)
services/product/product.repository.ts (1)
services/interfaces/repository.interface.ts (1)
IRepository(2-16)
🪛 Biome (1.9.4)
services/greeter.service.ts
[error] 1-1: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
services/product/product.service.ts
[error] 1-1: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
services/product/product.repository.ts
[error] 2-2: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
🪛 LanguageTool
README.md
[style] ~135-~135: ‘with success’ might be wordy. Consider a shorter alternative.
Context: ...ll endpoints - Structured responses with success/error handling - Authentication and...
(EN_WORDINESS_PREMIUM_WITH_SUCCESS)
[uncategorized] ~180-~180: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...afe Development All templates generate strongly-typed TypeScript code: - **Service interface...
(HYPHENATED_LY_ADVERB_ADJECTIVE)
[uncategorized] ~341-~341: Loose punctuation mark.
Context: ...cripts - pnpm generate:service [name]: Generate a new basic service with valid...
(UNLIKELY_OPENING_PUNCTUATION)
🪛 Checkov (3.2.334)
public/docs/open-api.json
[MEDIUM] 157-162: Ensure that arrays have a maximum number of items
(CKV_OPENAPI_21)
🔇 Additional comments (43)
.vscode/extensions.json (1)
1-6: LGTM! Good developer experience enhancement.The VS Code extension recommendation for
pavittarx.moleculer-snippetsaligns perfectly with the PR's focus on improving the Moleculer TypeScript template development experience.deta.json (1)
4-4: LGTM! Consistent with Node.js upgrade strategy.The runtime update to
nodejs20.xaligns with the overall Node.js version upgrade mentioned in the PR objectives and maintains consistency across deployment environments..github/workflows/deploy.yml (1)
23-23: LGTM! Consistent Node.js version upgrade across CI/CD pipeline.The systematic update to Node.js version 20 across all workflow jobs (lint, typecheck, test, build) ensures consistency with the overall project upgrade strategy and maintains compatibility throughout the deployment pipeline.
Also applies to: 47-47, 71-71
services/common/index.ts (1)
1-1: LGTM! Good module organization with barrel export pattern.The barrel export for validation utilities follows best practices for organizing shared utilities and provides a clean import path for the validation functions introduced in this PR.
services/dtos/index.ts (1)
1-2: Barrel export verification successfulBoth
greeter.dto.tsandproduct.dto.tsexist underservices/dtos/. The barrel export inservices/dtos/index.tsis correct—no further changes needed.services/interfaces/index.ts (1)
1-1: LGTM – Barrel export validated
- Verified that
services/interfaces/repository.interface.tsexists and follows the project’s barrel export pattern.test/unit/services/product.spec.ts (2)
10-39: Test formatting improved with consistent indentation.The test suite properly validates both successful execution and validation error scenarios for the addToCart action. The formatting has been improved with consistent tab indentation.
4-4: Import path verification passedThe file
services/product/product.service.tsexists, and the import intest/unit/services/product.spec.tscorrectly references../../../services/product/product.service. Changes can be approved.public/index.html (3)
1-1: Good HTML5 compliance improvement.Changing from lowercase
<!doctype html>to uppercase<!DOCTYPE html>follows HTML5 standard conventions.
696-696: Updated default welcome name aligns with PR objectives.The change from "dunghd" to "devalexanderdaza" aligns with the updated example values mentioned in the PR objectives and DTO schemas.
114-114: Clean formatting improvements.The removal of trailing commas and formatting adjustments improve code readability without affecting functionality.
Also applies to: 713-713, 749-749, 860-860, 867-867
_templates/service/new/hello.ejs.t (3)
5-7: Good addition of validation imports.The imports for
ZodParamsandvalidateParamsset up the foundation for parameter validation in generated services.
44-57: Comprehensive Swagger documentation enhances API discoverability.The detailed OpenAPI annotations provide clear endpoint documentation including descriptions, tags, parameters, and response schemas. This aligns with the PR objectives for improved documentation.
Also applies to: 71-94
111-114: Enhanced logging improves debugging capability.The addition of parameter logging in the handler provides valuable debugging information.
package.json (3)
33-33: New DTO generation script supports enhanced code generation.The addition of
generate:dtoscript aligns with the PR objectives for improved code generation capabilities.
88-88: Node.js version requirement raised to v20.This change aligns with the PR objectives and ensures compatibility with the latest environment. Ensure all deployment environments support Node.js 20.
41-53: Generate lockfile and re-run security auditWithout a lockfile,
npm auditcannot run. Please create one and then verify for vulnerabilities and breaking changes:npm install --package-lock-only npm audit --audit-level=moderate– Review any advisories and address critical/high issues.
– Double-check changelogs for breaking changes in the updated versions.Applies to dependencies in lines 41–53, 56–84, and 91–95.
services/dtos/product-dto.swagger.yaml (1)
52-145: Well-structured product schemas with comprehensive validation.The new
CreateProductResponseSchemaDTOandProductSchemaDTOdefinitions provide detailed structure for product-related APIs including:
- Proper required field validation
- Nested billing address constraints
- Clear descriptions and examples
- Consistent response format with success/message fields
These schemas align with the PR objectives for improved validation and documentation.
services/greeter.service.ts (2)
2-5: Enhanced validation setup improves type safety.The addition of validation imports and
ZodParamsvalidator provides better type safety and parameter validation capabilities.Also applies to: 23-23
119-126: Excellent integration of validation hooks and enhanced logging.The before hook implementation with
validateParamsand the enhanced handler with parameter logging provide robust validation and debugging capabilities. The typed context usinggetterValidator.contextensures type safety.Also applies to: 131-142
_templates/service/crud/create.ejs.t (3)
6-6: LGTM! Validation utility import added correctly.The import of
validateParamsfrom the common utilities is properly positioned and will enable parameter validation in the action hooks.
17-21: Excellent standardization of response format.The structured response with
successflag and descriptive message provides consistency across the API and improves client-side error handling.
48-75: Outstanding Swagger documentation enhancement.The comprehensive OpenAPI documentation with detailed response schemas, error handling, and proper HTTP status codes significantly improves API usability and developer experience.
_templates/service/crud/service.ejs.t (4)
4-4: Good addition of Service type import.Adding the
Servicetype import enables better TypeScript typing for the service schema definition.
16-21: Excellent TypeScript typing enhancement.The introduction of
ServiceMethodsandServiceThistypes provides better type safety and intellisense support for service methods and lifecycle handlers.
33-33: Proper generic type application.The updated service schema type annotation with
ServiceThisas the second generic parameter correctly applies the enhanced typing.
90-92: Good modernization with async lifecycle methods.Converting the
startedandstoppedlifecycle methods to async functions aligns with modern async/await patterns and allows for future asynchronous operations during service lifecycle events.Also applies to: 97-99
services/dtos/product.dto.ts (2)
1-11: Well-organized imports and Zod extension.The import organization and Zod OpenAPI extension setup is clean and follows best practices.
132-144: Excellent OpenAPI generation setup.The OpenAPI generator configuration and YAML file generation provides automated documentation that stays in sync with the schema definitions.
services/dtos/greeter.dto.ts (4)
1-11: Excellent DTO module structure.The imports and Zod extension setup follow the established pattern and best practices for DTO modules.
12-17: Good validation constraints for username.The username validation with min/max length constraints (4-25 characters) provides reasonable bounds and clear OpenAPI documentation.
22-28: Well-designed schema definitions.Both
WelcomeSchemaandWelcomeResponseSchemaare properly structured with appropriate OpenAPI metadata and examples.
30-40: Automated documentation generation implemented correctly.The OpenAPI generator setup and YAML file generation ensures the documentation stays synchronized with the schema definitions.
_templates/action/new/hello.ejs.t (5)
5-5: Validation utility import added correctly.The import of
validateParamsenables parameter validation consistent with other action templates.
11-15: Excellent dynamic path generation.The change from static
/welcometo dynamic/<%= name %>makes the template more flexible and generates appropriate REST endpoints based on the action name.Also applies to: 57-57
33-52: Outstanding Swagger documentation enhancement.The comprehensive OpenAPI documentation with structured response schemas and error handling significantly improves API usability and developer experience.
63-69: Consistent validation hook pattern.The validation hook implementation follows the same pattern as other templates, providing consistency across generated actions.
81-89: Proper structured response implementation.The return type annotation and structured response object with
messageandsuccessfields provide consistency across the API and improve type safety.public/docs/open-api.json (2)
98-167: Excellent API design with comprehensive documentation.The new product endpoints follow REST conventions well with proper HTTP methods, comprehensive error handling (422, 500), and detailed schema references. The documentation includes all necessary response codes and content types.
226-230: No inconsistency in billing schema.Both the OpenAPI spec (
public/docs/open-api.json) and theaddCartSchemaDTO (services/dtos/product.dto.ts) markaddressas optional and require onlycity,zip, andcountry. You can safely ignore this review comment.Likely an incorrect or invalid review comment.
services/product/product.repository.ts (3)
101-127: LGTM: Well-implemented aggregation pipeline.The aggregation method correctly implements MongoDB-like pipeline stages for
$match,$sort, and$limit. The implementation properly chains operations and handles edge cases.
129-136: LGTM: Efficient filter matching implementation.The
matchesFilterhelper method correctly implements partial object matching using type-safe key access.
88-99: Clarify ID consistency in findOneAndReplaceThe current implementation in services/product/product.repository.ts (lines 88–99) replaces the map value but retains the original key—even if
replacement.iddiffers—leading to a potential mismatch between key and product ID. We should decide on the intended behavior:
- Option A: Enforce original ID
Forcereplacement.id = idso the key always matches the product’s ID.if (this.matchesFilter(product, filter)) { replacement.id = id; this.products.set(id, replacement); return replacement; }- Option B: Re-key by new ID
Remove the old entry and insert underreplacement.id.if (this.matchesFilter(product, filter)) { this.products.delete(id); this.products.set(replacement.id, replacement); return replacement; }Please confirm which approach aligns with our domain rules or update the method to enforce the chosen strategy.
change min length from 4 to 6 Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
|
There was a problem hiding this 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
♻️ Duplicate comments (1)
services/greeter.service.ts (1)
122-122: Fix misleading log message.The log message incorrectly refers to "hello action" when this is the validation hook for the "welcome" action.
- logger.info("Validating parameters for hello action"); + logger.info("Validating parameters for welcome action");
🧹 Nitpick comments (1)
services/greeter.service.ts (1)
1-1: Useimport typefor type-only imports.The imported types from moleculer are only used for type annotations and should use
import typefor better tree-shaking.-import { type Context, type Service, type ServiceSchema } from "moleculer"; +import type { Context, Service, ServiceSchema } from "moleculer";
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
services/greeter.service.ts(2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
services/greeter.service.ts
[error] 1-1: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
🔇 Additional comments (3)
services/greeter.service.ts (3)
131-142: LGTM! Well-implemented handler with proper typing and validation.The handler correctly uses the typed context from the validator, includes useful logging, and has clean parameter extraction after validation.
23-24: Excellent validation integration with proper separation of concerns.The validation setup properly creates a typed validator instance and uses before hooks to enforce parameter validation before the handler executes. This maintains clean separation between validation logic and business logic.
Also applies to: 119-126
25-42: Comprehensive and well-structured API documentation.The Swagger documentation and JSDoc comments are thorough, covering endpoints, parameters, responses, and error cases. This will greatly improve API usability and developer experience.
Also applies to: 63-113
|
Thanks @devalexanderdaza for the great work on this PR. Could you review the AI bot reviews and resolve them? I believe there are valid. |
Changed "addToCart" to "create" text Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
…t creation logic using randomUUID from node:crypto
There was a problem hiding this 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
♻️ Duplicate comments (1)
README.md (1)
4-4: Minor inconsistency in Node.js version badge.The badge shows ">= 20.x.x" while the text shows ">= 20.0.0". For consistency, consider updating the badge to match the specific version requirement.
- +
🧹 Nitpick comments (2)
services/product/product.repository.ts (1)
1-2: Address the import type suggestion for better tree-shaking.The static analysis correctly identifies that
IRepositoryis only used as a type. Consider usingimport typefor better compilation optimization.-import { IRepository } from "../interfaces"; +import type { IRepository } from "../interfaces";services/greeter.service.ts (1)
1-1: Use import type for better compilation optimization.The static analysis correctly identifies that these imports are only used as types.
-import { type Context, type Service, type ServiceSchema } from "moleculer"; +import type { Context, Service, ServiceSchema } from "moleculer";
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (8)
README.md(12 hunks)_templates/dto/new/hello.ejs.t(1 hunks)_templates/service/crud/list.ejs.t(3 hunks)package.json(2 hunks)services/greeter.service.ts(2 hunks)services/interfaces/repository.interface.ts(1 hunks)services/product/product.repository.ts(1 hunks)services/product/product.service.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- _templates/dto/new/hello.ejs.t
- services/product/product.service.ts
- services/interfaces/repository.interface.ts
- package.json
🧰 Additional context used
🧬 Code Graph Analysis (2)
services/greeter.service.ts (3)
services/dtos/greeter.dto.ts (1)
welcomeSchema(12-17)logger.ts (1)
logger(4-7)services/common/validation.utils.ts (1)
validateParams(12-31)
services/product/product.repository.ts (1)
services/interfaces/repository.interface.ts (1)
IRepository(5-19)
🪛 LanguageTool
README.md
[style] ~135-~135: ‘with success’ might be wordy. Consider a shorter alternative.
Context: ...ll endpoints - Structured responses with success/error handling - Authentication and...
(EN_WORDINESS_PREMIUM_WITH_SUCCESS)
[uncategorized] ~180-~180: Although a hyphen is possible, it is not necessary in a compound modifier in which the first word is an adverb that ends in ‘ly’.
Context: ...afe Development All templates generate strongly-typed TypeScript code: - **Service interface...
(HYPHENATED_LY_ADVERB_ADJECTIVE)
[uncategorized] ~341-~341: Loose punctuation mark.
Context: ...cripts - pnpm generate:service [name]: Generate a new basic service with valid...
(UNLIKELY_OPENING_PUNCTUATION)
🪛 Biome (1.9.4)
services/greeter.service.ts
[error] 1-1: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
services/product/product.repository.ts
[error] 2-2: All these imports are only used as types.
Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.
(lint/style/useImportType)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: gitStream.cm
- GitHub Check: gitStream.cm
- GitHub Check: gitStream.cm
- GitHub Check: gitStream.cm
- GitHub Check: gitStream.cm
🔇 Additional comments (11)
services/product/product.repository.ts (2)
148-153: Excellent fix for secure ID generation!The implementation now uses
crypto.randomUUID()instead of the previous weakMath.random()approach, which addresses the security and collision concerns from the previous review.
11-154: Well-implemented repository pattern with comprehensive operations.The repository implementation follows good architectural patterns:
- Implements the generic
IRepository<Product>interface consistently- Provides all standard CRUD operations plus utility methods
- Includes advanced operations like
findOneAndUpdate,aggregatewith pipeline support- Uses async/await consistently throughout
- Proper error handling and type safety
The implementation is production-ready and follows the repository pattern effectively.
services/greeter.service.ts (3)
2-5: Excellent integration of validation utilities and DTO schemas.The new imports properly integrate the shared validation infrastructure:
ZodParamsfor typed context validation- Shared
loggerfor consistent loggingvalidateParamsutility for standardized validation- DTO schemas for type safety
This follows the architectural patterns outlined in the PR objectives.
119-126: Well-implemented validation hooks with proper logging.The
beforehook implementation follows best practices:
- Logs validation intent for debugging
- Uses the shared
validateParamsutility- Ensures validation occurs before handler execution
- Consistent with other services in the codebase
131-143: Strong typing and comprehensive parameter handling.The handler implementation demonstrates excellent practices:
- Uses typed context from
getterValidatorfor type safety- Includes parameter logging for debugging
- Clean parameter extraction and response generation
- Follows the structured response patterns
_templates/service/crud/list.ejs.t (3)
9-27: Excellent validation schema implementation addresses previous concerns.The new
listParamsSchemaproperly addresses the previous review comments about missing validation:
- ✅ Implements actual validation logic (previously commented out)
- ✅ Validates pagination parameters with proper constraints
- ✅ Uses Zod transformations for type conversion and validation
- ✅ Enforces sensible limits (page ≥ 1, limit 1-100)
- ✅ Provides clear error messages for invalid inputs
This is a significant improvement over the previous commented-out placeholder.
32-46: Well-structured response format with proper typing.The handler implementation follows excellent patterns:
- Uses strongly-typed context from Zod schema inference
- Returns structured JSON response with
success,data, andpaginationfields- Consistent with the architectural patterns described in the README
- Proper separation of concerns with clean parameter extraction
104-109: Proper validation hook implementation with shared utilities.The validation hook correctly integrates the shared validation infrastructure:
- Uses the
validateParamsutility for consistency across services- Includes logging for debugging and monitoring
- Validates before handler execution
- Follows the same pattern as other services in the codebase
README.md (3)
39-42: Excellent documentation of enhanced features.The new feature descriptions clearly highlight the key improvements:
- Enhanced validation with shared Zod schemas
- Comprehensive Swagger documentation with proper error handling
- Strong TypeScript typing throughout
- Structured JSON responses for consistency
These align perfectly with the codebase improvements and provide clear value propositions.
79-89: Comprehensive code generation documentation.The new "Code Generation" section excellently documents the modern best practices built into all templates:
- Automatic validation with shared utilities
- Complete Swagger documentation
- Strong TypeScript typing
- Structured responses and logging
This provides clear guidance for developers using the templates.
153-272: Outstanding architectural documentation and examples.The enhanced documentation provides excellent coverage of:
- Validation utilities with practical examples
- Structured response formats with JSON examples
- Repository pattern implementation details
- Clear service organization structure
This comprehensive documentation will significantly help developers understand and implement the architectural patterns correctly.
|
Hi @jellydn I fix all suggested changes from AI reviewers. Please check new changes, and not dude on share with me you thinks. :) |
|
@devalexanderdaza Could you fix the failed actions for linter and typecheck? Thanks. |
…-4e29-82cf-bd1be81ff7db [WIP] Corrección automática de formateo y lint según pre-commit hooks
|
🚨 gitStream Monthly Automation Limit Reached 🚨 Your organization has exceeded the number of pull requests allowed for automation with gitStream. To continue automating your PR workflows and unlock additional features, please contact LinearB. |
WHAT
This pull request introduces several updates to enhance compatibility, improve documentation, and add new features to the Moleculer TypeScript template. Key changes include upgrading the Node.js version, enriching the README with detailed instructions and best practices, and improving code generation templates with validation hooks, structured responses, and Swagger documentation.
Workflow Updates:
18to20in the GitHub Actions workflow configuration (.github/workflows/deploy.yml). [1] [2] [3]Documentation Enhancements:
>= 20.0.0) and added extensive sections on code generation, validation, and architecture patterns. This includes detailed examples of generated code, structured JSON responses, and Swagger documentation. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]Code Generation Improvements:
validateParams. [1] [2] [3] [4]successandmessagefields. [1] [2] [3]DTO Generation:
Editor Configuration:
.vscode/extensions.json) to suggest thepavittarx.moleculer-snippetsextension for developers.Important
Enhances Moleculer TypeScript template with Node.js 20 support, improved documentation, and new DTO and service templates with validation and Swagger documentation.
18to20in.github/workflows/deploy.ymlanddeta.json.README.mdto reflect Node.js>= 20.0.0requirement and added sections on code generation and architecture patterns.README.mdto use angle bracket syntax._templates/action/new/hello.ejs.t,_templates/service/crud/create.ejs.t, and_templates/service/crud/list.ejs.t._templates/dto/new/hello.ejs.twith Zod schemas and OpenAPI documentation.services/dtos/greeter.dto.tsandservices/dtos/product.dto.tsfor DTO definitions.validateParamsfunction inservices/common/validation.utils.tsfor parameter validation using Zod.services/greeter.service.tsandservices/product/product.service.tsto use new DTOs and validation.services/product/product.repository.tsfor product data management..vscode/extensions.json.package.jsondependencies and scripts for new features.This description was created by
for e987de5. You can customize this summary. It will automatically update as commits are pushed.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Chores
Refactor
Tests