Solucao desafio corelab#74
Conversation
WalkthroughThis 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
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
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 IDPULL_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
requestparameter is destructured but never used in thedestroymethod. 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
⛔ Files ignored due to path filters (2)
package-lock.jsonis excluded by!**/package-lock.jsonprisma/dev.dbis 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:3000is 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 DELETEAll 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 generatecommand 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 PrismaThe migration command
npx prisma migrate devwill work as expected since migration files are committed:
- prisma/migrations/20250714181039_init/migration.sql
No further action required.
| "eslint-plugin-prettier": "^4.0.0", | ||
| "pino-pretty": "^7.6.1", | ||
| "prettier": "^2.6.2", | ||
| "prisma": "^5.22.0", |
There was a problem hiding this comment.
💡 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:
- 1: https://github.com/prisma/prisma/releases?utm_source=openai
- 2: https://security.snyk.io/package/npm/prisma%405.22.0?utm_source=openai
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.
| Route.post('/notes', 'NotesController.store') | ||
| Route.get('/notes', 'NotesController.index') | ||
| Route.patch('/notes/:id', 'NotesController.update') | ||
| Route.delete('/notes/:id', 'NotesController.destroy') |
There was a problem hiding this comment.
💡 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.tsLength 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.tsLength 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.
| const note = await prisma.note.create({ | ||
| data: { | ||
| title, | ||
| content, | ||
| isFavorite, | ||
| color, | ||
| }, | ||
| }) |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| } catch (error) { | ||
| return response.internalServerError({ message: 'Não foi possível criar a nota.' }) | ||
| } |
There was a problem hiding this comment.
🛠️ 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']) |
There was a problem hiding this comment.
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.
| 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`.
| 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' }) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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), |
There was a problem hiding this comment.
🛠️ 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.
| 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), |
There was a problem hiding this comment.
🛠️ 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.
| 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.
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:
🛠️ 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-toastifye criando umNotificationServicereutilizável.Otimização de Performance: A lógica de filtragem no front-end foi otimizada com o hook
useMemopara 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:
Passos:
Clone os dois repositórios (
corelab-web-challengeecorelab-api-challenge) para dentro da mesma pasta pai.Na raiz desta pasta principal, crie um arquivo chamado
docker-compose.ymlcom o seguinte conteúdo:No terminal, a partir da pasta raiz, execute:
Acesse a aplicação em
http://localhost:3000.Rodando Localmente (Sem Docker)
Pré-requisitos:
v16.15.0v8.5.5Backend:
corelab-api-challenge.npm install,cp .env.example .env,node ace generate:key,npx prisma migrate dev, e finalmentenpm run dev.Frontend:
corelab-web-challenge.npm installenpm 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
Documentation
Chores