Skip to content

Om 97 - #67

Closed
Lianyang1234 wants to merge 2 commits into
devfrom
OM-97-
Closed

Lianyang1234 wants to merge 2 commits into
devfrom
OM-97-

Conversation

@Lianyang1234

@Lianyang1234 Lianyang1234 commented Mar 27, 2026 •

Copy link
Copy Markdown
Collaborator

Cambio JS a TS

Summary by CodeRabbit

  • Correcciones de Errores

    • Mejorada la validación de filtros de precios en tiendas; ahora rechaza cuando el precio mínimo es mayor que el máximo con mensajes de error claros.
  • Refactorización

    • Migrados componentes clave a TypeScript para mejor confiabilidad.
    • Normalización mejorada de valores ingresados en filtros de productos.
  • Pruebas

    • Agregadas pruebas unitarias para validación de filtros.

@coderabbitai

coderabbitai Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Se migraron módulos de DTOs de JavaScript a TypeScript, reemplazando validaciones en el DTO de solicitud con lógica de servicio. La validación de rango de precios se movió a filterStoreProductsService, que ahora normaliza e valida campos de precio antes de consultar la base de datos. Se añadieron clases de respuesta tipadas en TypeScript.

Changes

Cohort / File(s) Resumen
Migraciones de rutas e importaciones
src/modules/commerce/commerces/store.controller.js, src/modules/commerce/commerces/store.routes.js
Actualización de rutas de importación de módulos DTO desde .js a .ts para FilterStoreProductsDTO y StoreProductsPageDTO. Se añadió salto de línea final en store.routes.js.
Lógica de validación de precios en servicio
src/modules/commerce/commerces/store.service.js
Se introdujo helper parseOptionalFiniteNumberField() para normalizar campos de precio. Se agregó validación cruzada que rechaza cuando price_min > price_max con error 400. Se actualizó filterStoreProductsService para usar valores normalizados en filtro de precios.
DTOs de solicitud (migración .js → .ts)
src/modules/global/dtos/commerce/filter-store-products.dto.js, src/modules/global/dtos/commerce/filter-store-products.dto.ts
Se eliminó schema Zod del archivo .js y se recreó en .ts con la misma validación de campos (name, category, price_min, price_max, available, isOffer, sortBy, sortOrder) y refinamiento cruzado de precios. Se exporta tipo TypeScript inferred FilterStoreProductsDTOType.
DTOs de respuesta (migración .js → .ts)
src/modules/global/dtos/commerce/filter-store-products.response.js, src/modules/global/dtos/commerce/filter-store-products.response.ts
Se eliminaron clases StoreProductItemDTO y StoreProductsPageDTO del archivo .js. Se recrearon en .ts con coerción de tipos, normalización de campos (price, original_price, offer_price, is_offer, description, quantity), y manejo de categoría anidada mediante StoreProductCategoryNestedDTO.
Tests e2e
tests/e2e/stores.test.js
Se añadieron tests unitarios para filterStoreProductsService que validan rechazo de price_min/price_max inválidos con error 400 antes de consultar prisma. Se cerró correctamente bloque describe anterior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • CrisNAC
  • Andoumeda

Poem

🐰 De JavaScripto a Type a saltar,
Precios validados sin confusión,
DTOs migrados con precisión,
TypeScript llega para transformar,
¡Conejo feliz por esta razón! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive El título 'Om 97' es muy vago y genérico; no comunica de manera clara qué cambio principal se realizó en el código más allá de una referencia a un número de issue. Considerar un título más descriptivo que refleje el cambio principal, como 'Migrar DTOs de JavaScript a TypeScript' o 'OM-97: Refactorizar filtro de productos con validación mejorada'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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 OM-97-

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 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/modules/commerce/commerces/store.service.js (1)

877-886: Validación duplicada entre DTO y servicio.

Esta validación de price_min > price_max ya existe en el DTO (líneas 73-82 de filter-store-products.dto.ts) y se ejecuta vía middleware antes de llegar al controlador. Sin embargo, esta duplicación provee defensa en profundidad para llamadas directas al servicio (como en los tests unitarios), por lo que es aceptable mantenerla.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/commerce/commerces/store.service.js` around lines 877 - 886, Keep
the existing price_min > price_max validation in the service (the if block that
checks normalizedMinPrice and normalizedMaxPrice) to preserve defense-in-depth
for direct service calls/tests; add a concise comment above that block
explaining it duplicates the DTO validation (so future readers know it's
intentional), and ensure the thrown error still returns status: 400 with the
same message and uses normalizedMinPrice/normalizedMaxPrice as the checked
variables.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/modules/commerce/commerces/store.routes.js`:
- Line 14: The import of FilterStoreProductsDTO using a .ts extension in
store.routes.js will cause a runtime module resolution error; fix by either
changing the import to reference the compiled .js output of
FilterStoreProductsDTO, update your start/dev scripts to run via tsx (so Node
can load .ts at runtime), or ensure tsc builds the project before start and keep
the import pointing to the compiled .js file; locate the import statement for
FilterStoreProductsDTO in store.routes.js and apply one of these three fixes so
the module can be resolved at runtime.

In `@src/modules/global/dtos/commerce/filter-store-products.dto.ts`:
- Around line 53-71: Los validators `sortBy` y `sortOrder` usan la forma
inválida `{ error: "..." }` en z.enum; actualiza ambos para usar la API correcta
de Zod 4 — por ejemplo reemplaza `z.enum([...], { error: "mensaje" })` por
`z.enum([...], "mensaje")` (o alternadamente `{ error: (issues) => "mensaje"
}`), manteniendo la envoltura con `z.preprocess(emptyToUndefined, ...)`, las
llamadas a `z.enum` y las propiedades `.optional().default(...)` intactas para
`sortBy` y `sortOrder`.

---

Nitpick comments:
In `@src/modules/commerce/commerces/store.service.js`:
- Around line 877-886: Keep the existing price_min > price_max validation in the
service (the if block that checks normalizedMinPrice and normalizedMaxPrice) to
preserve defense-in-depth for direct service calls/tests; add a concise comment
above that block explaining it duplicates the DTO validation (so future readers
know it's intentional), and ensure the thrown error still returns status: 400
with the same message and uses normalizedMinPrice/normalizedMaxPrice as the
checked variables.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 77b939da-d457-4877-94ea-481b29fc1bf8

📥 Commits

Reviewing files that changed from the base of the PR and between 4f4a1ba and d7231de.

📒 Files selected for processing (8)
  • src/modules/commerce/commerces/store.controller.js
  • src/modules/commerce/commerces/store.routes.js
  • src/modules/commerce/commerces/store.service.js
  • src/modules/global/dtos/commerce/filter-store-products.dto.js
  • src/modules/global/dtos/commerce/filter-store-products.dto.ts
  • src/modules/global/dtos/commerce/filter-store-products.response.js
  • src/modules/global/dtos/commerce/filter-store-products.response.ts
  • tests/e2e/stores.test.js
💤 Files with no reviewable changes (2)
  • src/modules/global/dtos/commerce/filter-store-products.response.js
  • src/modules/global/dtos/commerce/filter-store-products.dto.js

import { parsePagination } from "../../../middlewares/pagination.middleware.js";
import { validate } from "../../../middlewares/validate.middleware.js";
import { FilterStoreProductsDTO } from "../../global/dtos/commerce/filter-store-products.dto.js";
import { FilterStoreProductsDTO } from "../../global/dtos/commerce/filter-store-products.dto.ts";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verificar configuración de TypeScript y scripts de build
cat tsconfig.json 2>/dev/null || echo "No tsconfig.json found"
cat package.json | jq '.scripts' 2>/dev/null

Repository: CrisNAC/BackendMarketplace

Length of output: 530


🏁 Script executed:

# Check if the target .ts file exists
fd -t f "filter-store-products.dto.ts"

Repository: CrisNAC/BackendMarketplace

Length of output: 131


🏁 Script executed:

# Check the content of src/server.js to see how it's bootstrapped
head -30 src/server.js

Repository: CrisNAC/BackendMarketplace

Length of output: 279


🏁 Script executed:

# Check if tsx or ts-node are installed as dependencies
jq '.dependencies, .devDependencies' package.json | grep -E "(tsx|ts-node|esbuild|webpack)" || echo "No tsx/ts-node found"

Repository: CrisNAC/BackendMarketplace

Length of output: 89


🏁 Script executed:

# Check the actual store.routes.js file to understand the context better
cat src/modules/commerce/commerces/store.routes.js | head -20

Repository: CrisNAC/BackendMarketplace

Length of output: 650


🏁 Script executed:

# Check if app.js and app.ts both exist
ls -la src/app.* 2>/dev/null || echo "No app files found"

Repository: CrisNAC/BackendMarketplace

Length of output: 129


🏁 Script executed:

# Check if there's any build setup or if files are pre-compiled
ls -la src/ | head -20

Repository: CrisNAC/BackendMarketplace

Length of output: 754


🏁 Script executed:

# Check if package.json has a prepare script or if build is automatically run
jq '.scripts | to_entries | .[]' package.json

Repository: CrisNAC/BackendMarketplace

Length of output: 366


🏁 Script executed:

# Verify how the actual imports work - check if .ts is being transpiled in build
cat package.json | jq '.build, .type'

Repository: CrisNAC/BackendMarketplace

Length of output: 83


Importación de archivo .ts desde archivo .js causará error de runtime.

La importación directa con extensión .ts desde un archivo JavaScript no funcionará. Node.js no puede resolver extensiones .ts en runtime con los scripts actuales (node sin tsx). Aunque tsx está instalado como dependencia, los scripts de start y dev usan node y nodemon directamente, no tsx.

Opciones para resolver:

  1. Cambiar el import a: import { FilterStoreProductsDTO } from "../../global/dtos/commerce/filter-store-products.dto.js"; (si el archivo está compilado a .js)
  2. O usar tsx en los scripts: "start": "tsx src/server.js" y "dev": "nodemon --exec tsx src/server.js"
  3. O asegurar que el build con tsc se ejecute antes de start (agregar step previo)

Este cambio causará un error de módulo no encontrado cuando la app intente iniciarse.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/commerce/commerces/store.routes.js` at line 14, The import of
FilterStoreProductsDTO using a .ts extension in store.routes.js will cause a
runtime module resolution error; fix by either changing the import to reference
the compiled .js output of FilterStoreProductsDTO, update your start/dev scripts
to run via tsx (so Node can load .ts at runtime), or ensure tsc builds the
project before start and keep the import pointing to the compiled .js file;
locate the import statement for FilterStoreProductsDTO in store.routes.js and
apply one of these three fixes so the module can be resolved at runtime.

Comment on lines +53 to +71
sortBy: z.preprocess(
emptyToUndefined,
z
.enum(["created_at", "price", "name"], {
error: "sortBy debe ser created_at, price o name"
})
.optional()
.default("created_at")
),

sortOrder: z.preprocess(
emptyToUndefined,
z
.enum(["asc", "desc"], {
error: "sortOrder debe ser asc o desc"
})
.optional()
.default("desc")
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

Zod 4 z.enum error customization syntax and parameters

💡 Result:

In Zod 4, error customization for z.enum uses the unified error parameter, replacing the Zod 3 errorMap. The error param accepts either a static string (applied to all errors from the schema) or a function that receives an issue object (iss) and returns a string or {message: string}. Syntax: - Static string: z.enum(["a", "b"], "Must be a or b!") - Function (error map): z.enum(["a", "b"], { error: (iss) => "Custom message" }) The function receives iss with properties like code (e.g., "invalid_type", "invalid_value" for enum), input, expected. Return undefined to fall back to default. Example for z.enum: const StatusSchema = z.enum(["draft", "published"], { error: (issue) => { if (issue.code === "invalid_value") { return "Status must be 'draft' or 'published'"; } return "Invalid status"; } }); This applies to all issues from the z.enum schema (invalid type, invalid enum value). For refinements on the enum, use separate error params. Zod 3 used errorMap: (issue, ctx) => ({message: string}); Zod 4 simplifies to error: (issue) => string | {message: string} | undefined, dropping ctx and specific params like invalid_type_error. Precedence: schema-level > per-parse > global > locale.

Citations:


Corregir la sintaxis de personalización de errores en z.enum() para Zod 4.

La sintaxis { error: "mensaje" } no es válida en Zod 4. Debe ser o bien una cadena de texto como segundo argumento: z.enum([...], "mensaje"), o una función dentro del objeto: { error: (iss) => "mensaje" }. Esto aplica a los campos sortBy (línea 57) y sortOrder (línea 67).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/global/dtos/commerce/filter-store-products.dto.ts` around lines
53 - 71, Los validators `sortBy` y `sortOrder` usan la forma inválida `{ error:
"..." }` en z.enum; actualiza ambos para usar la API correcta de Zod 4 — por
ejemplo reemplaza `z.enum([...], { error: "mensaje" })` por `z.enum([...],
"mensaje")` (o alternadamente `{ error: (issues) => "mensaje" }`), manteniendo
la envoltura con `z.preprocess(emptyToUndefined, ...)`, las llamadas a `z.enum`
y las propiedades `.optional().default(...)` intactas para `sortBy` y
`sortOrder`.

@Andoumeda
Andoumeda deleted the OM-97- branch April 11, 2026 17:14
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.

1 participant