Skip to content

RESTful API built with TypeScript, Express, and PostgreSQL, providing full CRUD functionality for project management and integrating Google Gemini AI for enhanced automation and insights.

nataliahe24/project-api-rest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Project API REST

RESTful API for project management with CRUD operations, built with Node.js, TypeScript, Express, Prisma, and PostgreSQL.

πŸš€ Features

  • βœ… CRUD Operations for Project entity
  • βœ… AI-Powered Analytics with Google Gemini for project insights
  • βœ… Aggregated Statistics for data visualization and reporting
  • βœ… TypeScript with strict mode and ESM
  • βœ… Prisma ORM with PostgreSQL
  • βœ… Express Validator for request validation
  • βœ… Swagger UI for API documentation at /docs
  • βœ… Business Logic Validation (endDate requirements based on status)
  • βœ… Custom Error Handling with structured error responses
  • βœ… Jest Tests with 100% coverage on utils and validation
  • βœ… Clean Code architecture (controllers, services, middlewares)

πŸ“‹ Prerequisites

  • Node.js >= 18
  • PostgreSQL database
  • npm or yarn

⚑ Quick Start

Visit http://localhost:3000/docs for Swagger documentation.

πŸ› οΈ Detailed Installation

Step 1: Clone the repository

git clone https://github.com/nataliahe24/project-api-rest.git
cd project-api-rest

Step 2: Install production dependencies

npm install express cors @prisma/client dotenv swagger-ui-express swagger-jsdoc express-validator

Step 3: Install development dependencies

npm install -D typescript ts-node tsx nodemon prisma @types/node @types/express @types/cors @types/swagger-jsdoc @types/swagger-ui-express

Step 4: Install AI and analytics dependencies

npm install @google/generative-ai

Step 5: Install testing dependencies

npm install -D jest ts-jest @jest/globals @types/jest

Step 6: Configure environment variables

Create a .env file in the root directory:

DATABASE_URL="postgresql://postgres:password@localhost:5432/name_db"
PORT=?

Database URL Format:

postgresql://USER:PASSWORD@HOST:PORT/DATABASE

Getting your Gemini API Key:

  1. Visit Google AI Studio
  2. Sign in with your Google account
  3. Click "Create API Key" or "Get API Key"
  4. Copy the key and paste it in your .env file

Note: The Gemini API has a generous free tier. The API key is required for the AI analytics endpoint.

Step 7: Initialize Prisma (if starting from scratch)

npx prisma init --datasource-provider postgresql

Step 8: Run Prisma migrations

This command creates the database tables based on your schema:

npx prisma migrate dev --name init

Note: If you make changes to prisma/schema.prisma, run migrations again:

npx prisma migrate dev --name your_migration_name

Step 9: Generate Prisma Client

npx prisma generate

Note: Run this command every time you change the Prisma schema.

πŸƒ Running the Application

Available Scripts

Script Command Description
Development npm run dev Start development server with hot reload
Test npm test Run all tests with Jest
Test Watch npm run test:watch Run tests in watch mode
Test Coverage npm run test:coverage Run tests with coverage report

Development Mode

npm run dev

πŸš€ Server running at: http://localhost:${PORT}

Available Endpoints

πŸ§ͺ Testing

Run all tests

npm test

Run tests in watch mode

npm run test:watch

Run tests with coverage

npm run test:coverage

Test Coverage

Current coverage for core business logic:

  • Utils: 100% coverage (AppError, DateIsRequired) - 20 tests
  • Validations: 100% coverage (body.validation) - 15 tests
  • Service: Mocked Prisma tests - 20 tests

Total: 55 tests βœ…

πŸ“š API Endpoints

Projects

Method Endpoint Description
GET /project Get all projects
GET /project/:id Get project by ID
POST /project Create a new project
PUT /project/:id Update a project
DELETE /project/:id Delete a project

Analytics πŸ€–

Method Endpoint Description
GET /analytics/graphics Get aggregated project statistics by status
GET /analytics/:id Generate AI-powered analysis for a project

Analytics Endpoints Details

GET /analytics/graphics - Project Statistics

Get aggregated data for charts and visualizations.

Response (200 OK):

{
  "totalProjects": 10,
  "projectsByStatus": [
    {
      "status": "in progress",
      "count": 6,
      "percentage": 60.0
    },
    {
      "status": "completed",
      "count": 4,
      "percentage": 40.0
    }
  ],
  "completedProjects": 4,
  "inProgressProjects": 6
}

Use Cases:

  • Generate pie/donut charts showing project distribution by status
  • Create bar charts with project counts per status
  • Display KPIs and metrics in dashboards
  • Generate executive reports with portfolio metrics

GET /analytics/:id - AI-Powered Project Analysis

Generate an AI-powered executive summary for a specific project using Google Gemini.

Parameters:

  • id (path parameter) - Project ID

Response (200 OK):

{
  "summary": "This Cloud Migration project aims to transition internal servers and storage to AWS infrastructure. Key objectives include improved scalability, cost optimization, and enhanced reliability. Currently in progress, the migration demonstrates forward-thinking IT strategy. Recommendations: ensure comprehensive backup procedures, staff training on AWS services, and phased implementation to minimize disruption.",
  "totalProjects": 1,
  "generatedAt": "2025-10-20T12:30:45.123Z"
}

Error Responses:

  • 404 Not Found - Project doesn't exist
{
  "message": "Project not found",
  "statusCode": 404,
  "type": "NotFoundError"
}
  • 500 Internal Server Error - AI service unavailable or API key not configured
{
  "message": "Failed to generate AI analysis. Please try again later.",
  "statusCode": 500,
  "type": "AIServiceError"
}

Use Cases:

  • Generate executive summaries automatically for reports
  • Identify patterns and trends in project portfolio
  • Obtain insights for strategic decision-making
  • Prepare presentations for stakeholders
  • Monthly/quarterly portfolio analysis

Requirements:

  • Valid GEMINI_API_KEY in environment variables
  • Active internet connection
  • Project must exist in database

Request/Response Examples

POST /project - Create Project

Request Body:

{
  "name": "New Project",
  "description": "Project description",
  "status": "in progress",
  "startDate": "2025-01-01T00:00:00.000Z"
}

Response (201 Created):

{
  "id": 1,
  "name": "New Project",
  "description": "Project description",
  "status": "in progress",
  "startDate": "2025-01-01T00:00:00.000Z",
  "endDate": null,
  "createdAt": "2025-10-19T06:00:00.000Z",
  "updatedAt": "2025-10-19T06:00:00.000Z"
}

POST /project - Create Completed Project

Request Body:

{
  "name": "Completed Project",
  "description": "This project is done",
  "status": "completed",
  "startDate": "2025-01-01T00:00:00.000Z",
  "endDate": "2025-12-31T00:00:00.000Z"
}

PUT /project/:id - Update Project (Partial Update)

Request Body:

{
  "status": "completed",
  "endDate": "2025-12-31T00:00:00.000Z"
}

Business Rules

Project Status Validation

  1. Status: "in progress"

    • endDate is optional (can be null or omitted)
    • If endDate is provided β†’ 400 Error
  2. Status: "completed"

    • endDate is required
    • If endDate is missing/null β†’ 400 Error

Validation Examples

❌ Invalid - Completed without endDate:

{
  "name": "Project",
  "status": "completed",
  "startDate": "2025-01-01T00:00:00.000Z"
}

Response: 400 Bad Request

{
  "message": "End date is required when status is Completed"
}

❌ Invalid - In progress with endDate:

{
  "name": "Project",
  "status": "in progress",
  "startDate": "2025-01-01T00:00:00.000Z",
  "endDate": "2025-12-31T00:00:00.000Z"
}

Response: 400 Bad Request

{
  "message": "End date is not allowed when status is In Progress"
}

πŸ—οΈ Project Structure

project-api-rest/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.ts                         # Express application setup
β”‚   β”œβ”€β”€ configurations/
β”‚   β”‚   └── swagger.ts                 # Swagger/OpenAPI configuration
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ analytics.controller.ts   # Analytics request handlers
β”‚   β”‚   └── project.controller.ts     # Project request handlers
β”‚   β”œβ”€β”€ interfaces/
β”‚   β”‚   β”œβ”€β”€ analytics.interface.ts    # Analytics TypeScript interfaces
β”‚   β”‚   └── project.interface.ts      # Project TypeScript interfaces
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   β”œβ”€β”€ body.validation.ts        # Express-validator rules
β”‚   β”‚   β”œβ”€β”€ global.error.handle.ts    # Global error handler
β”‚   β”‚   β”œβ”€β”€ validate.request.ts       # Validation middleware
β”‚   β”‚   └── __tests__/                # Middleware tests
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ index.ts                  # Dynamic route loader
β”‚   β”‚   β”œβ”€β”€ analytics.ts              # Analytics routes
β”‚   β”‚   └── project.ts                # Project routes
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ analytics.service.ts      # Analytics business logic with AI
β”‚   β”‚   β”œβ”€β”€ project.service.ts        # Project business logic
β”‚   β”‚   └── __tests__/                # Service tests
β”‚   └── utils/
β”‚       β”œβ”€β”€ app.error.ts              # Custom error class
β”‚       β”œβ”€β”€ validate.date.ts          # Date validation utility
β”‚       └── __tests__/                # Utility tests
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma                 # Prisma schema
β”‚   └── migrations/                   # Database migrations
β”œβ”€β”€ jest.config.cjs                   # Jest configuration
β”œβ”€β”€ tsconfig.json                     # TypeScript configuration
└── package.json                      # Project dependencies

πŸ”§ Technologies

  • Node.js - Runtime environment
  • TypeScript - Type-safe JavaScript
  • Express 5 - Web framework
  • Prisma - ORM for PostgreSQL
  • PostgreSQL - Relational database
  • Google Gemini AI - AI-powered project analysis
  • Swagger UI Express - API documentation
  • Express Validator - Request validation
  • Jest - Testing framework
  • ts-jest - TypeScript preprocessor for Jest

πŸ”¨ Useful Commands

Prisma Commands

# View your database in Prisma Studio (GUI)
npx prisma studio

# Create a new migration after schema changes
npx prisma migrate dev --name migration_name

# Apply pending migrations
npx prisma migrate deploy

# Reset database (WARNING: deletes all data)
npx prisma migrate reset

# Regenerate Prisma Client after schema changes
npx prisma generate

# Format your Prisma schema file
npx prisma format

# Validate your Prisma schema
npx prisma validate

Development Commands

# Run development server
npm run dev

# Run tests once
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

πŸ› Troubleshooting

Database Connection Issues

Problem: P1001: Can't reach database server

Solution:

  1. Ensure PostgreSQL is running
  2. Check your .env file has correct credentials
  3. Verify database exists: psql -U postgres -c "CREATE DATABASE projects_db;"

Prisma Client Not Found

Problem: Cannot find module '@prisma/client'

Solution:

npm install @prisma/client
npx prisma generate

Migration Errors

Problem: Schema drift detected

Solution:

npx prisma migrate reset
npx prisma migrate dev

Test Failures

Problem: Tests failing due to module resolution

Solution: Ensure you're using Node.js >= 18 and run:

npm install
npm test

πŸ“– Database Schema

model Project {
  id          Int       @id @default(autoincrement())
  name        String
  description String?
  status      String
  startDate   DateTime
  endDate     DateTime?
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
}

🎯 Testing Strategy

Tests focus on critical business logic:

  1. DateIsRequired Utility (validate.date.test.ts)
  • βœ… Status "completed" requires endDate
  • βœ… Status "in progress" rejects endDate
  • βœ… Proper error throwing with AppError
  • βœ… Edge cases (empty strings, null values)
  • βœ… ISO date string handling
  1. AppError Class (app.error.test.ts)
  • βœ… Default values (statusCode: 400, type: "AppError")
  • βœ… Custom statusCode and type
  • βœ… Error inheritance from Error class
  • βœ… Throwable and catchable
  • βœ… Stack trace preservation

3. Request Validations (body.validation.test.ts)

  • βœ… POST: Required fields validation
  • βœ… PUT: Optional fields (partial updates)
  • βœ… Status enum validation (case-insensitive)
  • βœ… Date format validation (ISO8601)
  • βœ… Empty body handling for PUT

4. Service with Mocked Prisma (project.service.test.ts)

  • βœ… getProjects: Returns all projects, handles empty arrays
  • βœ… getProjectById: Returns project by ID, throws AppError (404) when not found
  • βœ… createProject: Creates in progress/completed projects, validates endDate rules
  • βœ… updateProject: Updates fields, validates status transitions, enforces business rules
  • βœ… deleteProject: Deletes projects, validates existence before deletion
  • βœ… Uses mocked PrismaClient for isolated unit testing

Running Tests

# Run all tests
npm test

# Watch mode (auto-rerun on changes)
npm run test:watch

# With coverage report
npm run test:coverage

Test Results

Test Suites: 4 passed, 4 total
Tests:       52 assed, 52total
Snapshots:   0 total
Time:        ~10s

πŸ› Error Handling

The API uses structured error responses:

{
  "message": "Error message",
  "statusCode": 400,
  "type": "ValidationError"
}

Error Types:

  • ValidationError (400) - Input validation failed
  • NotFoundError (404) - Resource not found
  • AppError (400) - General application error

πŸ“ Git Commit Strategy

  • feat: New features
  • fix: Bug fixes
  • refactor: Code changes without affecting functionality
  • test: Adding or updating tests
  • chore: Maintenance tasks
  • docs: Documentation changes

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feat/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feat/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

ISC

πŸ‘€ Author

Natalia Henao


Built with ❀️ using TypeScript, Express, and Prisma

About

RESTful API built with TypeScript, Express, and PostgreSQL, providing full CRUD functionality for project management and integrating Google Gemini AI for enhanced automation and insights.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published