Entrega final do desafio técnico - corelab-api-challenge#76
Entrega final do desafio técnico - corelab-api-challenge#76DavidBotelhoo wants to merge 2 commits into
Conversation
WalkthroughReplaces an AdonisJS-based API with a NestJS + TypeORM PostgreSQL service. Adds tasks CRUD with DTOs, entity, service, controller, Swagger, config, Docker/Compose, and init SQL. Removes Adonis configs, providers, routes, tests, and type contracts. Introduces environment variables, lint/format configs, and updates project metadata and tsconfig. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant N as NestJS App
participant CFG as ConfigService
participant SWG as SwaggerModule
participant ORM as TypeORM
U->>N: Start app (node dist/main.js)
activate N
N->>CFG: Load env (.env)
CFG-->>N: Config values
N->>ORM: Initialize connection (forRootAsync)
ORM-->>N: Connected
N->>SWG: Build & setup docs (/api/v1/docs)
SWG-->>N: Swagger ready
N-->>U: Listening on PORT with API_PREFIX
deactivate N
sequenceDiagram
autonumber
participant C as Client
participant Ctrl as TasksController
participant Svc as TasksService
participant Repo as TypeORM Repository
participant DB as PostgreSQL
C->>Ctrl: GET /tasks?page&limit&status&isFavorite&search
Ctrl->>Svc: findAll(params)
Svc->>Repo: build query (filters, ILIKE, pagination, sort)
Repo->>DB: SELECT ... WHERE ... ORDER BY created_at DESC LIMIT/OFFSET
DB-->>Repo: rows, count
Repo-->>Svc: tasks[], total
Svc-->>Ctrl: { tasks, total, totalPages }
Ctrl-->>C: 200 OK (TasksResponseDto)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ 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. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 37
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
.gitignore (1)
1-2: .gitignore is dangerously minimal—risks committing secrets, build outputs, and framework artifacts.Expand ignores for Node, Nest, Next.js, Docker, and env files.
-node_modules +node_modules/ +dist/ +build/ +coverage/ +.next/ +out/ +*.log +logs/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.DS_Store +.env +.env.* +!.env.example +.eslintcache +.turbo +.vscode/ +.idea/ +# Docker +docker-compose.override.yml +*.local.yml +# DB/data +data/ +pgdata/.env (1)
1-21: Remove committed .env from VCS; use .env.example + env_file in ComposeSecrets and local overrides shouldn’t be in git. Commit only .env.example and ignore .env.
Steps:
- git rm --cached .env
- echo ".env" >> .gitignore
Optionally switch docker-compose services to use env_file: .env and override only DATABASE_HOST there.
🧹 Nitpick comments (38)
nest-cli.json (1)
5-9: Use SWC builder for faster, smaller builds (Webpack is legacy here).Switching Nest CLI builder from webpack to swc significantly speeds up builds and reduces image size while keeping
typeCheck: true."compilerOptions": { "deleteOutDir": true, - "builder": "webpack", + "builder": "swc", "typeCheck": true }.prettierrc (1)
2-9: PreferarrowParens: "always"to reduce diff churn and parsing ambiguities.Keeps param lists explicit and consistent, especially with TS generics and auto-fixes.
"bracketSpacing": true, - "arrowParens": "avoid" + "arrowParens": "always"tsconfig.json (1)
3-13: Align module/target with runtime and resolver for smoother DX.If Docker uses Node 20+, consider ES2022 target and explicit module resolution + Node types.
- "module": "commonjs", + "module": "commonjs", "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, - "target": "ES2020", + "target": "ES2022", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, + "moduleResolution": "node", + "types": ["node"],PULL_REQUEST.md (2)
59-63: Prefer migrations over a one-offinit.sqlfor evolvable schema.Adopt a migration tool (e.g., TypeORM migrations, Prisma Migrate, or knex) to version and roll back DB changes across environments.
47-47: Make the Swagger URL a clickable Markdown link and decouple hardcoded host.Improves docs UX and avoids implying fixed hostnames.
-Swagger disponível em `http://localhost:3001/api/v1/docs`. +Swagger disponível em [API Docs](http://localhost:3001/api/v1/docs).package.json (2)
1-7: Declare Node engine to match README and CI.README says Node 22+. Add engines to avoid runtime drift.
Apply:
{ "name": "to-do-list-api", "version": "0.0.1", "description": "To-Do List API with NestJS", "author": "David Botelho", "private": true, "license": "UNLICENSED", + "engines": { "node": ">=22" },Also applies to: 26-26
84-86: Document why glob is overridden.Pinning transitive deps is fine; add a comment in README or commit message to aid dependabot/upgrades.
src/tasks/entities/task.entity.ts (1)
16-83: Add indexes at the entity level to mirror DB indexes.You created DB indexes in init.sql; add decorators so future migrations keep them.
Apply:
-import { - Entity, - PrimaryGeneratedColumn, - Column, - CreateDateColumn, - UpdateDateColumn, -} from 'typeorm'; +import { + Entity, + PrimaryGeneratedColumn, + Column, + CreateDateColumn, + UpdateDateColumn, + Index, +} from 'typeorm'; ... - @Column({ + @Index('idx_tasks_status') + @Column({ type: 'enum', enum: TaskStatus, enumName: 'task_status', default: TaskStatus.PENDING, }) status: TaskStatus; ... - @Column({ type: 'boolean', default: false, name: 'is_favorite' }) + @Index('idx_tasks_is_favorite') + @Column({ type: 'boolean', default: false, name: 'is_favorite' }) isFavorite: boolean; ... - @CreateDateColumn({ name: 'created_at' }) + @Index('idx_tasks_created_at') + @CreateDateColumn({ name: 'created_at' }) createdAt: Date;README.md (4)
10-10: Use proper Markdown headings instead of bold sections (MD036).Switch emphasized lines to
##headings for linting and TOC.-**Repositório** +## Repositórios -**Visão Geral** +## Visão Geral -**Funcionalidades** +## Funcionalidades -**Stack** +## Stack -**Pré‑requisitos** +## Pré‑requisitos -**Rodando com NPM (desenvolvimento local)** +## Rodando com NPM (desenvolvimento local) -**Rodando com Docker (compose unificado)** +## Rodando com Docker (compose unificado) -**Variáveis de Ambiente** +## Variáveis de Ambiente -**Endpoints Principais (API)** +## Endpoints Principais (API) -**Estrutura de Pastas (raiz)** +## Estrutura de Pastas (raiz) -**Dicas de Desenvolvimento** +## Dicas de DesenvolvimentoAlso applies to: 23-23, 31-31, 37-37, 43-43, 65-65, 81-81, 91-91, 103-103, 108-108, 5-5
66-75: Unify docker-compose command form.Prefer
docker composeconsistently; avoid mixing withdocker-compose.- 2. `docker-compose up -d --build` + 2. `docker compose up -d --build`Also applies to: 69-70
57-61: Portuguese term: “servidor de desenvolvimento”.Minor language nit for consistency.
- 1. Em `to-do-list-web`, instale dependências e suba o dev server: + 1. Em `to-do-list-web`, instale dependências e suba o servidor de desenvolvimento:
71-75: Avoid line-number references; they rot quickly.Replace “veja arquivo:linha” with stable paths or config keys (PORT, API_PREFIX).
Also applies to: 18-19
.eslintrc.js (1)
3-7: Type-aware linting may slow CI.Using
parserOptions.projectenables type-aware rules. If CI time grows, consider a non-type-aware config for fast paths.init.sql (1)
2-2: uuid-ossp requires superuser on some images.If your DB user isn’t superuser, prefer
pgcryptoandgen_random_uuid()or enable the extension at build time.Alternative:
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- and use DEFAULT gen_random_uuid()Dockerfile.dev (1)
3-16: Pequenas melhorias de DX no dev container.
- Defina NODE_ENV=development (algumas libs habilitam logs úteis).
- Adicione .dockerignore para não copiar node_modules/dist.
Aplicar (opcional):
WORKDIR /app +ENV NODE_ENV=developmentArquivo extra (.dockerignore):
node_modules dist .git Dockerfile* docker-compose*.yml .env* coveragesrc/app.service.ts (1)
5-11: Health mais útil em produção (readiness/liveness).Considere Nest Terminus para checar DB (TypeORM ping), além de uptime.
Posso fornecer um exemplo de
@nestjs/terminuscomTypeOrmHealthIndicatorse quiser..env.example (5)
18-20: Quote Swagger values to satisfy dotenv-linter and avoid parsing surprisesValues with spaces should be quoted.
-SWAGGER_TITLE=To-Do List API -SWAGGER_DESCRIPTION=API for managing tasks and todo lists +SWAGGER_TITLE="To-Do List API" +SWAGGER_DESCRIPTION="API for managing tasks and todo lists" SWAGGER_VERSION=1.0
2-6: Reorder DATABASE_ keys to pass dotenv-linter (alphabetical within the block)*Purely stylistic, but keeps CI/lint quiet.
DATABASE_HOST=localhost -DATABASE_PORT=5432 -DATABASE_NAME=to-do-list-api -DATABASE_USERNAME=admin -DATABASE_PASSWORD=admin123 +DATABASE_NAME=to-do-list-api +DATABASE_PASSWORD=admin123 +DATABASE_PORT=5432 +DATABASE_USERNAME=admin
9-11: Place API_PREFIX before NODE_ENV per dotenv-linterNo runtime impact; makes linter green.
-# Application Configuration -NODE_ENV=development -PORT=3001 -API_PREFIX=api/v1 +# Application Configuration +PORT=3001 +API_PREFIX=api/v1 +NODE_ENV=development
14-15: Alphabetize JWT_ keys (dotenv-linter)*- JWT_SECRET=your-super-secret-jwt-key - JWT_EXPIRES_IN=7d + JWT_EXPIRES_IN=7d + JWT_SECRET=your-super-secret-jwt-key
4-4: Consider avoiding hyphens in DATABASE_NAMEPostgres allows them but they’re awkward in CLI/tools. Prefer snake_case (e.g., todo_list_api).
.env (5)
18-20: Quote Swagger values; same linter fixes as .env.example-SWAGGER_TITLE=To-Do List API -SWAGGER_DESCRIPTION=API for managing tasks and todo lists +SWAGGER_TITLE="To-Do List API" +SWAGGER_DESCRIPTION="API for managing tasks and todo lists" SWAGGER_VERSION=1.0
2-6: Reorder DATABASE_ keys to satisfy dotenv-linter*DATABASE_HOST=localhost -DATABASE_PORT=5432 -DATABASE_NAME=to-do-list-api -DATABASE_USERNAME=admin -DATABASE_PASSWORD=admin123 +DATABASE_NAME=to-do-list-api +DATABASE_PASSWORD=admin123 +DATABASE_PORT=5432 +DATABASE_USERNAME=admin
9-11: Place API_PREFIX before NODE_ENV-NODE_ENV=development -PORT=3001 -API_PREFIX=api/v1 +PORT=3001 +API_PREFIX=api/v1 +NODE_ENV=development
14-15: Alphabetize JWT_ keys*-JWT_SECRET=your-super-secret-jwt-key -JWT_EXPIRES_IN=7d +JWT_EXPIRES_IN=7d +JWT_SECRET=your-super-secret-jwt-key
4-4: Prefer snake_case DB nameSame rationale as in .env.example.
src/app.controller.ts (2)
12-23: Use ApiOkResponse and a typed DTO (optional)Improves Swagger clarity. Consider creating a HealthDto and using @ApiOkResponse({ type: HealthDto }).
1-27: Add real health checks (DB readiness) via @nestjs/terminus (optional)Replace simple uptime with Terminus indicators (TypeOrmHealthIndicator) so k8s/docker can gate readiness on DB availability.
docker-compose.yml (2)
26-34: Reduce secret sprawl; load shared vars from .env and override host onlyKeeps credentials out of compose. Override DATABASE_HOST in-service.
- environment: - - NODE_ENV=production - - PORT=3001 - - API_PREFIX=api/v1 - - DATABASE_HOST=postgres - - DATABASE_PORT=5432 - - DATABASE_NAME=to-do-list-api - - DATABASE_USERNAME=admin - - DATABASE_PASSWORD=admin123 + env_file: .env + environment: + - NODE_ENV=production + - DATABASE_HOST=postgres
44-56: Gate api-dev with a compose profile to avoid accidental startupPrevents running both api and api-dev simultaneously.
api-dev: build: context: . dockerfile: Dockerfile.dev container_name: to-do-list-api-dev restart: always + profiles: ["dev"] ports: - '3334:3001' environment: - NODE_ENV=development - PORT=3001 - API_PREFIX=api/v1 - DATABASE_HOST=postgres - DATABASE_PORT=5432 - DATABASE_NAME=to-do-list-api - DATABASE_USERNAME=admin - DATABASE_PASSWORD=admin123src/database/database.module.ts (2)
17-19: Prefer auto-load entities and drop hard-coded listReduces maintenance when adding entities.
- entities: [Task], + autoLoadEntities: true,Also remove the unused import:
-import { Task } from '../tasks/entities/task.entity';
11-19: Optional: production hardeningConsider pool sizing and SSL toggled by env (e.g., PGSSLMODE=require).
src/main.ts (1)
7-12: Enable graceful shutdown for containers.Helps on SIGTERM during deploys.
const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); const logger = new Logger('Bootstrap'); + app.enableShutdownHooks();src/tasks/tasks.service.ts (1)
110-124: Use DB aggregation for stats to avoid full-table scans.Scale better for large tables.
- async getTasksByStatus(): Promise<{ [key in TaskStatus]: number }> { - const tasks = await this.taskRepository.find(); - - return tasks.reduce( - (acc, task) => { - acc[task.status] = (acc[task.status] || 0) + 1; - return acc; - }, - { - [TaskStatus.PENDING]: 0, - [TaskStatus.IN_PROGRESS]: 0, - [TaskStatus.COMPLETED]: 0, - }, - ); - } + async getTasksByStatus(): Promise<{ [key in TaskStatus]: number }> { + const rows = await this.taskRepository + .createQueryBuilder('task') + .select('task.status', 'status') + .addSelect('COUNT(*)::int', 'count') + .groupBy('task.status') + .getRawMany<{ status: TaskStatus; count: number }>(); + const base = { + [TaskStatus.PENDING]: 0, + [TaskStatus.IN_PROGRESS]: 0, + [TaskStatus.COMPLETED]: 0, + } as { [key in TaskStatus]: number }; + for (const r of rows) base[r.status] = r.count; + return base; + }src/tasks/dto/task.dto.ts (3)
70-75: Add UUID format to id for better OpenAPI fidelity.@ApiProperty({ description: 'Task unique identifier', example: '123e4567-e89b-12d3-a456-426614174000', + format: 'uuid', }) id: string;
95-99: Make color example consistent with CreateTaskDto and service default.If standardizing on named colors, show 'blue'.
- @ApiProperty({ - description: 'Task color for UI customization', - example: '#3B82F6', - }) + @ApiProperty({ + description: 'Task color for UI customization', + example: 'blue', + }) color: string;If you prefer hex codes, I can update CreateTaskDto to accept hex via conditional validators instead.
107-112: Mark date-time formats for createdAt/updatedAt.@ApiProperty({ description: 'Task creation date', example: '2023-12-01T10:30:00.000Z', + type: String, + format: 'date-time', }) createdAt: Date; @@ @ApiProperty({ description: 'Task last update date', example: '2023-12-01T15:45:00.000Z', + type: String, + format: 'date-time', }) updatedAt: Date;Also applies to: 113-118
src/tasks/tasks.controller.ts (1)
33-45: Controller-to-DTO mapping (optional).You’re returning entities directly. If the entity gains extra fields later, responses may leak them. Consider mapping to TaskResponseDto or enabling ClassSerializerInterceptor.
I can provide a lightweight mapper or enable serialization in main.ts if desired.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (2)
dist/main.jsis excluded by!**/dist/**package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (53)
.adonisrc.json(0 hunks).editorconfig(0 hunks).env(1 hunks).env.example(1 hunks).eslintrc.js(1 hunks).gitignore(1 hunks).gitignore copy(0 hunks).prettierignore(0 hunks).prettierrc(1 hunks)Dockerfile(1 hunks)Dockerfile.dev(1 hunks)Leiame.md(0 hunks)PULL_REQUEST.md(1 hunks)README.md(1 hunks)ace(0 hunks)ace-manifest.json(0 hunks)app/Controllers/VehiclesController.ts(0 hunks)app/Exceptions/Handler.ts(0 hunks)app/Types/Vehicle.ts(0 hunks)commands/index.ts(0 hunks)config/app.ts(0 hunks)config/bodyparser.ts(0 hunks)config/cors.ts(0 hunks)config/drive.ts(0 hunks)config/hash.ts(0 hunks)contracts/drive.ts(0 hunks)contracts/env.ts(0 hunks)contracts/events.ts(0 hunks)contracts/hash.ts(0 hunks)contracts/tests.ts(0 hunks)docker-compose.yml(1 hunks)env.ts(0 hunks)init.sql(1 hunks)nest-cli.json(1 hunks)package.json(1 hunks)providers/AppProvider.ts(0 hunks)server.ts(0 hunks)src/app.controller.ts(1 hunks)src/app.module.ts(1 hunks)src/app.service.ts(1 hunks)src/database/database.module.ts(1 hunks)src/main.ts(1 hunks)src/tasks/dto/task.dto.ts(1 hunks)src/tasks/entities/task.entity.ts(1 hunks)src/tasks/tasks.controller.ts(1 hunks)src/tasks/tasks.module.ts(1 hunks)src/tasks/tasks.service.ts(1 hunks)start/kernel.ts(0 hunks)start/routes.ts(0 hunks)test.ts(0 hunks)tests/bootstrap.ts(0 hunks)tests/functional/vehicles-api.spec.ts(0 hunks)tsconfig.json(1 hunks)
💤 Files with no reviewable changes (29)
- contracts/tests.ts
- start/kernel.ts
- server.ts
- tests/functional/vehicles-api.spec.ts
- config/hash.ts
- app/Exceptions/Handler.ts
- contracts/hash.ts
- tests/bootstrap.ts
- test.ts
- providers/AppProvider.ts
- Leiame.md
- .adonisrc.json
- config/app.ts
- .editorconfig
- contracts/env.ts
- ace
- config/drive.ts
- config/bodyparser.ts
- ace-manifest.json
- .gitignore copy
- start/routes.ts
- commands/index.ts
- app/Types/Vehicle.ts
- .prettierignore
- env.ts
- contracts/events.ts
- contracts/drive.ts
- app/Controllers/VehiclesController.ts
- config/cors.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-18T22:52:15.229Z
Learnt from: leandrodomingues2051
PR: corelabbr/corelab-api-challenge#57
File: Dockerfile:1-10
Timestamp: 2025-03-18T22:52:15.229Z
Learning: The Dockerfile in this project is intended for development purposes only, not for production deployment.
Applied to files:
Dockerfile.dev
🧬 Code graph analysis (9)
src/tasks/tasks.module.ts (3)
src/app.module.ts (1)
Module(9-21)src/database/database.module.ts (1)
Module(6-28)dist/main.js (2)
Task(401-402)TasksModule(722-723)
src/database/database.module.ts (2)
src/app.module.ts (1)
Module(9-21)src/tasks/tasks.module.ts (1)
Module(7-13)
src/main.ts (1)
dist/main.js (1)
AppModule(85-86)
src/app.controller.ts (1)
dist/main.js (2)
AppController(27-34)AppService(122-130)
src/app.module.ts (3)
src/database/database.module.ts (1)
Module(6-28)src/tasks/tasks.module.ts (1)
Module(7-13)dist/main.js (4)
DatabaseModule(158-159)TasksModule(722-723)AppController(27-34)AppService(122-130)
src/app.service.ts (1)
dist/main.js (1)
AppService(122-130)
src/tasks/entities/task.entity.ts (1)
dist/main.js (1)
Task(401-402)
src/tasks/tasks.controller.ts (2)
dist/main.js (1)
TasksService(763-850)src/tasks/dto/task.dto.ts (4)
TaskResponseDto(69-118)CreateTaskDto(16-65)TasksResponseDto(120-150)UpdateTaskDto(67-67)
src/tasks/tasks.service.ts (1)
src/tasks/dto/task.dto.ts (2)
CreateTaskDto(16-65)UpdateTaskDto(67-67)
🪛 LanguageTool
PULL_REQUEST.md
[uncategorized] ~5-~5: Encontrada possível ausência de vírgula.
Context: ...ódulo de tarefas, persistência em banco relacional PostgreSQL, validações, CORS e variávei...
(AI_PT_HYDRA_LEO_MISSING_COMMA)
[locale-violation] ~6-~6: “Router” é um estrangeirismo. É preferível dizer “encaminhador” ou “roteador”.
Context: ...ambiente). - Front-end com Next.js (App Router), TypeScript e Tailwind CSS, construído...
(PT_BARBARISMS_REPLACE_ROUTER)
[grammar] ~12-~12: Possível erro de concordância.
Context: ...ois lados via cliente HTTP centralizado no web (src/services/api.ts). - Adiciona Doc...
(GENERAL_GENDER_AGREEMENT_ERRORS)
[locale-violation] ~18-~18: “Router” é um estrangeirismo. É preferível dizer “encaminhador” ou “roteador”.
Context: ...ostgres:15). - Front-end: Next.js (App Router em src/app`), TypeScript, Tailwind CSS...
(PT_BARBARISMS_REPLACE_ROUTER)
[uncategorized] ~18-~18: Encontrada possível ausência de vírgula.
Context: ... (App Router em src/app), TypeScript, Tailwind CSS; componentes reutilizáveis para for...
(AI_PT_HYDRA_LEO_MISSING_COMMA)
[uncategorized] ~27-~27: Sinal de pontuação isolado.
Context: ...orta em uso: 3001. - src/app.module.ts: módulo raiz, importa o módulo de databa...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~28-~28: Sinal de pontuação isolado.
Context: ...fas. - src/database/database.module.ts: configuração do acesso ao banco Postgre...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~29-~29: Sinal de pontuação isolado.
Context: ...credenciais via .env). - src/tasks/*: domínio de tarefas (controller, service...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~30-~30: Sinal de pontuação isolado.
Context: ...e entity). - entities/task.entity.ts: mapeamento da entidade Task no banco....
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~31-~31: Sinal de pontuação isolado.
Context: ...e Task no banco. - dto/task.dto.ts: contratos de entrada/validação para cri...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~32-~32: Sinal de pontuação isolado.
Context: ...o/atualização. - tasks.controller.ts: rotas REST. - tasks.service.ts: reg...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~33-~33: Sinal de pontuação isolado.
Context: ....ts: rotas REST. - tasks.service.ts`: regras de negócio e orquestração de per...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~41-~41: Sinal de pontuação isolado.
Context: ...stJS e o domínio tasks. - GET /tasks: lista tarefas (suporta filtros como tex...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~42-~42: Sinal de pontuação isolado.
Context: ..., status e favorito). - GET /tasks/:id: obtém uma tarefa por ID. - `POST /tasks...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~43-~43: Sinal de pontuação isolado.
Context: ...obtém uma tarefa por ID. - POST /tasks: cria nova tarefa. - PATCH /tasks/:id:...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~44-~44: Sinal de pontuação isolado.
Context: ...: cria nova tarefa. - PATCH /tasks/:id: atualiza campos da tarefa (ex.: título/...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~45-~45: Sinal de pontuação isolado.
Context: ...status, favorito). - DELETE /tasks/:id: remove tarefa. Swagger disponível em `...
(UNLIKELY_OPENING_PUNCTUATION)
[inconsistency] ~47-~47: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...: remove tarefa. Swagger disponível emhttp://localhost:3001/api/v1/docs`. ### Banco de Dados - Banco: PostgreSQL...
(URL_VALIDATION)
[locale-violation] ~63-~63: “package” é um estrangeirismo. É preferível dizer “embalagem” ou “pacote”.
Context: ... + API (porta 3001). - Scripts npm no package.json (ex.: start:dev, build, `star...
(PT_BARBARISMS_REPLACE_PACKAGE)
[locale-violation] ~79-~79: “Router” é um estrangeirismo. É preferível dizer “encaminhador” ou “roteador”.
Context: ...rc/app/page.tsx: página principal (App Router) que organiza as seções. - src/compone...
(PT_BARBARISMS_REPLACE_ROUTER)
[uncategorized] ~80-~80: Sinal de pontuação isolado.
Context: ... seções. - src/components/TaskForm.tsx: criação de tarefas (controle de input e...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~81-~81: Sinal de pontuação isolado.
Context: ...mit). - src/components/TaskFilters.tsx: busca/filtro de tarefas (texto, status ...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~82-~82: Sinal de pontuação isolado.
Context: ...oritos). - src/components/TaskItem.tsx: item de tarefa (exibir, favoritar, excl...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~83-~83: Sinal de pontuação isolado.
Context: ...ponível). - src/components/Loading.tsx: estado de carregamento enquanto busca d...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~84-~84: Sinal de pontuação isolado.
Context: ...os. - src/components/ErrorBoundary.tsx: fallback de erro para falhas de rede/ex...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~85-~85: Sinal de pontuação isolado.
Context: ...e rede/execução. - src/services/api.ts: cliente HTTP central (baseURL com prefi...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~86-~86: Sinal de pontuação isolado.
Context: ...funções para CRUD. - src/types/task.ts: tipagem da entidade Task utilizada no...
(UNLIKELY_OPENING_PUNCTUATION)
[grammar] ~103-~103: Possível erro de concordância.
Context: ...ervir a aplicação em dev/prod. - .env do web define a URL base quando necessário (ex...
(GENERAL_GENDER_AGREEMENT_ERRORS)
[locale-violation] ~104-~104: “package” é um estrangeirismo. É preferível dizer “embalagem” ou “pacote”.
Context: ...XT_PUBLIC_API_URL). - Scripts npmnopackage.json(ex.:dev, build, start, l...
(PT_BARBARISMS_REPLACE_PACKAGE)
[uncategorized] ~109-~109: Encontrada possível ausência de vírgula.
Context: ...) 1) Início pelo back-end: definição do domínio tasks, entidade e DTOs, implementação...
(AI_PT_HYDRA_LEO_MISSING_COMMA)
README.md
[inconsistency] ~53-~53: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...PI disponível (por padrão do código) emhttp://localhost:3001/api/v1`. - Swagger: `http://localhost:3001/...
(URL_VALIDATION)
[inconsistency] ~54-~54: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...localhost:3001/api/v1. - Swagger: http://localhost:3001/api/v1/docs. - Front‑end (Next.js): 1. Em `to-do-...
(URL_VALIDATION)
[locale-violation] ~57-~57: “server” é um estrangeirismo. É preferível dizer “servidor”.
Context: ...web, instale dependências e suba o dev server: - cd to-do-list-web -npm...
(PT_BARBARISMS_REPLACE_SERVER)
[inconsistency] ~61-~61: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...stall - npm run dev 2. Acesse http://localhost:3000. 3. As chamadas para /api/* são rees...
(URL_VALIDATION)
[inconsistency] ~62-~62: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: .../* são reescritas para o back local em http://localhost:3001 (veja to-do-list-web/next.config.ts:8...
(URL_VALIDATION)
[inconsistency] ~70-~70: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...e up -d --build 3. Acesse o front em http://localhost:3000. 4. A API deve expor `http://localhost...
(URL_VALIDATION)
[inconsistency] ~71-~71: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: .../localhost:3000. 4. A API deve expor http://localhost:3333/api/v1 segundo o compose. Importante: o código...
(URL_VALIDATION)
[inconsistency] ~75-~75: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...a) e recompilar a imagem. 5. Swagger:http://localhost:3333/api/v1/docs` (considere o ajuste de porta acima). -...
(URL_VALIDATION)
[uncategorized] ~82-~82: Pontuação duplicada
Context: ...nte** - Back‑end (to-do-list-api/.env): - DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, `DATA...
(DOUBLE_PUNCTUATION_XML)
[uncategorized] ~84-~84: Sinal de pontuação isolado.
Context: ...ME, DATABASE_PASSWORD. - NODE_ENV, API_PREFIX(p.ex.api/v1). - JWT...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~85-~85: Sinal de pontuação isolado.
Context: ...EFIX(p.ex.api/v1). - JWT_SECRET, JWT_EXPIRES_IN` (planejado para autent...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~92-~92: Pontuação duplicada
Context: ... Endpoints Principais (API) - Base: /api/v1 - GET /tasks: lista com paginação e filtros (status...
(DOUBLE_PUNCTUATION_XML)
[uncategorized] ~94-~94: Sinal de pontuação isolado.
Context: ...vorite, search). - GET /tasks/stats: estatísticas por status. - GET /tasks/...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~95-~95: Sinal de pontuação isolado.
Context: ...atísticas por status. - GET /tasks/:id: obtém tarefa por ID. - POST /tasks: c...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~96-~96: Sinal de pontuação isolado.
Context: ...d: obtém tarefa por ID. - POST /tasks: cria tarefa. - PATCH /tasks/:id`: atua...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~97-~97: Sinal de pontuação isolado.
Context: ...asks: cria tarefa. - PATCH /tasks/:id: atualiza tarefa. - PATCH /tasks/:id/st...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~98-~98: Sinal de pontuação isolado.
Context: ...liza tarefa. - PATCH /tasks/:id/status: atualiza status. - `PATCH /tasks/:id/fa...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~99-~99: Sinal de pontuação isolado.
Context: ...za status. - PATCH /tasks/:id/favorite: alterna favorito. - DELETE /tasks/:id...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~100-~100: Sinal de pontuação isolado.
Context: ... alterna favorito. - DELETE /tasks/:id: remove tarefa. **Estrutura de Pastas ...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~105-~105: Sinal de pontuação isolado.
Context: ...ação Next.js (front). - to-do-list-api: aplicação NestJS (back). **Dicas de D...
(UNLIKELY_OPENING_PUNCTUATION)
[locale-violation] ~109-~109: “package” é um estrangeirismo. É preferível dizer “embalagem” ou “pacote”.
Context: ...ode 22+ é necessário para o front (veja to-do-list-web/package.json:38). - CORS no back já permite `h...
(PT_BARBARISMS_REPLACE_PACKAGE)
[inconsistency] ~110-~110: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...ge.json:38). - CORS no back já permite http://localhost:3000 (veja to-do-list-api/src/main.ts:18)....
(URL_VALIDATION)
[uncategorized] ~113-~113: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ...: npm run start:dev, npm run build, npm test, npm run migration:run. - Front: `...
(ABREVIATIONS_PUNCTUATION)
🪛 dotenv-linter (3.3.0)
.env
[warning] 4-4: [UnorderedKey] The DATABASE_NAME key should go before the DATABASE_PORT key
(UnorderedKey)
[warning] 6-6: [UnorderedKey] The DATABASE_PASSWORD key should go before the DATABASE_PORT key
(UnorderedKey)
[warning] 11-11: [UnorderedKey] The API_PREFIX key should go before the NODE_ENV key
(UnorderedKey)
[warning] 15-15: [UnorderedKey] The JWT_EXPIRES_IN key should go before the JWT_SECRET key
(UnorderedKey)
[warning] 18-18: [ValueWithoutQuotes] This value needs to be surrounded in quotes
(ValueWithoutQuotes)
[warning] 19-19: [UnorderedKey] The SWAGGER_DESCRIPTION key should go before the SWAGGER_TITLE key
(UnorderedKey)
[warning] 19-19: [ValueWithoutQuotes] This value needs to be surrounded in quotes
(ValueWithoutQuotes)
.env.example
[warning] 4-4: [UnorderedKey] The DATABASE_NAME key should go before the DATABASE_PORT key
(UnorderedKey)
[warning] 6-6: [UnorderedKey] The DATABASE_PASSWORD key should go before the DATABASE_PORT key
(UnorderedKey)
[warning] 11-11: [UnorderedKey] The API_PREFIX key should go before the NODE_ENV key
(UnorderedKey)
[warning] 15-15: [UnorderedKey] The JWT_EXPIRES_IN key should go before the JWT_SECRET key
(UnorderedKey)
[warning] 18-18: [ValueWithoutQuotes] This value needs to be surrounded in quotes
(ValueWithoutQuotes)
[warning] 19-19: [UnorderedKey] The SWAGGER_DESCRIPTION key should go before the SWAGGER_TITLE key
(UnorderedKey)
[warning] 19-19: [ValueWithoutQuotes] This value needs to be surrounded in quotes
(ValueWithoutQuotes)
🪛 markdownlint-cli2 (0.17.2)
README.md
5-5: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
10-10: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
23-23: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
31-31: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
37-37: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
43-43: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
65-65: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
81-81: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
91-91: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
103-103: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
108-108: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
🔇 Additional comments (6)
nest-cli.json (1)
5-9: Confirm CLI/builder alignment.If you keep webpack, ensure the repo includes the needed webpack configs/plugins; if you switch to swc, verify the local/global Nest CLI is v9+ and supports
"builder": "swc".package.json (1)
67-83: All unit tests reside under src; rootDir is correct — no.spec.tsfiles were found outside thesrc/directory, so Jest will run all intended tests.src/tasks/tasks.module.ts (2)
1-13: Wiring do módulo está correto.Import do repositório via
forFeature, controller, service e export funcionam conforme o esperado.
7-13: Remover exportação de TasksService se não for consumida externamente
TasksService não é referenciado fora de src/tasks/**; confirme manualmente antes de remover a exportação e reduzir a superfície pública do módulo.- exports: [TasksService], + // exports: [TasksService],src/app.module.ts (1)
9-20: Wiring geral do AppModule está consistente.Integra Config, Database e Tasks corretamente.
.env.example (1)
10-11: API_PREFIX format is correctmain.ts calls
setGlobalPrefix(apiPrefix)without a leading slash, and.env.exampledefinesAPI_PREFIX=api/v1accordingly.
| plugins: ['@typescript-eslint/eslint-plugin'], | ||
| extends: [ | ||
| '@typescript-eslint/recommended', | ||
| 'prettier', | ||
| ], |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Enable Prettier via ESLint properly and simplify plugin names.
You depend on eslint-plugin-prettier but don’t enable it; also plugin name for TS can be simplified.
- plugins: ['@typescript-eslint/eslint-plugin'],
- extends: [
- '@typescript-eslint/recommended',
- 'prettier',
- ],
+ plugins: ['@typescript-eslint', 'prettier'],
+ extends: [
+ 'plugin:@typescript-eslint/recommended',
+ 'plugin:prettier/recommended',
+ ],
...
- '@typescript-eslint/prefer-const': 'error',
- 'prefer-const': 'error',
+ '@typescript-eslint/prefer-const': 'error',
+ 'prettier/prettier': 'warn',Also applies to: 19-31
🤖 Prompt for AI Agents
In .eslintrc.js around lines 8-12 (also apply same change to lines 19-31): the
Prettier ESLint integration isn't enabled and the plugin name for TypeScript is
verbose; update the plugins entry to use the short package names (e.g.,
"@typescript-eslint" and "prettier") and enable Prettier via ESLint by adding
the recommended Prettier config to extends (for example
"plugin:prettier/recommended"), ensuring Prettier is invoked by ESLint and
format rules are disabled in favor of Prettier.
| "singleQuote": true, | ||
| "trailingComma": "all", | ||
| "tabWidth": 2, | ||
| "semi": true, | ||
| "printWidth": 100, | ||
| "bracketSpacing": true, | ||
| "arrowParens": "avoid" | ||
| } No newline at end of file |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add a .prettierignore to avoid formatting artifacts (dist, .next, coverage, env files).
Prevents unnecessary formatting passes and accidental edits of generated assets.
Here’s a recommended .prettierignore (new file):
dist
build
coverage
.next
out
node_modules
*.log
.env
.env.*
🤖 Prompt for AI Agents
In .prettierrc around lines 2 to 9: add a .prettierignore file at the repo root
to prevent formatting runs on generated and sensitive files; create
.prettierignore containing entries for dist, build, coverage, .next, out,
node_modules, *.log, .env and .env.* (one pattern per line) and commit it so
Prettier will skip these paths and avoid accidental formatting of build
artifacts and env files.
| postgres: | ||
| image: postgres:15 | ||
| container_name: to-do-list-api-postgres-api | ||
| restart: always | ||
| environment: | ||
| POSTGRES_DB: to-do-list-api | ||
| POSTGRES_USER: admin | ||
| POSTGRES_PASSWORD: admin123 | ||
| ports: | ||
| - '5432:5432' | ||
| volumes: | ||
| - postgres_data:/var/lib/postgresql/data | ||
| - ./init.sql:/docker-entrypoint-initdb.d/init.sql | ||
| networks: | ||
| - to-do-list-api-network | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add Postgres healthcheck so API can wait for readiness
Without a healthcheck, depends_on doesn’t guarantee DB readiness; migrations may fail on boot.
postgres:
image: postgres:15
container_name: to-do-list-api-postgres-api
restart: always
environment:
POSTGRES_DB: to-do-list-api
POSTGRES_USER: admin
POSTGRES_PASSWORD: admin123
ports:
- '5432:5432'
+ healthcheck:
+ test: ['CMD-SHELL', 'pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB']
+ interval: 10s
+ timeout: 5s
+ retries: 5
+ start_period: 10s
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
networks:
- to-do-list-api-network📝 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.
| postgres: | |
| image: postgres:15 | |
| container_name: to-do-list-api-postgres-api | |
| restart: always | |
| environment: | |
| POSTGRES_DB: to-do-list-api | |
| POSTGRES_USER: admin | |
| POSTGRES_PASSWORD: admin123 | |
| ports: | |
| - '5432:5432' | |
| volumes: | |
| - postgres_data:/var/lib/postgresql/data | |
| - ./init.sql:/docker-entrypoint-initdb.d/init.sql | |
| networks: | |
| - to-do-list-api-network | |
| postgres: | |
| image: postgres:15 | |
| container_name: to-do-list-api-postgres-api | |
| restart: always | |
| environment: | |
| POSTGRES_DB: to-do-list-api | |
| POSTGRES_USER: admin | |
| POSTGRES_PASSWORD: admin123 | |
| ports: | |
| - '5432:5432' | |
| healthcheck: | |
| test: ['CMD-SHELL', 'pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB'] | |
| interval: 10s | |
| timeout: 5s | |
| retries: 5 | |
| start_period: 10s | |
| volumes: | |
| - postgres_data:/var/lib/postgresql/data | |
| - ./init.sql:/docker-entrypoint-initdb.d/init.sql | |
| networks: | |
| - to-do-list-api-network |
🤖 Prompt for AI Agents
In docker-compose.yml around lines 2 to 17, the postgres service lacks a Docker
healthcheck so depends_on cannot wait for DB readiness; add a healthcheck block
using pg_isready (e.g. test: ["CMD-SHELL", "pg_isready -U admin -d
to-do-list-api || exit 1"]) with sensible interval (e.g. 10s), timeout (e.g.
5s), retries (e.g. 5) and an optional start_period (e.g. 30s); then update any
API service depends_on to use condition: service_healthy (or ensure the
orchestrator waits for the health status) so migrations run only after Postgres
is healthy.
| depends_on: | ||
| - postgres |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Wait for DB health before starting API
Use conditional depends_on to avoid race conditions.
-depends_on:
- - postgres
+depends_on:
+ postgres:
+ condition: service_healthy📝 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.
| depends_on: | |
| - postgres | |
| depends_on: | |
| postgres: | |
| condition: service_healthy |
🤖 Prompt for AI Agents
In docker-compose.yml around lines 35-36, the current depends_on simply lists
postgres which can cause race conditions; change it to use conditional
depends_on so the API waits for the DB to be healthy: add a healthcheck section
to the postgres service (command, interval, timeout, retries) and update the API
service depends_on to reference postgres with condition: service_healthy so
docker-compose will wait until the healthcheck passes before starting the API.
| ports: | ||
| - '3001:3001' |
There was a problem hiding this comment.
Port conflict between api and api-dev
Both expose 3001 on the host. Change dev to a different host port (e.g., 3334) or gate with profiles.
- - '3001:3001'
+ - '3334:3001'📝 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.
| ports: | |
| - '3001:3001' | |
| ports: | |
| - '3334:3001' |
🤖 Prompt for AI Agents
In docker-compose.yml around lines 46-47 the ports mapping '3001:3001' causes a
host port conflict with the api service; change the dev service host port to a
different value (for example '3334:3001') or alternatively gate the dev service
behind a compose profile (add profiles to the service and run with the profile)
so both services are not bound to the same host port simultaneously.
| async updateStatus( | ||
| @Param('id', ParseUUIDPipe) id: string, | ||
| @Body('status') status: TaskStatus, | ||
| ): Promise<TaskResponseDto> { | ||
| return await this.tasksService.updateStatus(id, status); | ||
| } |
There was a problem hiding this comment.
Validate status in body with ParseEnumPipe.
Prevents 500s from DB enum errors; returns 400 on invalid input.
async updateStatus(
@Param('id', ParseUUIDPipe) id: string,
- @Body('status') status: TaskStatus,
+ @Body('status', new ParseEnumPipe(TaskStatus)) status: TaskStatus,
): Promise<TaskResponseDto> {📝 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.
| async updateStatus( | |
| @Param('id', ParseUUIDPipe) id: string, | |
| @Body('status') status: TaskStatus, | |
| ): Promise<TaskResponseDto> { | |
| return await this.tasksService.updateStatus(id, status); | |
| } | |
| async updateStatus( | |
| @Param('id', ParseUUIDPipe) id: string, | |
| @Body('status', new ParseEnumPipe(TaskStatus)) status: TaskStatus, | |
| ): Promise<TaskResponseDto> { | |
| return await this.tasksService.updateStatus(id, status); | |
| } |
🤖 Prompt for AI Agents
In src/tasks/tasks.controller.ts around lines 179 to 184, the controller
currently accepts status from the request body without validating it against the
TaskStatus enum which can cause DB enum errors; update the method signature to
validate the incoming status using Nest's ParseEnumPipe (e.g., @Body('status',
new ParseEnumPipe(TaskStatus)) status: TaskStatus) and add the necessary import
for ParseEnumPipe so invalid enum values return a 400 instead of causing a 500.
| ...createTaskDto, | ||
| status: createTaskDto.status || TaskStatus.PENDING, | ||
| color: createTaskDto.color || '#3B82F6', | ||
| isFavorite: createTaskDto.isFavorite || false, | ||
| }); |
There was a problem hiding this comment.
Align default color with DTO contract.
DTO allows named colors; service defaults to a hex code. Pick one convention. If keeping names, default to 'blue'.
- color: createTaskDto.color || '#3B82F6',
+ color: createTaskDto.color || 'blue',Alternatively, update DTO to also accept hex (see DTO comment).
📝 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.
| ...createTaskDto, | |
| status: createTaskDto.status || TaskStatus.PENDING, | |
| color: createTaskDto.color || '#3B82F6', | |
| isFavorite: createTaskDto.isFavorite || false, | |
| }); | |
| ...createTaskDto, | |
| status: createTaskDto.status || TaskStatus.PENDING, | |
| color: createTaskDto.color || 'blue', | |
| isFavorite: createTaskDto.isFavorite || false, | |
| }); |
🤖 Prompt for AI Agents
In src/tasks/tasks.service.ts around lines 16 to 20, the service sets the
default color to a hex value ('#3B82F6') while the DTO contract allows named
colors; change the service to default to the named color 'blue' (i.e., replace
the hex default with 'blue') so it aligns with the DTO, and update any related
unit tests or usages that expect the hex value; alternatively, if you prefer hex
values, update the DTO type to accept hex strings and adjust validation
accordingly.
| async findAll( | ||
| page = 1, | ||
| limit = 10, | ||
| status?: TaskStatus, | ||
| isFavorite?: boolean, | ||
| search?: string, | ||
| ): Promise<{ tasks: Task[]; total: number; totalPages: number }> { | ||
| const skip = (page - 1) * limit; | ||
| const where: FindOptionsWhere<Task> = {}; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Clamp pagination inputs and avoid divide-by-zero.
Protect against page < 1 and limit <= 0; cap limit (e.g., 100).
- async findAll(
+ async findAll(
page = 1,
limit = 10,
status?: TaskStatus,
isFavorite?: boolean,
search?: string,
): Promise<{ tasks: Task[]; total: number; totalPages: number }> {
- const skip = (page - 1) * limit;
+ const safePage = Math.max(1, Number(page) || 1);
+ const safeLimit = Math.min(Math.max(1, Number(limit) || 10), 100);
+ const skip = (safePage - 1) * safeLimit;
const where: FindOptionsWhere<Task> = {};
@@
- const [tasks, total] = await queryBuilder
+ const [tasks, total] = await queryBuilder
.orderBy('task.createdAt', 'DESC')
- .skip(skip)
- .take(limit)
+ .skip(skip)
+ .take(safeLimit)
.getManyAndCount();
-
- const totalPages = Math.ceil(total / limit);
+ const totalPages = Math.ceil(total / safeLimit);Note: Consider returning safePage/safeLimit so the controller can echo sanitized values.
Also applies to: 64-71
🤖 Prompt for AI Agents
In src/tasks/tasks.service.ts around lines 25 to 33, the pagination inputs are
not validated causing page < 1 or limit <= 0 and potential divide-by-zero; clamp
page to a minimum of 1 and limit to a range of 1..100 (or a defined MAX_LIMIT)
before using them (e.g., const safePage = Math.max(1, page); const safeLimit =
Math.min(MAX_LIMIT, Math.max(1, limit))); use safePage/safeLimit for skip
calculation and query limits and when computing totalPages guard division by
zero (e.g., Math.ceil(total / safeLimit)); return or expose safePage/safeLimit
so the controller can echo sanitized values; apply the same fixes to the similar
block at lines 64-71.
| "outDir": "build", | ||
| "rootDir": "./", | ||
| "module": "commonjs", | ||
| "declaration": true, |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Don’t emit type declarations for an app build.
"declaration": true slows builds and clutters dist with .d.ts—keep it for libs, not services.
- "declaration": true,
+ "declaration": false,📝 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.
| "declaration": true, | |
| "declaration": false, |
🤖 Prompt for AI Agents
In tsconfig.json around line 4, the project currently emits type declaration
files which are unnecessary for an application; set "declaration" to false (or
remove the property) so build won't generate .d.ts files and slow the build—keep
declaration generation only in library-specific tsconfig if needed.
| "strictNullChecks": false, | ||
| "noImplicitAny": false, | ||
| "strictBindCallApply": false, | ||
| "forceConsistentCasingInFileNames": false, | ||
| "noFallthroughCasesInSwitch": false, |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Re-enable strict typing; current config hides bugs (nullability, implicit any, casing).
At minimum, enable strict, strictNullChecks, and noImplicitAny. Keep skipLibCheck if build time matters.
- "skipLibCheck": true,
- "strictNullChecks": false,
- "noImplicitAny": false,
- "strictBindCallApply": false,
- "forceConsistentCasingInFileNames": false,
+ "skipLibCheck": true,
+ "strict": true,
+ "strictNullChecks": true,
+ "noImplicitAny": true,
+ "strictBindCallApply": true,
+ "forceConsistentCasingInFileNames": true,Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In tsconfig.json around lines 15-19, the TypeScript config currently disables
strict typing; set "strict": true, "strictNullChecks": true, and
"noImplicitAny": true to re-enable strict type checks (this will catch
nullability and implicit any issues). Keep "skipLibCheck" as-is if build time is
a concern; also enable "forceConsistentCasingInFileNames": true to avoid casing
issues across files, and remove or stop overriding strict-related flags that
contradict "strict": true so the compiler uses the full strict mode.
🚀Descrição da Entrega
🔍 Principais funcionalidades:
✅ Esta versão consolida a base do projeto, garantindo uma aplicação funcional, integrando back-end e front-end, pronta para evoluções futuras.
Summary by CodeRabbit
New Features
Documentation
Chores