### NPM Scripts for Service Management Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Provides a set of NPM scripts for managing development services, including starting, stopping, and removing services, as well as initiating the full development environment. The `dev` script orchestrates a sequence of actions: starting services, waiting for the database, applying migrations, and then starting the Next.js development server. ```bash # Iniciar serviços npm run services:up # Parar serviços (mantém dados) npm run services:stop # Remover serviços e volumes npm run services:down # Iniciar ambiente completo de desenvolvimento npm run dev # Executa: services:up -> wait-for-postgres -> migration:up -> next dev ``` -------------------------------- ### Docker Compose for Development Services Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Defines the Docker Compose configuration for the development environment, specifically for the PostgreSQL database service. It specifies the container name, image, environment file for configuration, and port mapping. This setup allows for easy management of the database service during development. ```yaml services: database: container_name: "postgres-dev" image: postgres:16.0-alpine3.18 env_file: - ../.env.development ports: - ${POSTGRES_PORT:-5432}:5432 ``` -------------------------------- ### Check System Status API (GET /api/v1/status) Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Retrieves the health status of the application and its dependencies, including detailed information about the PostgreSQL database connection. It returns the database version, maximum connections, and currently active connections. ```bash # Verificar status do sistema curl -X GET http://localhost:3000/api/v1/status # Resposta esperada (HTTP 200): { "updated_at": "2024-01-15T10:30:00.000Z", "dependencies": { "database": { "version": "16.0", "max_connections": 100, "opened_connections": 1 } } } ``` -------------------------------- ### List Pending Database Migrations API (GET /api/v1/migrations) Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Queries for pending database migrations without executing them (dry-run). It returns an array of migrations that have not yet been applied to the database. If no migrations are pending, an empty array is returned. ```bash # Listar migrações pendentes curl -X GET http://localhost:3000/api/v1/migrations # Resposta esperada (HTTP 200): [ { "path": "infra/migrations/1724116117071_first-migration-test.js", "name": "1724116117071_first-migration-test", "timestamp": 1724116117071 } ] # Se não houver migrações pendentes: [] ``` -------------------------------- ### GET /api/v1/status - System Status Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Endpoint to check the health of the application and its dependencies, returning detailed information about the PostgreSQL database connection. ```APIDOC ## GET /api/v1/status ### Description Endpoint to check the health of the application and its dependencies, returning detailed information about the PostgreSQL database connection, including version, maximum connections, and active connections. ### Method GET ### Endpoint /api/v1/status ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET http://localhost:3000/api/v1/status ``` ### Response #### Success Response (200) - **updated_at** (string) - The timestamp when the status was last updated. - **dependencies** (object) - An object containing information about system dependencies. - **database** (object) - Information about the database connection. - **version** (string) - The version of the PostgreSQL database. - **max_connections** (integer) - The maximum number of allowed connections to the database. - **opened_connections** (integer) - The current number of active connections to the database. #### Response Example ```json { "updated_at": "2024-01-15T10:30:00.000Z", "dependencies": { "database": { "version": "16.0", "max_connections": 100, "opened_connections": 1 } } } ``` ``` -------------------------------- ### Integration Test for API Status Endpoint Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt An example of an integration test written in JavaScript using Jest and Fetch API to validate the `/api/v1/status` endpoint. It checks for a 200 OK response, verifies the ISO format of the `updated_at` timestamp, and asserts the correctness of database connection details like version, max connections, and opened connections. ```javascript // tests/integration/api/v1/status/get.test.js test("GET to /api/v1/status should be return 200", async () => { const response = await fetch("http://localhost:3000/api/v1/status"); expect(response.status).toBe(200); const responseBody = await response.json(); // Validar formato de data ISO const parsedUpdatedAt = new Date(responseBody.updated_at).toISOString(); expect(responseBody.updated_at).toEqual(parsedUpdatedAt); // Validar informações do banco de dados expect(responseBody.dependencies.database.version).toBe("16.0"); expect(responseBody.dependencies.database.max_connections).toBe(100); expect(responseBody.dependencies.database.opened_connections).toBe(1); }); ``` -------------------------------- ### Get New PostgreSQL Client Connection (JavaScript) Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Creates a new direct connection client to PostgreSQL, suitable for operations requiring manual connection control like transactions or migrations. It is crucial to manually close the client after use to release resources. ```javascript import database from "infra/database.js"; import migrationRunner from "node-pg-migrate"; import { join } from "node:path"; // Obter cliente para operações que requerem conexão persistente let dbClient; try { dbClient = await database.getNewClient(); // Usar cliente para executar migrações const migrations = await migrationRunner({ dbClient: dbClient, dryRun: false, dir: join("infra", "migrations"), direction: "up", verbose: true, migrationsTable: "pgmigrations", }); console.log(`${migrations.length} migrações executadas`); } catch (error) { console.error("Erro na migração:", error); throw error; } finally { // IMPORTANTE: sempre fechar o cliente manualmente await dbClient.end(); } ``` -------------------------------- ### GET /api/v1/migrations - List Pending Migrations Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Endpoint to query pending database migrations without executing them (dry-run). Returns an array of migrations that have not yet been applied to the database. ```APIDOC ## GET /api/v1/migrations ### Description Endpoint to query pending database migrations without executing them (dry-run). Returns an array of migrations that have not yet been applied to the database. ### Method GET ### Endpoint /api/v1/migrations ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET http://localhost:3000/api/v1/migrations ``` ### Response #### Success Response (200) - **Array of Migration Objects**: Each object represents a pending migration. - **path** (string) - The file path of the migration. - **name** (string) - The name of the migration. - **timestamp** (integer) - The timestamp associated with the migration. #### Response Example ```json [ { "path": "infra/migrations/1724116117071_first-migration-test.js", "name": "1724116117071_first-migration-test", "timestamp": 1724116117071 } ] ``` #### Empty Response Example (No pending migrations) ```json [] ``` ``` -------------------------------- ### NPM Scripts for Database Migrations Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Outlines NPM scripts for managing database migrations using node-pg-migrate. It includes commands to create new migration files with a specified name and to apply all pending migrations to the database schema. These scripts facilitate version control and application of database schema changes. ```bash # Criar nova migração npm run migration:create nome-da-migracao # Executar migrações pendentes npm run migration:up ``` -------------------------------- ### Execute Database Migrations API (POST /api/v1/migrations) Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Executes all pending database migrations. It returns HTTP 201 with the applied migrations upon success, or HTTP 200 if no migrations were pending. It also handles non-allowed methods with HTTP 405. ```bash # Executar migrações pendentes curl -X POST http://localhost:3000/api/v1/migrations # Resposta quando migrações são aplicadas (HTTP 201): [ { "path": "infra/migrations/1724116117071_first-migration-test.js", "name": "1724116117071_first-migration-test", "timestamp": 1724116117071 } ] # Resposta quando não houver migrações pendentes (HTTP 200): [] # Resposta para método não permitido (HTTP 405): { "error": "Method PUT Not Allowed" } ``` -------------------------------- ### NPM Scripts for Running Tests Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Provides NPM scripts for executing the project's test suite. `npm test` runs all tests, while `npm run test:watch` enables watch mode, automatically re-running tests when code changes are detected. This facilitates a TDD workflow. ```bash # Executar todos os testes npm test # Executar testes em modo watch npm run test:watch ``` -------------------------------- ### Database Migration File Structure and Logic Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Illustrates the structure and JavaScript code for a database migration file used with node-pg-migrate. It defines `up` and `down` functions to handle schema changes, such as creating and dropping tables. The `up` function creates a 'users' table with specific columns and constraints, while the `down` function reverts this change by dropping the table. ```javascript // Estrutura de arquivo de migração: infra/migrations/[timestamp]_nome-da-migracao.js exports.shorthands = undefined; exports.up = (pgm) => { // Criar tabela pgm.createTable("users", { id: "id", email: { type: "varchar(255)", notNull: true, unique: true }, created_at: { type: "timestamp", notNull: true, default: pgm.func("current_timestamp"), }, }); }; exports.down = (pgm) => { // Reverter migração pgm.dropTable("users"); }; ``` -------------------------------- ### POST /api/v1/migrations - Execute Migrations Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Endpoint to execute all pending database migrations. Returns status 201 when migrations are applied successfully, or 200 when there are no pending migrations to execute. ```APIDOC ## POST /api/v1/migrations ### Description Endpoint to execute all pending database migrations. Returns status 201 when migrations are applied successfully, or 200 when there are no pending migrations to execute. ### Method POST ### Endpoint /api/v1/migrations ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X POST http://localhost:3000/api/v1/migrations ``` ### Response #### Success Response (201 - Migrations Applied) - **Array of Migration Objects**: Each object represents an applied migration. - **path** (string) - The file path of the migration. - **name** (string) - The name of the migration. - **timestamp** (integer) - The timestamp associated with the migration. #### Success Response (200 - No Pending Migrations) - **Empty Array**: Indicates no migrations were pending or executed. #### Error Response (405 - Method Not Allowed) - **error** (string) - Description of the error. #### Response Example (Migrations Applied - HTTP 201) ```json [ { "path": "infra/migrations/1724116117071_first-migration-test.js", "name": "1724116117071_first-migration-test", "timestamp": 1724116117071 } ] ``` #### Response Example (No Pending Migrations - HTTP 200) ```json [] ``` #### Response Example (Method Not Allowed - HTTP 405) ```json { "error": "Method PUT Not Allowed" } ``` ``` -------------------------------- ### Integration Test for API Migrations Endpoint Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt An integration test in JavaScript for the `/api/v1/migrations` POST endpoint. It uses `beforeAll` to clean the database before tests run. The test verifies that the first POST request applies pending migrations (returning 201 and a non-empty array), and a subsequent POST request returns 200 with an empty array, indicating no pending migrations. ```javascript // tests/integration/api/v1/migrations/post.test.js import database from "infra/database.js"; beforeAll(cleanDatabase); async function cleanDatabase() { await database.query("drop schema public cascade; create schema public;"); } test("POST to /api/v1/migrations should be return 200", async () => { // Primeira execução: deve aplicar migrações pendentes const response1 = await fetch("http://localhost:3000/api/v1/migrations", { method: "POST", }); expect(response1.status).toBe(201); const response1Body = await response1.json(); expect(Array.isArray(response1Body)).toBe(true); expect(response1Body.length).toBeGreaterThan(0); // Segunda execução: não deve haver migrações pendentes const response2 = await fetch("http://localhost:3000/api/v1/migrations", { method: "POST", }); expect(response2.status).toBe(200); const response2Body = await response2.json(); expect(Array.isArray(response2Body)).toBe(true); expect(response2Body.length).toBe(0); }); ``` -------------------------------- ### Development Environment Variables for PostgreSQL Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Defines the environment variables required for connecting to the PostgreSQL database in a development context. This `.env.development` file is used by `dotenv-expand` for variable interpolation, specifying host, port, database name, user, password, and the complete database URL. ```bash # .env.development POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_DB=local_db POSTGRES_USER=local_user POSTGRES_PASSWORD=local_password DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB ``` -------------------------------- ### Docker Compose for PostgreSQL Development Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt Docker Compose configuration for running a PostgreSQL database in a development environment. It uses the Alpine image for a smaller footprint and automatically loads environment variables for service configuration. ```yaml services: db: image: postgres:16-alpine container_name: clone-tabnews-db restart: always ports: - "5432:5432" volumes: - ./.docker/db/data:/var/lib/postgresql/data environment: POSTGRES_USER: "tabnews_user" POSTGRES_PASSWORD: "tabnews_password" POSTGRES_DB: "tabnews_db" PGDATA: "/var/lib/postgresql/data" ``` -------------------------------- ### Execute SQL Queries with Database Module (JavaScript) Source: https://context7.com/sanotsroger/clone-tabnews/llms.txt A utility function to execute SQL queries against PostgreSQL, managing connections automatically. It supports plain SQL strings and parameterized queries to prevent SQL injection. The results are returned in a structured format. ```javascript import database from "infra/database.js"; // Query simples const versionResult = await database.query("SHOW server_version;"); console.log(versionResult.rows[0].server_version); // Saída: "16.0" // Query parametrizada (prevenção de SQL injection) const connectionsResult = await database.query({ text: "SELECT COUNT(0)::int FROM pg_stat_activity WHERE datname = $1", values: ["local_db"], }); console.log(connectionsResult.rows[0].count); // Saída: 1 // Query para verificar configurações const maxConnResult = await database.query("SHOW max_connections;"); console.log(maxConnResult.rows[0].max_connections); // Saída: "100" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.