Repository navigation
OM-280: Agregand al swagger la parte de common, session y commerce - #50
Conversation
into OM-280-Configurar-Swagger
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughSe movió y reescribió la configuración de Swagger de Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant App as Express App
participant Config as Swagger Config
participant JSDoc as swagger-jsdoc
participant UI as swagger-ui-express
participant Schemas as Docs Schemas
Client->>App: inicia servidor (importa setupSwagger)
App->>Config: llama setupSwagger(app)
Config->>Schemas: importa/agrupa esquemas y patrones de rutas
Config->>JSDoc: swaggerJsdoc(options) -> genera swaggerSpec
Config->>UI: monta swaggerUi.serve y swaggerUi.setup(swaggerSpec) en /api/docs
Client->>App: GET /api/docs
App->>UI: sirve UI con swaggerSpec
UI-->>Client: responde UI + especificación OpenAPI
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
📝 Coding Plan
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (8)
src/modules/commerce/products/product.routes.js (1)
14-255: Faltan respuestas500en varios contratos Swagger de productos.Los controladores tienen fallback a
500(create/update/search/getById/compare), pero en estas specs no siempre está documentado. Conviene agregarlo de forma consistente para reflejar el comportamiento real de API.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/modules/commerce/products/product.routes.js` around lines 14 - 255, Swagger specs for several product routes are missing a 500 response; update the JSDoc swagger blocks for the routes handled by createProduct, updateProduct, getProductsSearch, getProductById and compareProducts (and optionally deleteProduct) to include a consistent 500 response entry pointing to the ErrorResponse schema so the docs reflect the controllers' fallback behavior; edit the blocks above router.post("/", ...), router.put("/:id", ...), router.get("/", ...), router.get("/:id", ...), and router.get("/compare/search", ...) to add the 500 responses with the same structure as other error responses.src/docs/schemas/commerce/address.schema.js (1)
17-26: Inconsistencia en restricciones del campoaddress.El campo
addressenCreateAddressRequestno tienemaxLength, pero enUpdateAddressRequesttampoco lo tiene, mientras quecityyregionsí lo tienen (100 caracteres). Para mantener consistencia y documentar correctamente los límites de la base de datos, considerar agregarmaxLengthal campoaddress.♻️ Corrección sugerida
CreateAddressRequest: { type: "object", required: ["address", "city", "region"], properties: { - address: { type: "string", example: "Av. España 1234" }, + address: { type: "string", maxLength: 255, example: "Av. España 1234" }, city: { type: "string", maxLength: 100, example: "Asunción" },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/commerce/address.schema.js` around lines 17 - 26, Add a maxLength constraint to the address property in the CreateAddressRequest schema to match the documented limits used for city/region and keep consistency with UpdateAddressRequest; update the CreateAddressRequest -> properties -> address definition to include an appropriate maxLength (e.g., 100) so it aligns with the other string fields and DB limits referenced by UpdateAddressRequest.src/docs/schemas/commerce/store.schema.js (1)
12-15: Considerar agregarformat: "uri"a los campos de URL.Los campos
logo,website_url,instagram_url, ytiktok_urlpodrían beneficiarse deformat: "uri"para documentar mejor el formato esperado y habilitar validación en clientes que soporten OpenAPI.♻️ Corrección sugerida
- logo: { type: "string", nullable: true, example: "https://example.com/logo.png" }, - website_url: { type: "string", nullable: true, example: "https://micomercio.com" }, - instagram_url: { type: "string", nullable: true, example: "https://instagram.com/micomercio" }, - tiktok_url: { type: "string", nullable: true, example: "https://tiktok.com/@micomercio" }, + logo: { type: "string", format: "uri", nullable: true, example: "https://example.com/logo.png" }, + website_url: { type: "string", format: "uri", nullable: true, example: "https://micomercio.com" }, + instagram_url: { type: "string", format: "uri", nullable: true, example: "https://instagram.com/micomercio" }, + tiktok_url: { type: "string", format: "uri", nullable: true, example: "https://tiktok.com/@micomercio" },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/commerce/store.schema.js` around lines 12 - 15, Agregar `format: "uri"` a las propiedades de URL en el esquema para documentar y validar su formato; en `store.schema.js` actualiza las definiciones de las propiedades logo, website_url, instagram_url y tiktok_url para incluir `format: "uri"` junto a `type: "string"` y `nullable: true` (es decir conservar los campos existentes y añadir la clave `format` a cada una de esas cuatro propiedades).src/docs/schemas/session/session.schema.js (3)
21-21: Inconsistencia en la definición del camporole.En
LoginResponse(línea 21),roleestá definido conenum: ["ADMIN", "CUSTOMER", "SELLER", "DELIVERY"], pero enUserSessionResponse(línea 36) solo tiene unexample. Esto puede confundir a los consumidores de la API sobre los valores válidos.♻️ Corrección sugerida para mantener consistencia
- role: { type: "string", example: "SELLER" }, + role: { type: "string", enum: ["ADMIN", "CUSTOMER", "SELLER", "DELIVERY"], example: "SELLER" },Also applies to: 36-36
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/session/session.schema.js` at line 21, The two response schemas are inconsistent: LoginResponse defines role with enum ["ADMIN","CUSTOMER","SELLER","DELIVERY"] while UserSessionResponse only provides an example; make them consistent by adding the same enum definition to the role field in UserSessionResponse (or alternately remove the enum from LoginResponse if you prefer the example-only approach) so both schemas (LoginResponse and UserSessionResponse) declare the same allowed role values.
42-42: Falta punto y coma al final del objeto.Para mantener consistencia con los otros archivos de esquemas que sí incluyen el punto y coma final.
🔧 Corrección sugerida
} -} +};🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/session/session.schema.js` at line 42, El objeto de esquema definido en este archivo carece del punto y coma final; agrega un punto y coma al cierre del objeto exportado (por ejemplo tras la llave final de session schema/export, p. ej. después de module.exports = { ... }; o del objeto nombrado sessionSchema) para mantener la consistencia con los demás esquemas.
1-1: Línea vacía innecesaria al inicio del archivo.🔧 Corrección sugerida
- export const sessionSchemas = {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/session/session.schema.js` at line 1, Elimina la línea vacía al inicio del archivo src/docs/schemas/session/session.schema.js para que el primer carácter del archivo sea el comienzo del contenido (por ejemplo la declaración de imports, const SessionSchema, o module.exports); abre el archivo, borra la línea en blanco inicial y guarda asegurándote de no introducir espacios en blanco antes del primer token del archivo.src/docs/schemas/index.js (1)
11-13: Código comentado sin contexto.Estas líneas comentadas podrían generar confusión. Si son esquemas pendientes de implementar, sería mejor agregar un comentario TODO o eliminarlas y trackear el trabajo pendiente en un issue.
🔧 Opción 1: Agregar contexto
-/* export * from "./order.schema.js"; -export * from "./review.schema.js"; -export * from "./user.schema.js"; */ +// TODO: Habilitar cuando se implementen los esquemas +// export * from "./order.schema.js"; +// export * from "./review.schema.js"; +// export * from "./user.schema.js";🔧 Opción 2: Eliminar código muerto
export * from "./session/session.schema.js"; - -/* export * from "./order.schema.js"; -export * from "./review.schema.js"; -export * from "./user.schema.js"; */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/index.js` around lines 11 - 13, Las líneas que exportan order.schema.js, review.schema.js y user.schema.js están comentadas sin contexto; añade contexto o elimínalas: si esos esquemas están pendientes, reemplaza el bloque comentado por un TODO que explique por qué están deshabilitados e incluye referencia a un issue/ID (p. ej. TODO: implementar order.schema - issue `#123`) para review.schema.js, user.schema.js y order.schema.js; si son código muerto, elimina las tres líneas comentadas y crea/adjunta un issue que documente el trabajo pendiente.src/config/swagger.config.js (1)
23-36: Considerar parametrizar las URLs de servidores.Las URLs de los servidores están hardcodeadas. Para mayor flexibilidad en diferentes entornos, podrían obtenerse desde variables de entorno.
♻️ Ejemplo de mejora
+const serverUrls = [ + { + url: process.env.API_URL || "http://localhost:3000", + description: "Servidor local" + }, + ...(process.env.TEST_API_URL ? [{ + url: process.env.TEST_API_URL, + description: "Servidor de testeo" + }] : []), + ...(process.env.PROD_API_URL ? [{ + url: process.env.PROD_API_URL, + description: "Servidor de producción" + }] : []) +];Nota: Esto es opcional y puede dejarse para una iteración futura si las URLs actuales funcionan bien para el equipo.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/config/swagger.config.js` around lines 23 - 36, Los URLs de servidores están hardcodeados en la propiedad servers; cambia la definición para leerlos desde variables de entorno (por ejemplo una variable SWAGGER_SERVER_URLS con valores separados por comas o variables individuales como SWAGGER_SERVER_LOCAL/TEST/PROD), parsear esos valores y construir el arreglo servers dinámicamente con el mismo formato { url, description }, manteniendo los valores actuales como fallback si la variable de entorno no está presente; modifica la configuración exportada (la entidad que contiene servers en swagger.config.js) para usar esa lógica al inicializar la configuración.
🤖 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/docs/schemas/commerce/product.schema.js`:
- Line 38: En ProductSearchItemResponse cambia la propiedad definida como
id_product a id para que coincida con ProductResponse y con la normalización que
realiza product.service.js (en la transformación donde hace id:
product.id_product); actualiza el esquema en product.schema.js (referencia a
ProductSearchItemResponse) para usar id: { type: "integer", example: 1 } y
mantener la consistencia con la respuesta real.
In `@src/docs/schemas/common.schema.js`:
- Around line 2-22: El esquema ErrorResponse no refleja la estructura real
devuelta por el middleware authenticate (que usa errors.auth.message en
src/config/jwt.config.js), así que actualiza ErrorResponse en
src/docs/schemas/common.schema.js para incluir una propiedad errors con la forma
esperada (por ejemplo errors.auth.message como string) o un objeto genérico de
errores; modifica la definición de ErrorResponse (símbolo ErrorResponse) para
documentar errors: { auth: { message: { type: "string", example: "..." } } } o
un esquema equivalente que cubra responses 401 devolviendo errors.auth.message.
In `@src/modules/commerce/commerces/store.routes.js`:
- Around line 229-260: The OpenAPI block documents query params (name, sortBy,
sortOrder) that filterStoreProducts doesn't use; update filterStoreProducts in
store.controller.js to read req.query.name, req.query.sortBy and
req.query.sortOrder, apply name as a case-insensitive partial match (e.g., ILIKE
'%name%') to the products query, validate sortBy against allowed fields
(created_at, price, name) and sortOrder against (asc, desc), and apply them to
the DB query/order clause (e.g., .orderBy(sortBy, sortOrder) or equivalent),
defaulting safely when absent; alternatively remove those three params from the
Swagger block if you prefer keeping controller behavior unchanged.
In `@src/modules/commerce/product-reviews/product-review.routes.js`:
- Around line 8-9: The OpenAPI path is wrong: your routes are mounted with
app.use("/products/reviews", productReviewRoutes) and implemented as
router.get("/:id", ...) (productReviewRoutes + router.get), so the actual
endpoint is /products/reviews/{id}; update the Swagger/OpenAPI path from
/products/{id}/reviews to /products/reviews/{id} (or alternatively change how
you mount the router) so the documented path matches the real route.
---
Nitpick comments:
In `@src/config/swagger.config.js`:
- Around line 23-36: Los URLs de servidores están hardcodeados en la propiedad
servers; cambia la definición para leerlos desde variables de entorno (por
ejemplo una variable SWAGGER_SERVER_URLS con valores separados por comas o
variables individuales como SWAGGER_SERVER_LOCAL/TEST/PROD), parsear esos
valores y construir el arreglo servers dinámicamente con el mismo formato { url,
description }, manteniendo los valores actuales como fallback si la variable de
entorno no está presente; modifica la configuración exportada (la entidad que
contiene servers en swagger.config.js) para usar esa lógica al inicializar la
configuración.
In `@src/docs/schemas/commerce/address.schema.js`:
- Around line 17-26: Add a maxLength constraint to the address property in the
CreateAddressRequest schema to match the documented limits used for city/region
and keep consistency with UpdateAddressRequest; update the CreateAddressRequest
-> properties -> address definition to include an appropriate maxLength (e.g.,
100) so it aligns with the other string fields and DB limits referenced by
UpdateAddressRequest.
In `@src/docs/schemas/commerce/store.schema.js`:
- Around line 12-15: Agregar `format: "uri"` a las propiedades de URL en el
esquema para documentar y validar su formato; en `store.schema.js` actualiza las
definiciones de las propiedades logo, website_url, instagram_url y tiktok_url
para incluir `format: "uri"` junto a `type: "string"` y `nullable: true` (es
decir conservar los campos existentes y añadir la clave `format` a cada una de
esas cuatro propiedades).
In `@src/docs/schemas/index.js`:
- Around line 11-13: Las líneas que exportan order.schema.js, review.schema.js y
user.schema.js están comentadas sin contexto; añade contexto o elimínalas: si
esos esquemas están pendientes, reemplaza el bloque comentado por un TODO que
explique por qué están deshabilitados e incluye referencia a un issue/ID (p. ej.
TODO: implementar order.schema - issue `#123`) para review.schema.js,
user.schema.js y order.schema.js; si son código muerto, elimina las tres líneas
comentadas y crea/adjunta un issue que documente el trabajo pendiente.
In `@src/docs/schemas/session/session.schema.js`:
- Line 21: The two response schemas are inconsistent: LoginResponse defines role
with enum ["ADMIN","CUSTOMER","SELLER","DELIVERY"] while UserSessionResponse
only provides an example; make them consistent by adding the same enum
definition to the role field in UserSessionResponse (or alternately remove the
enum from LoginResponse if you prefer the example-only approach) so both schemas
(LoginResponse and UserSessionResponse) declare the same allowed role values.
- Line 42: El objeto de esquema definido en este archivo carece del punto y coma
final; agrega un punto y coma al cierre del objeto exportado (por ejemplo tras
la llave final de session schema/export, p. ej. después de module.exports = {
... }; o del objeto nombrado sessionSchema) para mantener la consistencia con
los demás esquemas.
- Line 1: Elimina la línea vacía al inicio del archivo
src/docs/schemas/session/session.schema.js para que el primer carácter del
archivo sea el comienzo del contenido (por ejemplo la declaración de imports,
const SessionSchema, o module.exports); abre el archivo, borra la línea en
blanco inicial y guarda asegurándote de no introducir espacios en blanco antes
del primer token del archivo.
In `@src/modules/commerce/products/product.routes.js`:
- Around line 14-255: Swagger specs for several product routes are missing a 500
response; update the JSDoc swagger blocks for the routes handled by
createProduct, updateProduct, getProductsSearch, getProductById and
compareProducts (and optionally deleteProduct) to include a consistent 500
response entry pointing to the ErrorResponse schema so the docs reflect the
controllers' fallback behavior; edit the blocks above router.post("/", ...),
router.put("/:id", ...), router.get("/", ...), router.get("/:id", ...), and
router.get("/compare/search", ...) to add the 500 responses with the same
structure as other error responses.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 36463e3b-672c-475e-b6ad-49fcc2a5957a
📒 Files selected for processing (18)
src/app.jssrc/config/swagger.config.jssrc/docs/schemas/commerce/address.schema.jssrc/docs/schemas/commerce/product-review.schema.jssrc/docs/schemas/commerce/product-tag.schema.jssrc/docs/schemas/commerce/product.schema.jssrc/docs/schemas/commerce/store.schema.jssrc/docs/schemas/common.schema.jssrc/docs/schemas/index.jssrc/docs/schemas/session.schema.jssrc/docs/schemas/session/session.schema.jssrc/docs/schemas/store.schema.jssrc/docs/swagger.config.jssrc/modules/commerce/addresses/routes/addresses.routes.jssrc/modules/commerce/commerces/store.routes.jssrc/modules/commerce/product-reviews/product-review.routes.jssrc/modules/commerce/product-tags/product-tag.routes.jssrc/modules/commerce/products/product.routes.js
💤 Files with no reviewable changes (1)
- src/docs/swagger.config.js
| * - in: query | ||
| * name: name | ||
| * schema: | ||
| * type: string | ||
| * description: Filtrar por nombre del producto | ||
| * - in: query | ||
| * name: category | ||
| * schema: | ||
| * type: integer | ||
| * description: Filtrar por ID de categoría | ||
| * - in: query | ||
| * name: price_min | ||
| * schema: | ||
| * type: number | ||
| * description: Precio mínimo | ||
| * - in: query | ||
| * name: price_max | ||
| * schema: | ||
| * type: number | ||
| * description: Precio máximo | ||
| * - in: query | ||
| * name: sortBy | ||
| * schema: | ||
| * type: string | ||
| * enum: [created_at, price, name] | ||
| * description: Campo por el que ordenar | ||
| * - in: query | ||
| * name: sortOrder | ||
| * schema: | ||
| * type: string | ||
| * enum: [asc, desc] | ||
| * description: Dirección del ordenamiento |
There was a problem hiding this comment.
Parámetros documentados que hoy no se aplican en el controlador.
En este endpoint se documentan name, sortBy y sortOrder, pero filterStoreProducts (en src/modules/commerce/commerces/store.controller.js, Lines 100-115) solo usa category, price_min y price_max. La spec queda engañosa para clientes.
💡 Ajuste sugerido (alinear docs con comportamiento actual)
- * - in: query
- * name: name
- * schema:
- * type: string
- * description: Filtrar por nombre del producto
...
- * - in: query
- * name: sortBy
- * schema:
- * type: string
- * enum: [created_at, price, name]
- * description: Campo por el que ordenar
- * - in: query
- * name: sortOrder
- * schema:
- * type: string
- * enum: [asc, desc]
- * description: Dirección del ordenamiento📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * - in: query | |
| * name: name | |
| * schema: | |
| * type: string | |
| * description: Filtrar por nombre del producto | |
| * - in: query | |
| * name: category | |
| * schema: | |
| * type: integer | |
| * description: Filtrar por ID de categoría | |
| * - in: query | |
| * name: price_min | |
| * schema: | |
| * type: number | |
| * description: Precio mínimo | |
| * - in: query | |
| * name: price_max | |
| * schema: | |
| * type: number | |
| * description: Precio máximo | |
| * - in: query | |
| * name: sortBy | |
| * schema: | |
| * type: string | |
| * enum: [created_at, price, name] | |
| * description: Campo por el que ordenar | |
| * - in: query | |
| * name: sortOrder | |
| * schema: | |
| * type: string | |
| * enum: [asc, desc] | |
| * description: Dirección del ordenamiento | |
| * - in: query | |
| * name: category | |
| * schema: | |
| * type: integer | |
| * description: Filtrar por ID de categoría | |
| * - in: query | |
| * name: price_min | |
| * schema: | |
| * type: number | |
| * description: Precio mínimo | |
| * - in: query | |
| * name: price_max | |
| * schema: | |
| * type: number | |
| * description: Precio máximo |
🤖 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` around lines 229 - 260, The
OpenAPI block documents query params (name, sortBy, sortOrder) that
filterStoreProducts doesn't use; update filterStoreProducts in
store.controller.js to read req.query.name, req.query.sortBy and
req.query.sortOrder, apply name as a case-insensitive partial match (e.g., ILIKE
'%name%') to the products query, validate sortBy against allowed fields
(created_at, price, name) and sortOrder against (asc, desc), and apply them to
the DB query/order clause (e.g., .orderBy(sortBy, sortOrder) or equivalent),
defaulting safely when absent; alternatively remove those three params from the
Swagger block if you prefer keeping controller behavior unchanged.
…nto OM-280-Configurar-Swagger
Summary by CodeRabbit
Documentación
Refactorización