Skip to main content

Prerequisites

Before you begin, ensure you have the following installed:

Node.js

Version 18 or higher

PostgreSQL

Version 12 or higher

Git

For cloning the repository

Installation

Follow these steps to get the DAF Backend API running on your local machine:
1

Clone the repository

Clone the DAF Backend repository from GitHub:
git clone https://github.com/GoldenKra64/daf-backend.git
cd daf-backend
2

Install dependencies

Install all required npm packages:
npm install
This will install Express.js, PostgreSQL client (pg), JWT, Multer, and all other dependencies listed in package.json.
3

Configure environment variables

Create a .env file in the root directory with the following variables:
# Server Configuration
PORT=3000
FRONTEND_IP=http://localhost:5173

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRES_IN=24h

# POS Database Configuration
POS_HOST=localhost
POS_PORT=5432
POS_NAME=daf_pos_db
# Note: POS user/password come from JWT token, not from .env

# E-commerce Database Configuration
EC_HOST=localhost
EC_PORT=5432
EC_NAME=daf_ecom_db
EC_USER=ecom_user
EC_PASSWORD=your-ecom-db-password

# Application Settings
PAGINATION_LIMIT=20
ACTIVE_STATUS_INDEPENDENT=ACT
INACTIVE_STATUS_INDEPENDENT=INA
Important: Change JWT_SECRET to a strong, random value in production. Never commit your .env file to version control.
4

Set up PostgreSQL databases

Create two PostgreSQL databases:
-- Create POS database
CREATE DATABASE daf_pos_db;

-- Create E-commerce database
CREATE DATABASE daf_ecom_db;

-- Create e-commerce database user
CREATE USER ecom_user WITH PASSWORD 'your-ecom-db-password';
GRANT ALL PRIVILEGES ON DATABASE daf_ecom_db TO ecom_user;
For the POS database, you’ll create individual user accounts with specific permissions. These users will authenticate through the API.
5

Run database migrations

Run your database schema migrations to create all required tables. The API expects tables for:POS Database: cliente, producto, factura, proveedor, materiaprima, categoria, kardex_mp, kardex_prod, etc.ECOM Database: usuario, cliente, producto, carrito, detalle_carrito, ciudad, etc.
6

Start the development server

Start the API server with hot-reloading:
npm run dev
You should see:
🚀 Servidor ejecutándose en http://localhost:3000
The dev script uses Node.js --watch flag for automatic restarts on file changes.

Verify installation

Test that the API is running correctly:
Try accessing a non-existent route to verify the 404 handler:
curl http://localhost:3000/health
Expected response:
{"message":"Not Found"}

Make your first API call

Now let’s authenticate and make an API call:
1

Authenticate with POS system

First, create a PostgreSQL user for POS access:
-- In your POS database
CREATE USER pos_user WITH PASSWORD 'pos_password';
GRANT CONNECT ON DATABASE daf_pos_db TO pos_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO pos_user;
Then authenticate via the API:
curl -X POST http://localhost:3000/api/pos/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "user": "pos_user",
    "password": "pos_password"
  }'
{
  "message": "Login exitoso",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "role": "usuario"
}
2

Use the JWT token

Save the token from the response and use it in subsequent requests:
export TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

curl http://localhost:3000/api/pos/cliente \
  -H "Authorization: Bearer $TOKEN"
This will return a paginated list of clients from the POS database.
3

Register an e-commerce user

For the e-commerce system, register a new user:
curl -X POST http://localhost:3000/api/ecom/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123",
    "cli_ruc_ced": "1234567890",
    "cliente": {
      "cli_nombre": "John Doe",
      "cli_telefono": "0998765432",
      "cli_celular": "987654321",
      "cli_direccion": "123 Main St",
      "ct_codigo": "001"
    }
  }'
Then login:
curl -X POST http://localhost:3000/api/ecom/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "SecurePass123"
  }'

CORS configuration

The API is configured to accept requests from specific origins:
src/app.js:29-35
let corsConfiguration = {
  origin: process.env.FRONTEND_IP ? [process.env.FRONTEND_IP] : ['http://localhost:5173', 'http://localhost:5174'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}
app.use(cors(corsConfiguration));
By default, the API accepts requests from http://localhost:5173 and http://localhost:5174. Modify FRONTEND_IP in your .env file to add your frontend’s URL.

Common issues

Error: Credenciales incorrectas o error de conexiónSolutions:
  • Verify PostgreSQL is running: pg_isready
  • Check database names in .env match actual databases
  • Ensure database users have correct permissions
  • For POS: Verify the user exists in PostgreSQL
  • For ECOM: Check EC_USER and EC_PASSWORD in .env
Error: Token inválido o expiradoSolutions:
  • Check that JWT_SECRET in .env hasn’t changed
  • Verify token is being sent in Authorization: Bearer <token> format
  • Token may have expired (default 24h) - login again
Error: EADDRINUSE: address already in use ::3000Solutions:
  • Change PORT in .env to a different value
  • Kill the process using port 3000: lsof -ti:3000 | xargs kill
Error: Solo se permiten imágenesSolutions:
  • Ensure you’re sending image files (JPEG, PNG, etc.)
  • Check file size is under 5MB limit
  • Verify src/images directory exists and is writable

Next steps

Authentication

Learn about JWT structure and credential-based connections

Architecture

Understand the dual-database architecture

POS API Endpoints

Explore all available POS endpoints

Error Handling

Learn about error responses and debugging

Build docs developers (and LLMs) love