Skip to content

Entrega final do desafio técnico - corelab-api-challenge#76

Open
DavidBotelhoo wants to merge 2 commits into
corelabbr:mainfrom
DavidBotelhoo:main
Open

Entrega final do desafio técnico - corelab-api-challenge#76
DavidBotelhoo wants to merge 2 commits into
corelabbr:mainfrom
DavidBotelhoo:main

Conversation

@DavidBotelhoo

@DavidBotelhoo DavidBotelhoo commented Aug 29, 2025

Copy link
Copy Markdown

🚀Descrição da Entrega

  • Este PR entrega a versão funcional da Core Notes, composta por:
  • Back-end (NestJS + PostgreSQL): CRUD completo de tarefas (listar, criar, atualizar, excluir, favoritar), validações via DTOs e documentação com Swagger.
  • Front-end (Next.js + Tailwind): página principal estruturada (header → busca → criação → favoritas → outras), componentes reutilizáveis e integração direta com a API.
  • Infraestrutura: Dockerfiles para dev/prod, docker-compose para orquestração (API + DB + Web), .env configuráveis e scripts de execução.

🔍 Principais funcionalidades:

  • Criar, buscar, editar e excluir tarefas.
  • Marcar/desmarcar como favoritas.
  • Listagem dividida em favoritas e demais tarefas.
  • Feedbacks de carregamento e erro.

✅ 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

    • Introduced a NestJS-based To-Do List API with CRUD, pagination, search, status updates, and favorite toggling.
    • Added health check endpoint and interactive API docs via Swagger at /api/v1/docs.
    • Provided Docker and Docker Compose support with PostgreSQL, plus environment variable configuration and initial DB seed.
  • Documentation

    • Rewrote README with setup, endpoints, and environment guidance; added detailed PR template.
  • Chores

    • Migrated from legacy framework, cleaned up obsolete files/routes, and added linting/formatting configs and CLI settings.

@coderabbitai

coderabbitai Bot commented Aug 29, 2025

Copy link
Copy Markdown

Walkthrough

Replaces 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

Cohort / File(s) Summary of Changes
Framework migration: AdonisJS removal
server.ts, ace, ace-manifest.json, .adonisrc.json, env.ts, start/*, app/*, config/*, contracts/*, commands/index.ts, providers/AppProvider.ts, tests/**/*, test.ts
Removed AdonisJS bootstrap, CLI/manifest, env validation, middleware/routes, controllers/types, configs (app, bodyparser, cors, drive, hash), IoC contracts, provider, and Japa tests.
NestJS application setup
src/main.ts, src/app.module.ts, src/app.controller.ts, src/app.service.ts
Added NestJS bootstrap with CORS, validation, global prefix, Swagger docs, health endpoint, and AppModule wiring.
Tasks feature (NestJS + TypeORM)
src/tasks/* (entities/task.entity.ts, dto/task.dto.ts, tasks.module.ts, tasks.service.ts, tasks.controller.ts)
Implemented Task entity (enum-backed status), DTOs, service (CRUD, search, pagination, stats, favorite toggle), controller (REST endpoints with Swagger).
Database integration
src/database/database.module.ts, init.sql
Added TypeORM DatabaseModule (Postgres via env), migrations config, and SQL init (enum, table, indexes, trigger, seed).
Project configuration
package.json, tsconfig.json, nest-cli.json
Switched to NestJS dependencies/scripts, Jest config, TypeORM scripts, updated compiler options, paths, dist outDir, and Nest CLI config.
Environment & tooling
.env, .env.example, .eslintrc.js, .prettierrc, .prettierignore, .editorconfig
Added env files (DB, app, JWT, Swagger). Introduced ESLint/Prettier configs; removed EditorConfig; cleared Prettier ignore.
Containerization
Dockerfile, Dockerfile.dev, docker-compose.yml
Added multi-stage runtime Dockerfile, dev Dockerfile, and Compose stack (Postgres, API, API dev) with volumes and env wiring.
Documentation
README.md, PULL_REQUEST.md, Leiame.md
Replaced challenge brief with project docs; added PR guide; removed previous brief.
Ignore rules
.gitignore, .gitignore copy
Simplified .gitignore to only node_modules; removed patterns in the copy.

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
Loading
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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

In burrows of code, I thump with delight,
Adonis hops out, Nest takes flight.
Tasks sprout neatly, enums in row,
Swagger blooms where APIs grow.
Containers hum, SQL seeds the ground—
Carrot approved: robust and sound. 🥕✨

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 Compose

Secrets 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: Prefer arrowParens: "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-off init.sql for 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 Desenvolvimento

Also 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 compose consistently; avoid mixing with docker-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.project enables 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 pgcrypto and gen_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=development

Arquivo extra (.dockerignore):

node_modules
dist
.git
Dockerfile*
docker-compose*.yml
.env*
coverage
src/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/terminus com TypeOrmHealthIndicator se quiser.

.env.example (5)

18-20: Quote Swagger values to satisfy dotenv-linter and avoid parsing surprises

Values 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-linter

No 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_NAME

Postgres 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 name

Same 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 only

Keeps 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 startup

Prevents 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=admin123
src/database/database.module.ts (2)

17-19: Prefer auto-load entities and drop hard-coded list

Reduces maintenance when adding entities.

-        entities: [Task],
+        autoLoadEntities: true,

Also remove the unused import:

-import { Task } from '../tasks/entities/task.entity';

11-19: Optional: production hardening

Consider 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.

📥 Commits

Reviewing files that changed from the base of the PR and between b174fe6 and b481645.

⛔ Files ignored due to path filters (2)
  • dist/main.js is excluded by !**/dist/**
  • package-lock.json is 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.ts files were found outside the src/ 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 correct

main.ts calls setGlobalPrefix(apiPrefix) without a leading slash, and .env.example defines API_PREFIX=api/v1 accordingly.

Comment thread .eslintrc.js
Comment on lines +8 to +12
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'@typescript-eslint/recommended',
'prettier',
],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Comment thread .prettierrc
Comment on lines +2 to +9
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"printWidth": 100,
"bracketSpacing": true,
"arrowParens": "avoid"
} No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Comment thread docker-compose.yml
Comment on lines +2 to +17
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
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.

Comment thread docker-compose.yml
Comment on lines +35 to +36
depends_on:
- postgres

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
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.

Comment thread docker-compose.yml
Comment on lines +46 to +47
ports:
- '3001:3001'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines +179 to +184
async updateStatus(
@Param('id', ParseUUIDPipe) id: string,
@Body('status') status: TaskStatus,
): Promise<TaskResponseDto> {
return await this.tasksService.updateStatus(id, status);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines +16 to +20
...createTaskDto,
status: createTaskDto.status || TaskStatus.PENDING,
color: createTaskDto.color || '#3B82F6',
isFavorite: createTaskDto.isFavorite || false,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
...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.

Comment on lines +25 to +33
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> = {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Comment thread tsconfig.json
"outDir": "build",
"rootDir": "./",
"module": "commonjs",
"declaration": true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
"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.

Comment thread tsconfig.json
Comment on lines +15 to +19
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

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