How bili20/encurtador-de-url works
Project Type and Purpose
• This is a full-stack web application: a URL shortener built with Node.js/TypeScript on the backend and a minimal frontend (static HTML/JS/CSS).
• It exposes HTTP endpoints to shorten URLs, redirect requests, implements rate limiting, caching, and scheduled jobs for popular-URL optimization.
File Structure
• src/
• config/db → PostgreSQL (Knex) and Redis connection setup
• controller → Express controllers for URL shortening and redirection
• middlewares → rateLimit.ts (uses Redis to throttle)
• model → URL data model and repository interface
• repository → PostgreSQL repository implementation
• service → business logic (generate short IDs, validate, cache check/write)
• jobs → scheduled tasks (cachesPopular.ts runs periodically to pre-cache hot URLs in Redis)
• routes → wires controllers to Express router
• app.ts → initializes Express, loads middleware, routes, error handling
• views/ → static frontend files (HTML + script.ts → compiled JS, CSS)
• docker-compose.yml → orchestrates three containers: app, PostgreSQL, Redis
• sample.env → environment variables (DB credentials, Redis URL, rate limit thresholds)
Extract Key Points from the README
• Tech Stack: Node.js, TypeScript, Express, Knex.js, PostgreSQL, Redis, Docker
• Features: URL shortening, rate limiting, redirect, simple UI, copy-to-clipboard, auto-cache popular URLs, scheduled jobs
a. Main Components
1. Client (Browser) – static UI served by Express + user interaction
2. API Server (Express/TypeScript)
3. PostgreSQL Database (persistent URL mappings)
4. Redis Cache (hot URL lookup & rate-limit counters)
5. Job Scheduler (cron job inside the same container or a separate worker process)
6. Infrastructure Orchestration (Docker Compose)
b. Relationships & Data Flows
• Browser → HTTP POST /shorten → Rate-Limit Middleware → Controller → Service
• Service checks Redis cache → if miss, writes to PostgreSQL via Repository → returns short code
• Browser → HTTP GET /:shortCode → Controller → Service
• Service checks Redis cache → if hit, redirect immediately
• if miss, query PostgreSQL → set Redis → redirect
• Job Scheduler (cachesPopular.ts)
• Periodically queries PostgreSQL for most-accessed URLs → populates Redis keys
• Rate-Limit Middleware
• On each incoming request, increments a Redis counter per IP → rejects if threshold exceeded
c. Architectural Patterns & Principles
• Layered architecture (Controller → Service → Repository → DB)
• Interface-based repository (urlsRepository.interface.ts) enabling swap of persistence layer
• Cache-Aside pattern for Redis (check-then-load then write)
• Middleware pipeline in Express
• Docker-based isolation of services
d. Key Technologies & Frameworks
• Node.js + Express (HTTP server)
• TypeScript (static typing)
• Knex.js (SQL query builder)
• PostgreSQL (relational persistence)
• Redis (caching & rate limiting)
• Docker Compose (local multi-container orchestration)