Skip to main content

System requirements

Ensure your system meets these requirements before installation:

Required software

  • Node.js - Version 16.x or higher
  • PostgreSQL - Version 12.x or higher
  • npm - Version 7.x or higher (comes with Node.js)

Optional tools

  • Docker & Docker Compose - For containerized deployment
  • Git - For version control
  • Postman or Insomnia - For API testing

Installation methods

Clone the repository

git clone https://github.com/Goncar29/proyecto.git
cd proyecto

Install dependencies

npm install
This will install all required packages including:
  • express - Web framework
  • @prisma/client - Database client
  • jsonwebtoken - JWT authentication
  • bcryptjs - Password hashing
  • joi - Request validation
  • swagger-ui-express - API documentation

Database setup

Create a PostgreSQL database

Connect to your PostgreSQL server and create a new database:
CREATE DATABASE medical_appointments;
Or use the PostgreSQL command line:
psql -U postgres
CREATE DATABASE medical_appointments;
\q

Configure the database connection

The API uses Prisma ORM to interact with PostgreSQL. Configure your database connection in the .env file:
DATABASE_URL="postgresql://username:password@localhost:5432/medical_appointments?schema=public"
Replace:
  • username - Your PostgreSQL username (default: postgres)
  • password - Your PostgreSQL password
  • localhost:5432 - Your database host and port
  • medical_appointments - Your database name

Environment configuration

Create environment file

Copy the example environment file:
cp .env-example .env

Configure environment variables

Edit .env with your specific configuration:
.env
PORT=3005
NODE_ENV=development
SALT_ROUNDS=11
DATABASE_URL=postgresql://postgres:your_password@localhost:5432/medical_appointments?schema=public
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

Environment variable reference

VariableDescriptionDefaultRequired
PORTServer port number3005No
NODE_ENVEnvironment modedevelopmentNo
SALT_ROUNDSbcrypt salt rounds for password hashing11No
DATABASE_URLPostgreSQL connection string-Yes
JWT_SECRETSecret key for signing JWT tokens-Yes
Security Best Practices:
  • Use a strong, randomly generated JWT_SECRET in production
  • Never commit your .env file to version control
  • Use different secrets for development and production environments
  • Consider using environment-specific .env.production and .env.development files

Database migrations

Run Prisma migrations

Create the database schema by running migrations:
npx prisma migrate dev
This command will:
  1. Create all necessary tables based on the Prisma schema
  2. Generate the Prisma Client
  3. Apply all pending migrations

Prisma schema overview

The database includes these main tables: User table:
model User {
  id               Int       @id @default(autoincrement())
  name             String
  email            String    @unique
  password         String
  role             Role
  isActive         Boolean   @default(true)
  isSuspended      Boolean   @default(false)
  suspensionReason String?
  deletedAt        DateTime?
  createdAt        DateTime  @default(now())
  updatedAt        DateTime  @updatedAt

  appointments       Appointment[] @relation("PatientAppointments")
  doctorAppointments Appointment[] @relation("DoctorAppointments")
  timeBlocks         TimeBlock[]
  auditLogs          AuditLog[]
}
Appointment table:
model Appointment {
  id          Int               @id @default(autoincrement())
  date        DateTime
  timeBlockId Int               @unique
  patientId   Int
  doctorId    Int
  status      AppointmentStatus @default(PENDING)
  notes       String?
  reason      String?
  createdAt   DateTime          @default(now())
  updatedAt   DateTime          @updatedAt

  timeBlock TimeBlock @relation(fields: [timeBlockId], references: [id])
  patient   User      @relation("PatientAppointments", fields: [patientId], references: [id])
  doctor    User      @relation("DoctorAppointments", fields: [doctorId], references: [id])
}

Generate Prisma Client

Generate the type-safe Prisma Client:
npx prisma generate
The Prisma Client provides type-safe database access and is imported in the application:
const prisma = require('./utils/prismaClient');

Seed the database

Load sample data

Populate the database with initial test data:
node prisma/seed.js
The seed script creates:
  • Sample user accounts with different roles (Admin, Doctor, Patient)
  • Example time blocks for doctor availability
  • Sample appointments
Seeding is optional and primarily useful for development and testing. Skip this step in production environments.

Start the server

Development mode

Run the server with auto-reload on file changes:
npm run dev
This uses Node.js’s --watch flag to automatically restart when files change.

Production mode

Run the server in production mode:
npm start

Verify the server is running

You should see output similar to:
Servidor escuchando en el puerto http://localhost:3005

Verification steps

Test the base endpoint

Verify the server is responding:
curl http://localhost:3005/
Expected response:
Hola, mundo!

Access Swagger documentation

Open your browser and navigate to:
http://localhost:3005/api-docs
You should see the interactive Swagger UI with all API endpoints documented.

Test database connection

Verify Prisma can connect to the database:
npx prisma studio
This opens Prisma Studio, a visual database browser at http://localhost:5555.

Register a test user

Create a test user account:
curl -X POST http://localhost:3005/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "testPassword123",
    "name": "Test User",
    "role": "PATIENT"
  }'
Expected response:
{
  "message": "Usuario registrado con éxito"
}

Troubleshooting

Common issues

Database connection failed
  • Verify PostgreSQL is running: pg_isready
  • Check your DATABASE_URL in .env
  • Ensure the database exists: psql -l
Port already in use
  • Change the PORT in .env to an available port
  • Kill the process using the port: lsof -ti:3005 | xargs kill -9
Prisma Client errors
  • Regenerate the client: npx prisma generate
  • Clear the Prisma cache: rm -rf node_modules/.prisma
Migration errors
  • Reset the database: npx prisma migrate reset
  • Check for schema conflicts in prisma/schema.prisma
Using prisma migrate reset will delete all data in your database. Only use this in development environments.

Next steps

Quickstart Guide

Follow our quickstart to make your first API calls

Authentication

Learn how to authenticate users and manage JWT tokens

User Roles

Understand role-based access control in the system

Time Blocks

Learn about the time block and appointment system

Build docs developers (and LLMs) love