Repository navigation
Add getCategoryById function for ADMIN role - #100
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 52 minutes and 18 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughLos cambios introducen una nueva ruta de administración para obtener detalles de categorías de productos ( Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Cliente HTTP
participant Auth as Middleware Auth
participant Controller as Controller
participant Service as Service
participant DB as Prisma/BD
Client->>Auth: GET /api/admin/categories/:id<br/>(con JWT token)
Auth->>Auth: Validar token JWT
Auth->>Controller: ✓ Token válido + Role ADMIN
Controller->>Controller: validateId(params.id)
activate Controller
Controller->>Service: getAdminProductCategoryService(id)
deactivate Controller
Service->>DB: findUnique({id_product_category: id})
DB->>Service: category + _count.products
alt Categoría encontrada
Service->>Service: Normalizar respuesta<br/>(id, name, status, productCount, timestamps)
Service-->>Controller: Retornar objeto normalizado
Controller-->>Client: 200 JSON (AdminCategoryResponse)
else Categoría no encontrada
Service-->>Controller: Lanzar NotFoundError
Controller-->>Client: 404 Error
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutos 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 unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/lib/validators.js (1)
3-9: Evitá duplicar la lógica de validación de enteros positivos.
validateIdrepite la misma validación queparsePositiveInteger; si cambia la regla en el futuro, se pueden desalinear. Conviene centralizar en una sola función.♻️ Propuesta de ajuste
export const validateId = (value) => { - const parsed = Number(value); - if (!Number.isInteger(parsed) || parsed <= 0) { - throw new ValidationError(`ID debe ser un entero mayor a 0`); - } - return parsed; + return parsePositiveInteger(value, "ID"); };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/validators.js` around lines 3 - 9, La función validateId contiene la misma lógica que parsePositiveInteger; cambia validateId para delegar la validación y el parseo a parsePositiveInteger (usando ese resultado y lanzando ValidationError si parsePositiveInteger lo hace), eliminando la duplicación de lógica; referencia validateId, parsePositiveInteger y ValidationError para localizar el código y asegurar que validateId solo invoque parsePositiveInteger y devuelva su resultado en lugar de reimplementar la comprobación de enteros positivos.tests/unit/admin/admin-category.test.js (1)
53-84: Sumaría aserciones de “no acceso a DB” en errores tempranos.En los casos
401/403/400, agregarexpect(prisma.productCategories.findUnique).not.toHaveBeenCalled()te asegura que auth/validación cortan antes del servicio.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/unit/admin/admin-category.test.js` around lines 53 - 84, Add assertions in the four early-failure tests to ensure the DB is not touched: after each request in the tests for 401 (no token), 403 (seller), 403 (customer) and 400 (invalid id) add expect(prisma.productCategories.findUnique).not.toHaveBeenCalled(); so you verify auth/validation short-circuits before calling the service; use the existing helper asRole and the mocked prisma.productCategories.findUnique used elsewhere in the test suite.src/docs/schemas/admin/admin-category.schema.js (1)
2-11: Conviene endurecer el contrato del schema conrequired.Hoy el esquema permite respuestas parciales. Si la API siempre devuelve estos campos, sumá
required(y opcionalmenteadditionalProperties: false) para que Swagger refleje el contrato real.🧩 Propuesta de ajuste
AdminCategoryResponse: { type: "object", + required: ["id", "name", "status", "productCount", "createdAt", "updatedAt"], + additionalProperties: false, properties: { id: { type: "integer", example: 1 }, name: { type: "string", example: "Electrónica" }, status: { type: "boolean", example: true }, productCount: { type: "integer", example: 42 }, createdAt: { type: "string", format: "date-time" }, updatedAt: { type: "string", format: "date-time" } } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/docs/schemas/admin/admin-category.schema.js` around lines 2 - 11, El esquema AdminCategoryResponse permite respuestas parciales; corregílo agregando la propiedad required con todos los campos que la API siempre devuelve (id, name, status, productCount, createdAt, updatedAt) dentro del objeto AdminCategoryResponse y, si querés endurecer aún más el contrato, añadí additionalProperties: false para prohibir campos extras; buscá el objeto AdminCategoryResponse en el archivo y actualizá ese bloque con estas claves.
🤖 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/admin/categories/admin-category.routes.js`:
- Around line 23-31: El bloque OpenAPI para este endpoint sólo documenta 200 y
404; añade las respuestas 400, 401 y 403 al mismo response map para evitar
ambigüedades: agrega entradas para 400 (Bad Request), 401 (Unauthorized) y 403
(Forbidden) junto a la actual 200 (AdminCategoryResponse) y 404, y apunta cada
una al esquema de error estándar del proyecto (por ejemplo
ErrorResponse/ApiError en components/schemas) o incluye un objeto
content/application/json con una descripción clara; modifica la sección de
respuestas donde aparece AdminCategoryResponse para incluir estas nuevas claves
y descripciones.
---
Nitpick comments:
In `@src/docs/schemas/admin/admin-category.schema.js`:
- Around line 2-11: El esquema AdminCategoryResponse permite respuestas
parciales; corregílo agregando la propiedad required con todos los campos que la
API siempre devuelve (id, name, status, productCount, createdAt, updatedAt)
dentro del objeto AdminCategoryResponse y, si querés endurecer aún más el
contrato, añadí additionalProperties: false para prohibir campos extras; buscá
el objeto AdminCategoryResponse en el archivo y actualizá ese bloque con estas
claves.
In `@src/lib/validators.js`:
- Around line 3-9: La función validateId contiene la misma lógica que
parsePositiveInteger; cambia validateId para delegar la validación y el parseo a
parsePositiveInteger (usando ese resultado y lanzando ValidationError si
parsePositiveInteger lo hace), eliminando la duplicación de lógica; referencia
validateId, parsePositiveInteger y ValidationError para localizar el código y
asegurar que validateId solo invoque parsePositiveInteger y devuelva su
resultado en lugar de reimplementar la comprobación de enteros positivos.
In `@tests/unit/admin/admin-category.test.js`:
- Around line 53-84: Add assertions in the four early-failure tests to ensure
the DB is not touched: after each request in the tests for 401 (no token), 403
(seller), 403 (customer) and 400 (invalid id) add
expect(prisma.productCategories.findUnique).not.toHaveBeenCalled(); so you
verify auth/validation short-circuits before calling the service; use the
existing helper asRole and the mocked prisma.productCategories.findUnique used
elsewhere in the test suite.
🪄 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: a3392f05-e82f-42e0-9357-891071af6e21
📒 Files selected for processing (18)
src/app.jssrc/config/swagger.config.jssrc/docs/schemas/admin/admin-category.schema.jssrc/docs/schemas/index.jssrc/docs/schemas/product.schema.jssrc/docs/schemas/review.schema.jssrc/lib/validators.jssrc/modules/admin/categories/admin-category.controller.jssrc/modules/admin/categories/admin-category.routes.jssrc/modules/admin/categories/admin-category.service.jssrc/modules/admin/index.jssrc/modules/admin/users/admin-users.routes.jssrc/modules/global/categories/.gitkeepsrc/modules/images/routes/index.jssrc/modules/images/routes/product-image.routes.jssrc/modules/images/routes/store-image.routes.jssrc/modules/images/routes/user-image.routes.jstests/unit/admin/admin-category.test.js
Summary by CodeRabbit
Nuevas Funcionalidades
/api/admin/categories/:idpara administradores que permite recuperar detalles completos de categorías de productos, incluyendo nombre, estado, cantidad de productos asociados e información de registro.Pruebas