Skip to content

Solucao desafio corelab#74

Open
Lucas-d-Barbosa wants to merge 7 commits into
corelabbr:mainfrom
Lucas-d-Barbosa:solucao-desafio-corelab
Open

Solucao desafio corelab#74
Lucas-d-Barbosa wants to merge 7 commits into
corelabbr:mainfrom
Lucas-d-Barbosa:solucao-desafio-corelab

Conversation

@Lucas-d-Barbosa

@Lucas-d-Barbosa Lucas-d-Barbosa commented Jul 15, 2025

Copy link
Copy Markdown

Solução do Desafio Corelab: Aplicação de Notas (CoreNotes)

Olá, equipe Corelab!

Este Pull Request contém a minha solução completa para o Desafio de Lista de Tarefas. Foi um projeto extremamente divertido e desafiador de construir, no qual busquei não apenas cumprir os requisitos, mas também aplicar boas práticas de arquitetura e desenvolvimento.


Funcionalidades Implementadas

Todas as funcionalidades solicitadas no desafio foram implementadas:

  • CRUD Completo: As notas podem ser criadas, lidas, atualizadas e deletadas, com todas as ações persistidas no banco de dados através da API.
  • Sistema de Favoritos: É possível marcar notas como favoritas, e elas são automaticamente exibidas no topo da lista para fácil acesso.
  • Cores para Notas: O usuário pode atribuir uma cor específica para cada nota através de uma paleta interativa.
  • Busca em Tempo Real: A lista de notas é filtrada instantaneamente conforme o usuário digita no campo de busca.
  • Filtro por Cor: O usuário pode filtrar as notas para exibir apenas aquelas de uma cor específica.
  • Responsividade: O layout foi construído seguindo a abordagem "Mobile First" e se adapta de forma fluida a telas de desktop.

🛠️ Tecnologias e Arquitetura

Para a construção do projeto, fiz as seguintes escolhas tecnológicas:

  • Back-end (AdonisJS + Prisma): Escolhi o AdonisJS pela sua estrutura organizada e o Prisma pela sua excelente integração com o TypeScript, garantindo segurança de tipos na comunicação com o banco de dados (SQLite).

  • Front-end (React + TypeScript + Sass): Utilizei React para uma UI reativa e componentizada, TypeScript para qualidade e manutenibilidade, e Sass (SCSS) para uma estilização mais organizada.

  • Padrão de Projeto (Adapter): Para as notificações, implementei o padrão Adapter, desacoplando a aplicação da biblioteca react-toastify e criando um NotificationService reutilizável.

  • Otimização de Performance: A lógica de filtragem no front-end foi otimizada com o hook useMemo para evitar cálculos desnecessários.


✨ Destaques e Itens "Para Impressionar"

  • Dockerização Completa: A aplicação inteira (front-end e back-end) foi containerizada com Docker e orquestrada com docker-compose. Isso permite que qualquer pessoa execute o projeto completo com um único comando.

  • Qualidade de Código: Foco em um código limpo, componentizado e na aplicação de padrões de projeto para garantir a manutenibilidade e escalabilidade.


🚀 Como Executar

Existem duas maneiras de rodar esta aplicação: com Docker (método recomendado) ou localmente.

Rodando com Docker (Recomendado)

Pré-requisitos:

  • Docker Desktop instalado e rodando.

Passos:

  1. Clone os dois repositórios (corelab-web-challenge e corelab-api-challenge) para dentro da mesma pasta pai.

    your-main-folder/
    ├── corelab-api-challenge/
    └── corelab-web-challenge/
    
  2. Na raiz desta pasta principal, crie um arquivo chamado docker-compose.yml com o seguinte conteúdo:

    version: '3.8'
    services:
      backend:
        build: ./corelab-api-challenge
        container_name: corelab-api
        ports:
          - '3333:3333'
        volumes:
          - ./corelab-api-challenge:/app
          - /app/node_modules
        environment:
          - DATABASE_URL=file:./dev.db
      frontend:
        build: ./corelab-web-challenge
        container_name: corelab-web
        ports:
          - '3000:3000'
        volumes:
          - ./corelab-web-challenge:/app
          - /app/node_modules
        depends_on:
          - backend
  3. No terminal, a partir da pasta raiz, execute:

    docker compose up --build
  4. Acesse a aplicação em http://localhost:3000.

Rodando Localmente (Sem Docker)

Pré-requisitos:

  • Node.js v16.15.0
  • NPM v8.5.5

Backend:

  1. Navegue até a pasta corelab-api-challenge.
  2. Rode os comandos: npm install, cp .env.example .env, node ace generate:key, npx prisma migrate dev, e finalmente npm run dev.

Frontend:

  1. Em um novo terminal, navegue até a pasta corelab-web-challenge.
  2. Rode os comandos: npm install e npm start.

🎬 Demonstração

https://drive.google.com/file/d/1ds5InIWwT7Omxl1yimCLB4tGqypnmNIa/view?usp=sharing

Agradeço a oportunidade de participar do desafio. Estou à disposição para qualquer dúvida.

Summary by CodeRabbit

  • New Features

    • Introduced full CRUD operations for notes, including creation, listing (with favorites prioritized), updating, and deletion.
    • Added color assignment and favorites support for notes.
    • Implemented RESTful API endpoints for managing notes.
  • Documentation

    • Expanded and reorganized the README with setup instructions and API documentation.
    • Added a detailed project description and setup guide in a new PULL_REQUEST.md file.
  • Chores

    • Added Dockerfile for easy containerized deployment.
    • Integrated Prisma ORM and database schema for notes.
    • Updated package dependencies to include Prisma.
    • Configured initial database migrations and schema.
    • Restricted CORS settings to allow only specific origins and HTTP methods.

@coderabbitai

coderabbitai Bot commented Jul 15, 2025

Copy link
Copy Markdown

Walkthrough

This update introduces a backend API for managing notes, including full CRUD operations, using AdonisJS with Prisma and SQLite. It adds a Dockerfile for containerization, expands documentation with setup and API details, and configures CORS. The Prisma schema and migration define the Note model, and new routes and controllers implement the API endpoints.

Changes

File(s) Change Summary
.env.example Added a single trailing newline at the end of the file.
Dockerfile Added a new Dockerfile for Node.js application containerization with Prisma setup and app startup instructions.
PULL_REQUEST.md Added a comprehensive project solution description, features, tech stack, and setup instructions.
README.md Expanded with setup instructions, Docker usage, API endpoint documentation, and formatting improvements.
app/Controllers/NotesController.ts Added NotesController class implementing CRUD operations for notes using Prisma.
app/database/prismaClient.ts Added a module exporting a singleton Prisma client instance for app-wide DB access.
config/cors.ts Restricted CORS to http://localhost:3000 and updated allowed HTTP methods.
package.json Added @prisma/client and prisma packages to dependencies and devDependencies.
prisma/schema.prisma Added Prisma schema defining the Note model and SQLite datasource configuration.
prisma/migrations/20250714181039_init/migration.sql Added migration creating the Note table with all required fields and constraints.
prisma/migrations/migration_lock.toml Added migration lock file specifying SQLite as the provider.
start/routes.ts Added RESTful routes for notes resource and a root GET route returning a hello world JSON.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant NotesController
    participant PrismaClient
    Client->>Router: HTTP request (GET/POST/PATCH/DELETE /notes)
    Router->>NotesController: Route handler invocation
    NotesController->>PrismaClient: DB operation (find, create, update, delete)
    PrismaClient-->>NotesController: Query result / error
    NotesController-->>Router: Response data / error
    Router-->>Client: HTTP response
Loading

Poem

🐇
A note-taking warren, now neat and complete,
With Prisma and Docker, our backend’s a treat!
CRUD hops along, with routes all in tow,
Colors and favorites, in schema they grow.
Docs guide the way, as migrations take root—
The rabbit is proud, and the code is cute!

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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

Documentation and Community

  • 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: 8

🧹 Nitpick comments (12)
app/database/prismaClient.ts (1)

1-3: Consider adding proper client lifecycle management.

The centralized Prisma client instance is a good pattern. However, consider adding proper disconnect handling for production environments to prevent connection leaks.

Consider adding a cleanup function for graceful shutdown:

 import { PrismaClient } from '@prisma/client'

 export const prisma = new PrismaClient()
+
+// Graceful shutdown handler
+process.on('SIGINT', async () => {
+  await prisma.$disconnect()
+  process.exit(0)
+})
+
+process.on('SIGTERM', async () => {
+  await prisma.$disconnect()
+  process.exit(0)
+})

Alternatively, handle disconnect in your main application shutdown logic.

start/routes.ts (1)

24-26: Consider removing or securing the debug root route.

The root route returning { hello: 'world' } appears to be a debug or test endpoint. Consider removing it from production or adding proper API versioning.

-Route.get('/', async () => {
-  return { hello: 'world' }
-})
+Route.get('/', async () => {
+  return { 
+    name: 'CoreNotes API',
+    version: '1.0.0',
+    status: 'healthy'
+  }
+})
Dockerfile (2)

1-1: Consider using a more recent Node.js version.

Node.js 16.15.0 is approaching end-of-life. Consider upgrading to a more recent LTS version for better security and performance.

-FROM node:16.15.0-alpine
+FROM node:18-alpine

15-15: Consider adding a non-root user for security.

For better security practices, consider running the application as a non-root user inside the container.

+RUN addgroup -g 1001 -S nodejs
+RUN adduser -S nodejs -u 1001
+
+USER nodejs
+
 CMD ["npm", "run", "dev"]
prisma/migrations/20250714181039_init/migration.sql (1)

6-6: Consider adding validation for color format.

The color field defaults to '#FFFFFF' but lacks format validation. Consider adding a CHECK constraint to ensure valid hex color codes.

-    "color" TEXT NOT NULL DEFAULT '#FFFFFF',
+    "color" TEXT NOT NULL DEFAULT '#FFFFFF' CHECK (color LIKE '#%' AND length(color) = 7),
prisma/schema.prisma (1)

14-14: Consider consistency in comment language.

The Portuguese comment is helpful but consider using English for consistency with the rest of the codebase or standardizing all comments in Portuguese.

-  id         Int      @id @default(autoincrement()) // ID único que se auto-incrementa
+  id         Int      @id @default(autoincrement()) // Unique auto-incrementing ID
PULL_REQUEST.md (3)

1-1: Fix markdown heading punctuation.

Remove the trailing colon from the heading as per markdown best practices.

-## Solução do Desafio Corelab: Aplicação de Notas (CoreNotes)
+## Solução do Desafio Corelab - Aplicação de Notas (CoreNotes)

32-32: Consider using Portuguese equivalent for "Performance".

The static analysis tool suggests using "desempenho" instead of "Performance" for better Portuguese language consistency.

-- **Otimização de Performance:** A lógica de filtragem no front-end foi otimizada com o hook `useMemo` para evitar cálculos desnecessários.
+- **Otimização de Desempenho:** A lógica de filtragem no front-end foi otimizada com o hook `useMemo` para evitar cálculos desnecessários.

107-107: Add language specification to code block.

The static analysis tool suggests adding a language specification to the code block for better rendering.

-2.  Rode os comandos: `npm install`, `cp .env.example .env`, `node ace generate:key`, `npx prisma migrate dev`, e finalmente `npm run dev`.
+2.  Rode os comandos: 
+    ```bash
+    npm install
+    cp .env.example .env
+    node ace generate:key
+    npx prisma migrate dev
+    npm run dev
+    ```
app/Controllers/NotesController.ts (3)

14-16: Language inconsistency in error messages.

The error messages are in Portuguese while the README and other documentation are in English. Consider maintaining consistency by using English error messages throughout the application.

-        return response.status(400).json({ error: 'O título é obrigatório.' })
+        return response.status(400).json({ error: 'Title is required.' })

62-62: Remove unused request parameter.

The request parameter is destructured but never used in the destroy method. Consider removing it to keep the code clean.

-  public async destroy({ params, response, request }: HttpContextContract) {
+  public async destroy({ params, response }: HttpContextContract) {

1-75: Consider adding request validation middleware.

The controller would benefit from a validation middleware to handle input validation consistently across all methods, reducing code duplication and improving maintainability.

Consider implementing a validation middleware or using AdonisJS validators to handle input validation centrally. This would provide:

  • Consistent validation rules
  • Better error messages
  • Reduced code duplication
  • Type safety improvements
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 328ccdd and 65d4f5c.

⛔ Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json
  • prisma/dev.db is excluded by !**/*.db
📒 Files selected for processing (12)
  • .env.example (1 hunks)
  • Dockerfile (1 hunks)
  • PULL_REQUEST.md (1 hunks)
  • README.md (5 hunks)
  • app/Controllers/NotesController.ts (1 hunks)
  • app/database/prismaClient.ts (1 hunks)
  • config/cors.ts (2 hunks)
  • package.json (1 hunks)
  • prisma/migrations/20250714181039_init/migration.sql (1 hunks)
  • prisma/migrations/migration_lock.toml (1 hunks)
  • prisma/schema.prisma (1 hunks)
  • start/routes.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
.env.example (1)
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.
Dockerfile (1)
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.
🧬 Code Graph Analysis (1)
app/Controllers/NotesController.ts (1)
app/database/prismaClient.ts (1)
  • prisma (3-3)
🪛 LanguageTool
PULL_REQUEST.md

[style] ~15-~15: Para conferir mais clareza ao seu texto, busque usar uma linguagem mais concisa.
Context: ...ibuir uma cor específica para cada nota através de uma paleta interativa. - [x] **Busca em...

(ATRAVES_DE_POR_VIA)


[locale-violation] ~32-~32: “Performance” é um estrangeirismo. É preferível dizer “desempenho”, “atuação”, “apresentação”, “espetáculo” ou “interpretação”.
Context: ...rvice` reutilizável. - Otimização de Performance: A lógica de filtragem no front-end f...

(PT_BARBARISMS_REPLACE_PERFORMANCE)


[inconsistency] ~95-~95: 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: ...build ``` 4. Acesse a aplicação emhttp://localhost:3000`. #### Rodando Localmente (Sem Docker) ...

(URL_VALIDATION)


[uncategorized] ~107-~107: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: .... 2. Rode os comandos: npm install, cp .env.example .env, node ace generate:...

(ABREVIATIONS_PUNCTUATION)

🪛 markdownlint-cli2 (0.17.2)
PULL_REQUEST.md

1-1: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


19-19: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


27-27: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


33-33: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


38-38: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


109-109: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (16)
.env.example (1)

6-6: LGTM: Good formatting practice.

Adding a trailing newline aligns with Unix/Linux conventions and common coding standards.

prisma/migrations/migration_lock.toml (1)

1-3: LGTM: Properly configured Prisma migration lock file.

The migration lock file is correctly configured for SQLite provider and should remain unmodified as it's auto-generated by Prisma CLI.

config/cors.ts (2)

47-47: LGTM: Appropriate CORS origin restriction for development.

Restricting the origin to localhost:3000 is a good security practice for development environments.

Ensure that production deployment will update this origin configuration to match the actual frontend domain.


59-59: Confirmed: API routes use only GET, POST, PATCH, and DELETE

All route definitions in start/routes.ts adhere to the allowed HTTP methods configured in config/cors.ts. No unsupported methods (e.g., PUT, HEAD) were found.

No further changes required.

start/routes.ts (1)

27-30: LGTM: RESTful route structure is well-designed.

The notes routes follow proper RESTful conventions with appropriate HTTP methods for CRUD operations.

Dockerfile (2)

5-9: Good practice: Optimized layer caching.

The Dockerfile correctly separates package file copying from source code copying, which optimizes Docker layer caching during builds.


11-11: Ensure Prisma client generation is necessary in container.

The prisma generate command is required since the Prisma client needs to be generated based on the schema for the application to function properly.

prisma/migrations/20250714181039_init/migration.sql (1)

2-10: Well-designed table schema with appropriate constraints.

The Note table schema is well-designed with:

  • Auto-incrementing primary key
  • Proper data types for each field
  • Sensible default values for color and favorite status
  • Timestamps for audit trail
prisma/schema.prisma (3)

4-6: LGTM: Standard Prisma client configuration.

The Prisma client generator configuration is correct and follows standard practices.


8-11: LGTM: Appropriate SQLite datasource configuration.

The SQLite datasource configuration with environment variable for database URL is appropriate for the application requirements.


13-22: Well-designed Note model with proper Prisma decorators.

The Note model is well-structured with:

  • Appropriate field types and constraints
  • Sensible default values
  • Proper use of Prisma decorators
  • Audit fields for tracking changes
PULL_REQUEST.md (2)

66-89: Comprehensive Docker setup instructions.

The Docker Compose configuration and setup instructions are thorough and well-documented, making it easy for others to run the application.


104-112: Complete local development setup instructions.

The local development setup instructions are clear and include all necessary steps for running both backend and frontend services.

README.md (3)

117-142: Docker Compose configuration looks well-structured.

The Docker setup is comprehensive and includes proper volume mapping, environment variables, and service dependencies. The structure supports both development and production workflows effectively.


173-215: API documentation is comprehensive and accurate.

The API endpoints documentation correctly describes the CRUD operations implemented in the NotesController, including proper HTTP methods, request/response formats, and status codes. The documentation aligns well with the actual implementation.


157-164: Confirmed migration files present for Prisma

The migration command npx prisma migrate dev will work as expected since migration files are committed:

  • prisma/migrations/20250714181039_init/migration.sql

No further action required.

Comment thread package.json
"eslint-plugin-prettier": "^4.0.0",
"pino-pretty": "^7.6.1",
"prettier": "^2.6.2",
"prisma": "^5.22.0",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify Prisma version is current and secure.

The Prisma dependencies are correctly placed - CLI tool in devDependencies and client in dependencies. The version consistency is good.

Please verify that Prisma version 5.22.0 is current and free from known security vulnerabilities:

Also applies to: 60-60


🌐 Web query:

What is the latest stable version of Prisma and are there any known security vulnerabilities in version 5.22.0?

💡 Result:

As of July 15, 2025, the latest stable version of Prisma ORM is 6.11.1, released on July 3, 2025. (github.com)

Regarding version 5.22.0, released on November 5, 2024, there are no direct vulnerabilities reported for this version in Snyk's database. (security.snyk.io)

However, it's important to note that Prisma ORM 5.22.0 is an older release, and using the latest stable version is recommended to benefit from the most recent features, improvements, and security patches.

Citations:


Upgrade Prisma dependencies to the latest stable version

The project currently pins both prisma and @prisma/client at ^5.22.0, which has no known vulnerabilities but is outdated. Prisma 6.11.1 (released July 3, 2025) is the latest stable release and includes new features, bug fixes, and security patches.

• package.json (devDependencies): update

- "prisma": "^5.22.0",
+ "prisma": "^6.11.1",

• package.json (dependencies): update

- "@prisma/client": "^5.22.0",
+ "@prisma/client": "^6.11.1",
🤖 Prompt for AI Agents
In package.json at line 52, update the version of "prisma" from "^5.22.0" to
"^6.11.1" to use the latest stable release. Also, locate the "@prisma/client"
dependency and update its version to "^6.11.1" to keep both Prisma packages
consistent and up to date.

Comment thread start/routes.ts
Comment on lines +27 to +30
Route.post('/notes', 'NotesController.store')
Route.get('/notes', 'NotesController.index')
Route.patch('/notes/:id', 'NotesController.update')
Route.delete('/notes/:id', 'NotesController.destroy')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider adding input validation and authentication middleware.

The notes routes lack explicit input validation and authentication. Ensure these are handled in the controller or consider adding middleware for security.


🏁 Script executed:

#!/bin/bash
# Check if there's authentication middleware or validation in the NotesController
ast-grep --pattern $'export default class NotesController {
  $$$
}'

Length of output: 4706


🏁 Script executed:

#!/bin/bash
# Check for middleware usage in the notes routes
rg -n "notes" -n "middleware" start/routes.ts

Length of output: 367


🏁 Script executed:

#!/bin/bash
# Verify if routes are wrapped in a group with authentication middleware
rg -n "Route\.group" start/routes.ts

# Check for any middleware attached to individual routes
rg -n "middleware" start/routes.ts

Length of output: 73


Add authentication and structured input validation to notes routes

The /notes endpoints currently lack auth protection and rely on ad-hoc checks in the controller. To harden security and ensure consistent payloads:

• In start/routes.ts, wrap all notes routes in an auth middleware group:

- Route.post('/notes', 'NotesController.store')
- Route.get('/notes', 'NotesController.index')
- Route.patch('/notes/:id', 'NotesController.update')
- Route.delete('/notes/:id', 'NotesController.destroy')
+ Route.group(() => {
+   Route.post('/notes', 'NotesController.store')
+   Route.get('/notes', 'NotesController.index')
+   Route.patch('/notes/:id', 'NotesController.update')
+   Route.delete('/notes/:id', 'NotesController.destroy')
+ }).middleware('auth')

• Create validators under app/Validators:
– StoreNoteValidator.ts (rules for title, content, isFavorite, color)
– UpdateNoteValidator.ts (same or partial rules)

• In NotesController.store/update, replace manual request.only + if (!title) checks with:

import StoreNoteValidator from 'App/Validators/StoreNoteValidator'

public async store({ request, response }: HttpContextContract) {
  const payload = await request.validate(StoreNoteValidator)
  const note = await prisma.note.create({ data: payload })
  return response.created(note)
}

(and similarly for update with UpdateNoteValidator)

This ensures only authenticated users can access these routes and that all inputs conform to a defined schema.

🤖 Prompt for AI Agents
In start/routes.ts around lines 27 to 30, the notes routes lack authentication
and structured input validation. Wrap all notes routes in an authentication
middleware group to restrict access to authenticated users. Create
StoreNoteValidator.ts and UpdateNoteValidator.ts in app/Validators with rules
for title, content, isFavorite, and color. In NotesController.store and update
methods, replace manual request.only and conditional checks with
request.validate using the respective validators to enforce consistent payload
validation.

Comment on lines +18 to +25
const note = await prisma.note.create({
data: {
title,
content,
isFavorite,
color,
},
})

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

Missing input validation for optional fields.

While the title validation is present, there's no validation for other fields like color format (should be hex), or content length limits. Consider adding comprehensive input validation.

+      // Validate color format if provided
+      if (color && !/^#[0-9A-F]{6}$/i.test(color)) {
+        return response.status(400).json({ error: 'Color must be a valid hex format.' })
+      }
+
+      // Validate content length if provided
+      if (content && content.length > 1000) {
+        return response.status(400).json({ error: 'Content must be less than 1000 characters.' })
+      }
📝 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
const note = await prisma.note.create({
data: {
title,
content,
isFavorite,
color,
},
})
// Validate color format if provided
if (color && !/^#[0-9A-F]{6}$/i.test(color)) {
return response.status(400).json({ error: 'Color must be a valid hex format.' })
}
// Validate content length if provided
if (content && content.length > 1000) {
return response.status(400).json({ error: 'Content must be less than 1000 characters.' })
}
const note = await prisma.note.create({
data: {
title,
content,
isFavorite,
color,
},
})
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts around lines 18 to 25, the code creates a
note without validating optional fields such as color and content. Add
validation to ensure the color field matches a hex color format and enforce
length limits on the content field before creating the note. This can be done by
adding checks or using a validation library to verify these constraints and
returning errors if validation fails.

Comment on lines +28 to +30
} catch (error) {
return response.internalServerError({ message: 'Não foi possível criar a nota.' })
}

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

Improve error handling specificity.

The generic error handling doesn't provide specific information about what went wrong. Consider logging the actual error and providing more specific error messages based on the error type.

    } catch (error) {
+      console.error('Error creating note:', error)
+      
+      // Handle specific Prisma errors
+      if (error.code === 'P2002') {
+        return response.status(409).json({ message: 'Note with this title already exists.' })
+      }
+      
       return response.internalServerError({ message: 'Não foi possível criar a nota.' })
     }
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts around lines 28 to 30, the catch block
returns a generic error message without logging the actual error or
differentiating error types. Modify the catch block to log the caught error for
debugging purposes and enhance the response by checking the error type or
properties to return more specific and informative error messages to the client.

public async update({ params, response, request }: HttpContextContract) {
try {
const noteId = params.id
const updateDate = request.only(['title', 'content', 'isFavorite', 'color'])

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

Fix variable name typo.

The variable name updateDate should be updateData as it contains update data, not a date.

-      const updateDate = request.only(['title', 'content', 'isFavorite', 'color'])
+      const updateData = request.only(['title', 'content', 'isFavorite', 'color'])

And update the usage:

-        data: updateDate,
+        data: updateData,
📝 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
const updateDate = request.only(['title', 'content', 'isFavorite', 'color'])
const updateData = request.only(['title', 'content', 'isFavorite', 'color'])
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts at line 49, rename the variable
`updateDate` to `updateData` to correctly reflect that it holds update
information, not a date. Also, update all subsequent references to this variable
in the method to use `updateData` instead of `updateDate`.

Comment on lines +50 to +59
const note = await prisma.note.update({
where: {
id: Number(noteId),
},
data: updateDate,
})
return response.ok(note)
} catch (error) {
return response.internalServerError({ message: 'Não foi possível atualizar a nota' })
}

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

Consider handling note not found scenario.

Prisma will throw an error if the note doesn't exist during update. Consider catching this specific case and returning a 404 response instead of a 500 error.

    } catch (error) {
+      if (error.code === 'P2025') {
+        return response.status(404).json({ message: 'Note not found.' })
+      }
+      
       return response.internalServerError({ message: 'Não foi possível atualizar a nota' })
     }
📝 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
const note = await prisma.note.update({
where: {
id: Number(noteId),
},
data: updateDate,
})
return response.ok(note)
} catch (error) {
return response.internalServerError({ message: 'Não foi possível atualizar a nota' })
}
const note = await prisma.note.update({
where: {
id: Number(noteId),
},
data: updateDate,
})
return response.ok(note)
} catch (error) {
if (error.code === 'P2025') {
return response.status(404).json({ message: 'Note not found.' })
}
return response.internalServerError({ message: 'Não foi possível atualizar a nota' })
}
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts around lines 50 to 59, the current code
returns a 500 error when Prisma fails to update a note that doesn't exist.
Modify the catch block to detect if the error is due to the note not being found
(e.g., by checking the error code or message from Prisma) and return a 404
response in that case. For other errors, continue returning the 500 internal
server error as before.

const noteId = params.id
await prisma.note.delete({
where: {
id: Number(noteId),

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 input validation for note ID in destroy method.

Similar to the update method, add proper validation for the note ID parameter.

+      const id = parseInt(noteId, 10)
+      if (isNaN(id) || id <= 0) {
+        return response.status(400).json({ error: 'Invalid note ID format.' })
+      }
+
       await prisma.note.delete({
         where: {
-          id: Number(noteId),
+          id,
         },
       })
📝 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
id: Number(noteId),
const id = parseInt(noteId, 10)
if (isNaN(id) || id <= 0) {
return response.status(400).json({ error: 'Invalid note ID format.' })
}
await prisma.note.delete({
where: {
id,
},
})
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts at line 67, the destroy method uses the
note ID without validation. Add input validation for the note ID parameter
similar to the update method by checking if the noteId is a valid number and
handling invalid input appropriately before proceeding with the deletion logic.

const updateDate = request.only(['title', 'content', 'isFavorite', 'color'])
const note = await prisma.note.update({
where: {
id: Number(noteId),

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 input validation for note ID parameter.

The Number(noteId) conversion can fail silently or produce NaN for invalid inputs. Add proper validation to handle invalid ID formats.

+      const id = parseInt(noteId, 10)
+      if (isNaN(id) || id <= 0) {
+        return response.status(400).json({ error: 'Invalid note ID format.' })
+      }
+
       const note = await prisma.note.update({
         where: {
-          id: Number(noteId),
+          id,
         },
         data: updateDate,
       })
📝 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
id: Number(noteId),
const id = parseInt(noteId, 10)
if (isNaN(id) || id <= 0) {
return response.status(400).json({ error: 'Invalid note ID format.' })
}
const note = await prisma.note.update({
where: {
id,
},
data: updateDate,
})
🤖 Prompt for AI Agents
In app/Controllers/NotesController.ts at line 52, the code converts noteId to a
number without validating it, which can result in NaN for invalid inputs. Add
input validation before this conversion to check if noteId is a valid numeric
string or integer. If invalid, handle the error appropriately, such as returning
a validation error response or throwing an exception, to prevent silent
failures.

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