### Run NestJS Project with npm Scripts Source: https://github.com/77mdias/firts-project-nest/blob/main/back/README.md Provides commands to run the NestJS application in development, watch mode, and production environments using npm scripts. 'npm run start' for development, 'npm run start:dev' for watching changes, and 'npm run start:prod' for production. ```bash # development $ npm run start # watch mode $ npm run start:dev # production mode $ npm run start:prod ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/77mdias/firts-project-nest/blob/main/back/README.md Installs all the necessary project dependencies using npm. This is a fundamental step before running or building the project. ```bash $ npm install ``` -------------------------------- ### Deploy NestJS Application with Mau CLI Source: https://github.com/77mdias/firts-project-nest/blob/main/back/README.md Installs the NestJS Mau CLI globally and deploys the application to AWS. This simplifies the deployment process for NestJS applications. ```bash $ npm install -g @nestjs/mau $ mau deploy ``` -------------------------------- ### Example API Calls with cURL Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Demonstrates how to interact with the backend API endpoints using cURL commands. Includes examples for login, retrieving user profile, listing content, and creating new content. Requires replacing 'YOUR_ACCESS_TOKEN' with a valid JWT. ```bash curl -X POST http://localhost:3001/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"admin@example.com","password":"admin123"}' curl -X GET http://localhost:3001/auth/me \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" curl -X GET "http://localhost:3001/content?page=1&limit=10" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" curl -X POST http://localhost:3001/content \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "title": "My Article", "slug": "my-article", "body": "Article content...", "status": "DRAFT" }' ``` -------------------------------- ### Run Tests for NestJS Project with npm Source: https://github.com/77mdias/firts-project-nest/blob/main/back/README.md Commands to execute unit tests, end-to-end (e2e) tests, and generate test coverage reports for a NestJS project using npm scripts. ```bash # unit tests $ npm run test # e2e tests $ npm run test:e2e # test coverage $ npm run test:cov ``` -------------------------------- ### Docker Compose: Build and Run Backend & Frontend Services Source: https://context7.com/77mdias/firts-project-nest/llms.txt Commands to build Docker images, start services in detached mode, view logs, execute commands inside containers, and stop services. This setup enables hot-reloading for both backend and frontend development. ```bash # Build and start all services (backend + frontend) docker compose build docker compose up -d # View logs docker compose logs -f back # Backend logs docker compose logs -f front # Frontend logs # Execute commands inside containers docker compose exec back npm run test docker compose exec back npx prisma studio docker compose exec front npm run build # Stop services docker compose down # Stop and remove volumes (clean slate) docker compose down -v ``` -------------------------------- ### GET / Source: https://github.com/77mdias/firts-project-nest/blob/main/back/docs/estudo-nest/02-controller-comentado.md This endpoint is the main route of the application and returns a 'Hello World!' message. ```APIDOC ## GET / ### Description Returns a 'Hello World!' message when the root endpoint is accessed. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example { "message": "Hello World!" } ``` -------------------------------- ### Docker Compose Commands Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Commands for building, starting, and stopping Docker services for the project. Also includes executing commands within specific containers. ```bash # Build and start all services docker compose build docker compose up -d # Stop services docker compose down # Execute commands inside containers docker compose exec back npm run docker compose exec front npm run ``` -------------------------------- ### Environment Configuration: Development and Production Variables Source: https://context7.com/77mdias/firts-project-nest/llms.txt Examples of environment variable files for backend (.env.development, .env.production) and frontend (.env.development, .env.production). These files define settings like NODE_ENV, database connection strings, JWT secrets, and API URLs for different deployment environments. ```env # back/.env.development NODE_ENV=development PORT=3001 DATABASE_URL="file:./dev.db" JWT_SECRET=your-development-secret-min-32-characters JWT_EXPIRES_IN=7d JWT_REFRESH_SECRET=your-refresh-secret-min-32-characters JWT_REFRESH_EXPIRES_IN=30d FRONTEND_URL=http://localhost:3000 # back/.env.production NODE_ENV=production PORT=3001 DATABASE_URL="postgresql://user:password@postgres:5432/dbname" JWT_SECRET=your-production-secret-min-32-characters JWT_EXPIRES_IN=7d JWT_REFRESH_SECRET=your-production-refresh-secret JWT_REFRESH_EXPIRES_IN=30d FRONTEND_URL=https://yourdomain.com # front/.env.development NEXT_PUBLIC_API_URL=http://localhost:3001 # front/.env.production NEXT_PUBLIC_API_URL=https://api.yourdomain.com ``` -------------------------------- ### Get Content by ID (GET) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Fetches a single content item by its unique ID. Permission checks are applied based on user role (VIEWER: published only, EDITOR: own + published, ADMIN: all). ```bash # Get content by ID curl -X GET http://localhost:3001/content/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Backend: Prisma Database Seeding Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md This command seeds the database with initial or test data after schema migrations. It's useful for populating the database with necessary records for development and testing. Ensure the seeding script is correctly implemented in your Prisma setup. ```bash npx prisma db seed ``` -------------------------------- ### Get Content by Slug (GET) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves a content item using its slug identifier. This endpoint enforces the same permission checks as retrieving content by ID. ```bash # Get content by slug curl -X GET http://localhost:3001/content/slug/getting-started-nestjs \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### List Content with Filters (GET) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves a paginated list of content items. Supports filtering by status, author, and category. Access is role-based (VIEWER: published only, EDITOR: own + published, ADMIN: all). ```bash # List all content with filters and pagination curl -X GET "http://localhost:3001/content?status=PUBLISHED&page=1&limit=10" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Filter by author (ADMIN/EDITOR) curl -X GET "http://localhost:3001/content?authorId=user-uuid&page=1&limit=20" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Filter by category curl -X GET "http://localhost:3001/content?categoryId=category-uuid&status=PUBLISHED" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Frontend: Making Authenticated API Requests Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md This example shows how to make authenticated API requests from the frontend using an `ApiClient` class. It emphasizes adding methods to the `ApiClient` to handle authenticated requests, passing the access token obtained from the `useAuth` hook. Ensure `types/auth.ts` is updated with necessary interfaces. ```typescript import { ApiClient } from '@/lib/api'; // Assuming ApiClient is exported from '@/lib/api' import { useAuth } from '@/context/AuthContext'; interface Resource { id: string; name: string; } async function fetchResource(id: string) { const { accessToken } = useAuth(); const apiClient = new ApiClient(); // Instantiate ApiClient if (!accessToken) { // Handle case where token is not available console.error('Access token is missing'); return null; } try { const data = await apiClient.authenticatedRequest(`/resource/${id}`, accessToken); return data; } catch (error) { console.error('Failed to fetch resource:', error); // Handle API errors gracefully return null; } } // Example usage in a component: // const resourceData = await fetchResource('some-id'); ``` -------------------------------- ### GET /content - List Content Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves a paginated list of content items. Filtering options are available for status, author, and category. Role-based access controls apply. ```APIDOC ## GET /content ### Description Retrieves a paginated list of content items. Access is filtered based on user roles: VIEWER sees only published content, EDITOR sees their own content plus published content, and ADMIN sees all content. ### Method GET ### Endpoint /content ### Parameters #### Path Parameters None #### Query Parameters - **status** (string) - Optional - Filters content by status (e.g., 'PUBLISHED', 'DRAFT'). - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **limit** (integer) - Optional - The number of items per page. Defaults to 10. - **authorId** (string) - Optional - Filters content by a specific author ID. Only available for ADMIN and EDITOR roles. - **categoryId** (string) - Optional - Filters content by a specific category ID. ### Request Example ```bash curl -X GET "http://localhost:3001/content?status=PUBLISHED&page=1&limit=10" ``` ### Response #### Success Response (200 OK) - **data** (array) - An array of content objects. - **id** (string) - The unique identifier of the content. - **title** (string) - The title of the content. - **slug** (string) - The slug of the content. - **excerpt** (string) - The excerpt of the content. - **status** (string) - The publishing status. - **publishedAt** (string) - The timestamp when the content was published. - **author** (object) - Information about the content's author. - **id** (string) - **name** (string) - **email** (string) - **category** (object) - Information about the content's category. - **id** (string) - **name** (string) - **slug** (string) - **createdAt** (string) - The timestamp when the content was created. - **meta** (object) - Pagination metadata. - **total** (integer) - Total number of items. - **page** (integer) - Current page number. - **limit** (integer) - Items per page. - **totalPages** (integer) - Total number of pages. #### Response Example ```json { "data": [ { "id": "content-uuid-1", "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "publishedAt": "2025-10-26T12:00:00.000Z", "author": { "id": "author-uuid", "name": "John Doe", "email": "john@example.com" }, "category": { "id": "category-uuid", "name": "Tutorials", "slug": "tutorials" }, "createdAt": "2025-10-26T12:00:00.000Z" } ], "meta": { "total": 42, "page": 1, "limit": 10, "totalPages": 5 } } ``` #### Error Handling - **401 Unauthorized**: Returned if the user is not authenticated. - **403 Forbidden**: Returned if the user attempts to filter by `authorId` without sufficient permissions. ``` -------------------------------- ### Implement API Client for Custom Endpoints in React Source: https://context7.com/77mdias/firts-project-nest/llms.txt This code extends an existing API client to handle authenticated requests for custom content endpoints. It includes functions to fetch a list of content and to create new content, both requiring an access token. The example usage shows a React component that fetches and displays content, leveraging `useAuth` for authentication state and `useEffect` for data fetching. It handles loading states and potential errors during API calls. ```typescript // lib/api.ts - Adding custom content endpoints import { apiClient } from "@/lib/api"; // Fetch content list export async function getContentList(accessToken: string, page = 1, limit = 10) { return apiClient.authenticatedRequest( `/content?page=${page}&limit=${limit}`, accessToken ); } // Create new content export async function createContent( accessToken: string, data: { title: string; slug: string; body: string; status?: string } ) { return apiClient.authenticatedRequest( "/content", accessToken, { method: "POST", body: JSON.stringify(data), } ); } // Usage in component "use client"; import { useAuth } from "@/contexts/AuthContext"; import { useState, useEffect } from "react"; import { getContentList } from "@/lib/api"; export default function ContentListPage() { const { accessToken, isAuthenticated } = useAuth(); const [content, setContent] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { if (isAuthenticated && accessToken) { getContentList(accessToken, 1, 20) .then((data) => setContent(data.data)) .catch((error) => console.error("Failed to load content:", error)) .finally(() => setLoading(false)); } }, [isAuthenticated, accessToken]); if (loading) return
Loading content...
; return (

Content Library

{content.map((item: any) => (

{item.title}

{item.excerpt}

))}
); } ``` -------------------------------- ### Controller Básico NestJS com @Controller e @Get Source: https://github.com/77mdias/firts-project-nest/blob/main/back/docs/estudo-nest/02-controller-comentado.md Define um controlador NestJS básico para mapear rotas HTTP. Utiliza os decorators @Controller para a classe e @Get para definir uma rota GET. Retorna uma string simples como resposta. ```typescript import { Controller, Get } from '@nestjs/common'; /** * ✅ O que faz: Define o controlador principal da aplicação. * 📌 Onde usar: Em qualquer aplicação NestJS para mapear rotas. * ⚙️ Como funciona: O decorator @Controller() indica que a classe é um controller. */ @Controller() export class AppController { /** * ✅ O que faz: Retorna uma mensagem de hello world. * 📌 Onde usar: Rota GET principal do sistema. * ⚙️ Como funciona: Ao acessar '/', retorna a string. */ @Get() getHello(): string { return 'Hello World!'; } } ``` -------------------------------- ### Next.js Frontend Development Commands Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Commands for running, building, and linting the Next.js frontend application. Covers development server, production build, and linting checks. ```bash # Development npm run dev # Build npm run build # Production npm run start # Linting npm run lint ``` -------------------------------- ### Prisma ORM Management Commands Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Commands for managing the Prisma schema and database, including generating the client, pushing schema changes, creating migrations, deploying migrations, seeding data, and opening Prisma Studio. ```bash # Generate Prisma client (run after schema changes) npx prisma generate # Push schema to database (dev only) npx prisma db push # Create migration (recommended for production) npx prisma migrate dev --name # Apply migrations npx prisma migrate deploy # Seed database with test data npx prisma db seed # Open Prisma Studio (GUI) npx prisma studio ``` -------------------------------- ### GET /content/slug/{slug} - Get Content by Slug Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves a single content item using its slug. This endpoint enforces the same permission checks as retrieving content by ID. ```APIDOC ## GET /content/slug/{slug} ### Description Retrieves a single content item using its URL-friendly slug. This endpoint enforces the same access control logic as fetching content by ID, considering user roles and ownership. ### Method GET ### Endpoint /content/slug/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The URL-friendly slug of the content to retrieve. #### Query Parameters None ### Request Example ```bash curl -X GET http://localhost:3001/content/slug/getting-started-nestjs ``` ### Response #### Success Response (200 OK) - The response structure is identical to the `GET /content/{id}` endpoint. #### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "body": "# Introduction\n\nNestJS is a progressive Node.js framework...", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "publishedAt": "2025-10-26T12:00:00.000Z", "author": { "id": "author-uuid", "name": "John Doe", "email": "john@example.com", "role": "EDITOR" }, "category": { "id": "category-uuid", "name": "Tutorials", "slug": "tutorials", "description": "Technical tutorials and guides" }, "createdAt": "2025-10-26T12:00:00.000Z", "updatedAt": "2025-10-26T12:00:00.000Z" } ``` #### Error Handling - **404 Not Found**: Returned if the content with the specified slug does not exist or if the user lacks the necessary permissions to view it. - **401 Unauthorized**: Returned if the user is not authenticated. ``` -------------------------------- ### GET /content/{id} - Get Content by ID Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves a single content item by its unique ID. Access is restricted based on user roles and content ownership. ```APIDOC ## GET /content/{id} ### Description Fetches a single content item by its unique ID. Access control is applied based on user roles (VIEWER, EDITOR, ADMIN) and content ownership. ### Method GET ### Endpoint /content/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the content to retrieve. #### Query Parameters None ### Request Example ```bash curl -X GET http://localhost:3001/content/550e8400-e29b-41d4-a716-446655440000 ``` ### Response #### Success Response (200 OK) - **id** (string) - The unique identifier of the content. - **title** (string) - The title of the content. - **slug** (string) - The slug of the content. - **body** (string) - The main content. - **excerpt** (string) - The excerpt of the content. - **status** (string) - The publishing status. - **publishedAt** (string) - The timestamp when the content was published. - **author** (object) - Information about the content's author. - **id** (string) - **name** (string) - **email** (string) - **role** (string) - The role of the author. - **category** (object) - Information about the content's category. - **id** (string) - **name** (string) - **slug** (string) - **description** (string) - **createdAt** (string) - The timestamp when the content was created. - **updatedAt** (string) - The timestamp when the content was last updated. #### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "body": "# Introduction\n\nNestJS is a progressive Node.js framework...", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "publishedAt": "2025-10-26T12:00:00.000Z", "author": { "id": "author-uuid", "name": "John Doe", "email": "john@example.com", "role": "EDITOR" }, "category": { "id": "category-uuid", "name": "Tutorials", "slug": "tutorials", "description": "Technical tutorials and guides" }, "createdAt": "2025-10-26T12:00:00.000Z", "updatedAt": "2025-10-26T12:00:00.000Z" } ``` #### Error Handling - **404 Not Found**: Returned if the content does not exist or if the user does not have permission to access it. - **401 Unauthorized**: Returned if the user is not authenticated. ``` -------------------------------- ### NestJS Backend Development Commands Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Commands for running, building, testing, linting, and formatting the NestJS backend application. Includes development, production, unit, and E2E testing options. ```bash # Development (auto-reloads on changes, generates Prisma client) npm run start:dev # Build npm run build # Production npm run start:prod # Testing npm run test # Unit tests npm run test:watch # Watch mode npm run test:e2e # E2E tests npm run test:cov # Coverage # Linting & Formatting npm run lint # ESLint with auto-fix npm run format # Prettier ``` -------------------------------- ### Prisma Database Management Commands (Bash) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Provides essential bash commands for managing Prisma migrations, generating the Prisma client, seeding the database, and accessing Prisma Studio. These commands facilitate the development workflow. ```bash # Create new migration after schema changes cd back npx prisma migrate dev --name add_content_categories # Apply migrations in production npx prisma migrate deploy # Generate Prisma Client (auto-included in npm run start:dev) npx prisma generate # Seed database with test data npx prisma db seed # Open Prisma Studio GUI (http://localhost:5555) npx prisma studio # Reset database (WARNING: deletes all data) npx prisma migrate reset ``` -------------------------------- ### GET /auth/me - Get Current User Profile Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves the profile information of the currently authenticated user by extracting details from the JWT token. This is useful for verifying token validity and fetching up-to-date user data. ```APIDOC ## GET /auth/me ### Description Returns authenticated user information extracted from JWT token, useful for validating token and fetching updated user data. ### Method GET ### Endpoint /auth/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```bash curl -X GET http://localhost:3001/auth/me \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200 OK) - **id** (string) - Unique identifier for the user. - **email** (string) - User's email address. - **name** (string) - User's full name. - **role** (string) - User's assigned role. #### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "admin@example.com", "name": "Admin User", "role": "ADMIN" } ``` #### Error Handling - **HTTP 401 Unauthorized** - Missing or invalid token. ```json { "statusCode": 401, "message": "Unauthorized" } ``` ``` -------------------------------- ### Production: Deploying Prisma Migrations Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Applies pending database migrations to the production PostgreSQL database. This command should be run after updating the schema and setting the `DATABASE_URL` in `.env.production`. Ensure your database is accessible and migrations are correctly configured. ```bash npx prisma migrate deploy ``` -------------------------------- ### Get Current User Profile API (Bash) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Retrieves the profile information of the currently authenticated user by sending a GET request to the /auth/me endpoint with an Authorization header. Extracts user details from the JWT. Handles missing or invalid token errors. ```bash # Get current user profile curl -X GET http://localhost:3001/auth/me \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Response { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "admin@example.com", "name": "Admin User", "role": "ADMIN" } # Error handling # HTTP 401 Unauthorized - Missing or invalid token { "statusCode": 401, "message": "Unauthorized" } ``` -------------------------------- ### Backend: Running Unit Tests Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Executes the backend unit tests using the configured test runner (likely Jest). Navigate to the `back` directory before running this command. This command is essential for verifying the correctness of individual backend modules and functions. ```bash cd back && npm run test ``` -------------------------------- ### Create Content (POST) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Creates a new content item. Requires ADMIN or EDITOR role. Sends JSON payload with content details to the /content endpoint. ```bash curl -X POST http://localhost:3001/content \ -H "Content-Type: application/json" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -d '{ "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "body": "# Introduction\n\nNestJS is a progressive Node.js framework...", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "categoryId": "category-uuid-optional" }' ``` -------------------------------- ### Backend: Running End-to-End Tests Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Executes the backend end-to-end (E2E) tests. These tests simulate user interactions and test the application as a whole. Navigate to the `back` directory before running this command. Ensure your test environment is properly configured. ```bash cd back && npm run test:e2e ``` -------------------------------- ### Get User by ID API Endpoint (Admin Only) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Fetches a single user's profile, including their role and account status. This endpoint is restricted to ADMIN users and requires an Authorization header. ```bash # Get user by ID (ADMIN only) curl -X GET http://localhost:3001/users/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Response { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "editor@example.com", "name": "Editor User", "role": "EDITOR", "isActive": true, "createdAt": "2025-01-15T00:00:00.000Z", "updatedAt": "2025-10-20T10:00:00.000Z" } ``` -------------------------------- ### User Registration API (Bash) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Registers a new user by sending an email, password, and name to the /auth/register endpoint. It hashes the password using bcrypt and returns user details along with access and refresh tokens. Handles 'Email already registered' conflict. ```bash # Register new user curl -X POST http://localhost:3001/auth/register \ -H "Content-Type: application/json" \ -d '{ "email": "john.doe@example.com", "password": "securepass123", "name": "John Doe" }' # Response { "user": { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "john.doe@example.com", "name": "John Doe", "role": "VIEWER", "createdAt": "2025-10-26T12:00:00.000Z" }, "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } # Error handling # HTTP 409 Conflict - Email already registered { "statusCode": 409, "message": "Email already registered" } ``` -------------------------------- ### POST /auth/register - User Registration Source: https://context7.com/77mdias/firts-project-nest/llms.txt Creates a new user account with email and password. Automatically assigns the VIEWER role, hashes the password using bcrypt, and returns access and refresh tokens along with user data. ```APIDOC ## POST /auth/register ### Description Creates a new user account with email and password, automatically assigns VIEWER role, hashes the password with bcrypt, and returns access/refresh tokens with user data. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. - **name** (string) - Required - User's full name. ### Request Example ```json { "email": "john.doe@example.com", "password": "securepass123", "name": "John Doe" } ``` ### Response #### Success Response (201 Created) - **user** (object) - User details. - **id** (string) - Unique identifier for the user. - **email** (string) - User's email address. - **name** (string) - User's full name. - **role** (string) - User's assigned role (e.g., 'VIEWER'). - **createdAt** (string) - Timestamp of user creation. - **accessToken** (string) - JWT access token. - **refreshToken** (string) - JWT refresh token. #### Response Example ```json { "user": { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "john.doe@example.com", "name": "John Doe", "role": "VIEWER", "createdAt": "2025-10-26T12:00:00.000Z" }, "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` #### Error Handling - **HTTP 409 Conflict** - Email already registered. ```json { "statusCode": 409, "message": "Email already registered" } ``` ``` -------------------------------- ### Backend: Running Tests in Watch Mode (TDD) Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Starts the backend test runner in watch mode, which automatically re-runs tests when code changes are detected. This is ideal for Test-Driven Development (TDD) workflows. Navigate to the `back` directory before running this command. ```bash cd back && npm run test:watch ``` -------------------------------- ### Backend: Generating Test Coverage Report Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Generates a test coverage report for the backend. This report indicates which parts of your codebase are covered by tests. Navigate to the `back` directory before running this command. Reviewing coverage helps identify areas needing more tests. ```bash cd back && npm run test:cov ``` -------------------------------- ### Frontend: Handling Loading State for Protected Content Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md This code illustrates how to handle the loading state when accessing protected content on the frontend. It uses the `useAuth` hook to check the `isLoading` and `isAuthenticated` states before rendering sensitive information, preventing hydration mismatches. Ensure the `AuthContext` is properly set up. ```typescript import { useAuth } from '@/context/AuthContext'; function ProtectedComponent() { const { isLoading, isAuthenticated } = useAuth(); if (isLoading) { return
Loading authentication state...
; } if (!isAuthenticated) { // Redirect to login or show unauthorized message return
You are not authorized to view this page.
; } return (

Welcome to the protected area!

{/* Protected content goes here */}
); } ``` -------------------------------- ### Implement Protected API Endpoints with Guards in NestJS Source: https://context7.com/77mdias/firts-project-nest/llms.txt This NestJS controller demonstrates how to implement role-based authorization for API endpoints using guards and decorators. The `ContentController` uses `JwtAuthGuard` for authentication and `RolesGuard` for authorization. The `@Roles` decorator specifies the allowed roles for each endpoint (e.g., ADMIN, EDITOR, VIEWER). The `@CurrentUser` decorator injects the authenticated user's data into the route handler. This setup ensures that only authorized users can access specific resources. ```typescript // content.controller.ts import { Controller, Get, Post, Body, UseGuards, Query } from "@nestjs/common"; import { JwtAuthGuard } from "src/auth/guards/jwt-auth.guard"; import { RolesGuard } from "src/auth/guards/roles.guard"; import { Roles } from "src/auth/decorators/roles.decorator"; import { CurrentUser } from "src/auth/decorators/current-user.decorator"; import { Role } from "@prisma/client"; import type { CurrentUserData } from "src/auth/decorators/current-user.decorator"; import { ContentService } from "./content.service"; import { CreateContentDto } from "./dto/create-content.dto"; import { QueryContentDto } from "./dto/query-content.dto"; @Controller("content") @UseGuards(JwtAuthGuard, RolesGuard) // Apply guards to all routes export class ContentController { constructor(private contentService: ContentService) {} // Only ADMIN and EDITOR can create content @Post() @Roles(Role.ADMIN, Role.EDITOR) async create( @Body() dto: CreateContentDto, @CurrentUser() user: CurrentUserData // Inject authenticated user ) { return this.contentService.create(dto, user.id); } // All authenticated users can list content @Get() @Roles(Role.ADMIN, Role.EDITOR, Role.VIEWER) async findAll( @Query() query: QueryContentDto, @CurrentUser() user: CurrentUserData ) { // Service applies role-based filtering return this.contentService.findAll(query, user.id, user.role as Role); } } ``` -------------------------------- ### NestJS Repository Pattern Implementation Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Illustrates the pattern for abstracting repository classes and providing Prisma-specific implementations within the NestJS backend. This promotes data access abstraction. ```typescript // Abstract repository classes define contracts (e.g., UsersRepository, ContentRepository) // Prisma-specific implementations in `repositories/prisma/` // Registered as providers using `provide/useClass` pattern // Example: { provide: UsersRepository, useClass: PrismaUsersRepository } ``` -------------------------------- ### Backend: Prisma Database Schema Migration Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md This command is used to apply database schema changes defined in `prisma/schema.prisma`. It generates SQL migration files and applies them to the database. Ensure the Prisma schema is updated before running this command. For production, `prisma migrate deploy` should be used. ```bash npx prisma migrate dev --name ``` -------------------------------- ### Backend Environment Variables Configuration Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Configuration settings for the backend application, including server port, database connection URL, JWT secrets and expiry times, and CORS origin. Supports different environments like development, test, and production. ```dotenv # Server NODE_ENV=development PORT=3001 # Database DATABASE_URL="file:./dev.db" # SQLite for dev # DATABASE_URL="postgresql://user:pass@host:5432/db" # PostgreSQL for prod # JWT JWT_SECRET=your-secret-key-min-32-chars JWT_EXPIRES_IN=7d JWT_REFRESH_SECRET=your-refresh-secret-key-min-32-chars JWT_REFRESH_EXPIRES_IN=30d # CORS FRONTEND_URL=http://localhost:3000 ``` -------------------------------- ### POST /content - Create Content Source: https://context7.com/77mdias/firts-project-nest/llms.txt Allows users with ADMIN or EDITOR roles to create new content. Requires authentication and content details in the request body. ```APIDOC ## POST /content ### Description Creates a new content item. Only users with ADMIN or EDITOR roles can perform this action. ### Method POST ### Endpoint /content ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The title of the content. - **slug** (string) - Required - A URL-friendly identifier for the content. - **body** (string) - Required - The main content. - **excerpt** (string) - Optional - A short summary of the content. - **status** (string) - Optional - The publishing status (e.g., 'PUBLISHED', 'DRAFT'). Defaults to 'DRAFT'. - **categoryId** (string) - Optional - The ID of the category this content belongs to. ### Request Example ```json { "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "body": "# Introduction\n\nNestJS is a progressive Node.js framework...", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "categoryId": "category-uuid-optional" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier of the created content. - **title** (string) - The title of the content. - **slug** (string) - The slug of the content. - **body** (string) - The main content. - **excerpt** (string) - The excerpt of the content. - **status** (string) - The publishing status. - **publishedAt** (string) - The timestamp when the content was published. - **authorId** (string) - The ID of the author. - **categoryId** (string) - The ID of the category. - **createdAt** (string) - The timestamp when the content was created. - **updatedAt** (string) - The timestamp when the content was last updated. #### Response Example ```json { "id": "content-uuid-here", "title": "Getting Started with NestJS", "slug": "getting-started-nestjs", "body": "# Introduction\n\nNestJS is a progressive Node.js framework...", "excerpt": "Learn the basics of NestJS framework", "status": "PUBLISHED", "publishedAt": "2025-10-26T12:00:00.000Z", "authorId": "user-uuid-here", "categoryId": "category-uuid-optional", "createdAt": "2025-10-26T12:00:00.000Z", "updatedAt": "2025-10-26T12:00:00.000Z" } ``` #### Error Handling - **403 Forbidden**: Returned if the user does not have the required role (ADMIN or EDITOR). - **400 Bad Request**: Returned for invalid input data. ``` -------------------------------- ### User Login API (Bash) Source: https://context7.com/77mdias/firts-project-nest/llms.txt Authenticates a user by sending email and password to the /auth/login endpoint. It validates credentials and account status, then generates and returns a new access and refresh token pair. Handles 'Invalid credentials' and 'Account is inactive' errors. ```bash # Login with credentials curl -X POST http://localhost:3001/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "admin@example.com", "password": "admin123" }' # Response { "user": { "id": "admin-uuid-here", "email": "admin@example.com", "name": "Admin User", "role": "ADMIN" }, "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } # Error handling # HTTP 401 Unauthorized - Invalid credentials { "statusCode": 401, "message": "Invalid credentials" } # HTTP 401 Unauthorized - Inactive account { "statusCode": 401, "message": "Account is inactive" } ``` -------------------------------- ### Authentication API Source: https://github.com/77mdias/firts-project-nest/blob/main/CLAUDE.md Endpoints for user registration, login, token refresh, logout, and fetching current user profile. ```APIDOC ## POST /auth/register ### Description Registers a new user. The default role assigned is VIEWER. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **email** (string) - Required - User's email address - **password** (string) - Required - User's password - **name** (string) - Optional - User's name ### Request Example { "email": "user@example.com", "password": "securepassword", "name": "John Doe" } ### Response #### Success Response (201) - **message** (string) - Success message - **user** (object) - Created user details - **id** (string) - User ID - **email** (string) - User email - **name** (string) - User name - **role** (string) - User role (default: VIEWER) #### Response Example { "message": "User registered successfully", "user": { "id": "uuid-user-id", "email": "user@example.com", "name": "John Doe", "role": "VIEWER" } } ## POST /auth/login ### Description Authenticates a user and returns access and refresh tokens upon successful login. ### Method POST ### Endpoint /auth/login ### Parameters #### Request Body - **email** (string) - Required - User's email address - **password** (string) - Required - User's password ### Request Example { "email": "user@example.com", "password": "securepassword" } ### Response #### Success Response (200) - **accessToken** (string) - JWT access token - **refreshToken** (string) - JWT refresh token #### Response Example { "accessToken": "eyJ...", "refreshToken": "eyJ..." } ## POST /auth/refresh ### Description Refreshes the access token using a valid refresh token. ### Method POST ### Endpoint /auth/refresh ### Parameters #### Request Body - **refreshToken** (string) - Required - The user's refresh token ### Request Example { "refreshToken": "eyJ..." } ### Response #### Success Response (200) - **accessToken** (string) - New JWT access token #### Response Example { "accessToken": "eyJ..." } ## POST /auth/logout ### Description Invalidates the user's refresh token, logging them out. ### Method POST ### Endpoint /auth/logout ### Parameters #### Request Body - **refreshToken** (string) - Required - The user's refresh token to invalidate ### Request Example { "refreshToken": "eyJ..." } ### Response #### Success Response (200) - **message** (string) - Success message indicating logout #### Response Example { "message": "User logged out successfully" } ## GET /auth/me ### Description Retrieves the profile information of the currently authenticated user. ### Method GET ### Endpoint /auth/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token (e.g., `Bearer `) ### Response #### Success Response (200) - **id** (string) - User ID - **email** (string) - User email - **name** (string) - User name - **role** (string) - User role #### Response Example { "id": "uuid-user-id", "email": "user@example.com", "name": "John Doe", "role": "EDITOR" } ```