Back

Technical proposal

Backend — News & Projects Application

Confidential document · Client version

Introduction

This document describes the backend development plan for a hybrid platform: social network and newspaper focused on news and nearby projects. It includes hexagonal architecture, publication flows with AI verification and administrative approval, and agreed technologies (React Native for the mobile app, REST API backend).

We will handle the backend in full: hexagonal architecture, API, database, authentication, integration with AI services for content verification, file storage, testing, CI/CD and cloud deployment.

Project vision: social network and newspaper

The system combines social network and newspaper: users upload nearby projects, can create news according to their role, and content goes through AI verification and/or administrator approval before publication.

Nearby projects

Users upload and share nearby projects (initiatives, works, local events). These projects are social content and context for news.

User types and publishing

Verified journalists: recognised users who pass verification and can publish news directly. Other users: can create news but require AI token verification and then administrator approval for publication.

AI verification

AI tokens will be used to check that news submitted by unverified users meets quality and consistency criteria. The verification result feeds the approval flow.

Administrative approval

An administrator reviews and approves news that passed AI verification (or rejects it). Only approved content is published in the “newspaper” visible to all.

Summary: Social network (nearby projects, creator users) + newspaper (curated content). Two publication paths: verified journalist → direct publication; standard user → AI verification → admin approval → publication.

Using React Native for the mobile app

The mobile app (reading news, uploading nearby projects, users creating news) will be developed with React Native. The choice is justified by widespread industry adoption and the benefits it brings to the project:

Hexagonal architecture (Ports & Adapters)

The backend will be developed using hexagonal architecture: the domain core (business logic, publication rules, verification) is isolated from technical details; communication with the outside is through ports (interfaces) and adapters (concrete implementations).

Benefits for this project: independence from frameworks and databases, unit testing of the domain without infrastructure, and the ability to change or add adapters (another API, another AI provider, another storage) without rewriting business logic.

Diagram: applying the hexagonal pattern in the project

flowchart TB subgraph Entrada["Input ports/adapters"] REST[REST API] Panel[Admin web panel] end subgraph Nucleo["Core (domain)"] Services[Application services] Reglas[Rules: publish, verify, approve] end subgraph Salida["Output ports/adapters"] PG[(PostgreSQL)] Redis[(Redis)] S3[S3 / storage] IA[AI provider] end REST --> Services Panel --> Services Services --> Reglas Services --> PG Services --> Redis Services --> S3 Services --> IA

Project structure and operation

High-level view: mobile app (React Native), hexagonal backend, admin panel and differentiated publication flows.

flowchart LR A[App React Native] B[Backend API] C[Admin panel] A -->|News, projects, publish| B C -->|Approve, manage| B B -->|Publish, data| A

Load efficiency and offline reading

  • Last news flag: The endpoint will expose a flag (timestamp or version) of the last published news. The app can query only this value to decide if there is new content.
  • Local cache and offline reading: The app will have local cache (e.g. device storage) allowing users to read news when offline, using the last downloaded copy.
  • Conditional loading: Loading will be efficient because news will only be requested from the API when the user's last registered news is older than the endpoint flag. If the flag has not changed, the app will use cache and avoid unnecessary bandwidth and network time.

Optimised queries, server cache (Redis), low response times and a fast experience in both the web editor and the app will be maintained.

Agreed technical specifications

Node.js with TypeScript (2+ years)
NestJS (Node.js + TypeScript)
PostgreSQL — model, indexes, optimisation
Redis — cache and queues (BullMQ or similar)
Well-designed REST API
JWT (access + refresh tokens)
Validation, sanitisation and API security
Unit and integration tests (Jest)
Git flow, PRs, conventional commits
CI/CD (GitHub Actions or similar)
Deployment with Dokku
S3 or equivalent for files/images
Environment variables and secrets
Autonomous work as sole backend
React Native (mobile app)
Hexagonal architecture
AI content verification (tokens)

API framework and deployment with Dokku

The main frameworks for building this platform's API were compared. Production deployment will use Dokku (self-hosted Heroku-like PaaS, deploy via git push, support for PostgreSQL, Redis and environment variables).

Framework comparison for this API

Framework Language Strengths Fit for this project
NestJS Node.js / TypeScript Module architecture and dependency injection, ideal for hexagonal; TypeScript (typing, safe refactor); ecosystem: TypeORM/Prisma, Bull/BullMQ, class-validator, JWT; same language for API and workers. Very high: fits hexagonal, complex flows (approval, AI), queues and validation; Dokku supports Node natively.
Laravel PHP Rapid development, Eloquent, queues and cache with Redis, Sanctum/Passport, mature ecosystem. High: good CRUD and queues; hexagonal needs more discipline; PHP less common in teams already using React Native/Node.
FastAPI Python Async, automatic OpenAPI docs, Pydantic; strong for ML/AI integration in the same language. Medium: excellent for pure APIs; project only consumes an external AI API (HTTP), does not run models; less convention for CRUD + workflows than NestJS/Laravel.
Go (Gin / Fiber) Go Performance, single binary, native concurrency; very good on Dokku. Medium: more boilerplate for auth, validation, queues and approval flows; fewer "batteries included" for this type of API.

Choice: NestJS (Node.js + TypeScript)

NestJS with Node.js and TypeScript will be used for this API because it fits directly with the hexagonal architecture we want to apply: modules and dependency injection allow defining ports (interfaces) in the core and injecting adapters (PostgreSQL repositories, AI client, S3 storage) without coupling business logic to the framework. TypeScript typing reduces errors and eases maintenance for a developer working alone on the backend. NestJS offers native support for queues (Bull/BullMQ con Redis), validation with DTOs and class-validator, guards for JWT and roles, and a clear structure by domain (news, projects, users, approvals), which speeds up implementing flows como “verificación IA → aprobación admin” and the distinction between verified journalists and standard users. Integration with AI providers is trivial (HTTP calls from core services). Finally, deployment with Dokku is straightforward (Node buildpack, Procfile, environment variables for DB and Redis), and the same runtime serves both the API and workers that process verification or notification queues.

Dokku: Dokku will be used as the deployment platform. It allows deploy via git push, containerised app management, add-ons or linking of PostgreSQL and Redis, and domain and SSL configuration. Compatible with the NestJS + Node stack and with CI/CD pipelines (e.g. GitHub Actions) that build and deploy to the Dokku server.

Database: model and development

The backend will use PostgreSQL as the main engine. The model supports social network + newspaper: users uploading nearby projects, news with AI verification and administrative approval flow, and roles for verified journalists (direct publish) vs users requiring approval. Below: tables and entity-relationship diagram.

Model tables

Table Description and main columns
roles System roles: admin, editor, verified_journalist (verified journalist, publishes directly), user (requires approval). Columns: id, name, slug, timestamps.
users Users. Columns: id, name, email, password (hash), role_id (FK), email_verified_at, remember_token, timestamps. Role determines whether they can publish directly or must go through approval.
projects Nearby projects uploaded by users. Columns: id, user_id (FK), name, slug, description, location (or lat/lng), status, timestamps. Social network content.
categories Categories/topics to classify news. Columns: id, name, slug, parent_id (optional), timestamps.
news News with publication flow. Columns: id, title, slug, excerpt, body, category_id (FK), user_id (author), project_id (FK optional), status (draft, pending_ai_review, pending_approval, published, rejected), ai_verified_at, ai_verification_result (or JSON), approved_by (FK user, admin), approved_at, published_at, timestamps.
comments Comments on news. Columns: id, news_id (FK), user_id (FK), body, parent_id (replies), timestamps.
media Files/images (polymorphic: news or project). Columns: id, path, url, type, mediaable_id, mediaable_type, order, timestamps.
refresh_tokens JWT refresh tokens. Columns: id, user_id (FK), token (hash), expires_at, revoked_at, timestamps.
password_reset_tokens Password reset tokens (forgot/reset). Columns: id, user_id (FK), token, expires_at, used_at, timestamps.
Profile User profile (1:1). Columns: id, userId (FK UNIQUE), firstName, lastName, address, avatar, lastConnectionAt, lastNewsDownloadedId (FK News), lastCommentId (FK Comment), lastSearch, timestamps. Used by admin panel and app.

Entity-relationship diagram

Users with roles (admin, editor, verified_journalist, user); nearby projects uploaded by users; news with state flow (AI + approval); categories, comments and media. The diagram prints correctly to PDF.

erDiagram ROLES ||--o{ USERS : has USERS ||--o{ PROJECTS : uploads CATEGORIES ||--o{ NEWS : classifies USERS ||--o{ NEWS : writes PROJECTS ||--o{ NEWS : linked_to NEWS ||--o{ COMMENTS : has USERS ||--o{ COMMENTS : writes NEWS ||--o{ MEDIA : attachments PROJECTS ||--o{ MEDIA : attachments USERS ||--o{ REFRESH_TOKENS : tokens USERS ||--o{ PASSWORD_RESET_TOKENS : reset_tokens USERS ||--|| PROFILE : has PROFILE |o--o| NEWS : last_news PROFILE |o--o| COMMENTS : last_comment ROLES { int id PK string name string slug } USERS { int id PK string name string email string password int role_id FK date created_at date updated_at } PROJECTS { int id PK int user_id FK string name string slug string location } CATEGORIES { int id PK string name string slug int parent_id FK } NEWS { int id PK string title string slug string body int category_id FK int user_id FK int project_id FK string status date approved_at int approved_by FK } COMMENTS { int id PK int news_id FK int user_id FK string body } MEDIA { int id PK string path string url string mediaable_type int mediaable_id } REFRESH_TOKENS { int id PK int user_id FK string token date expires_at } PASSWORD_RESET_TOKENS { int id PK int user_id FK string token date expires_at date used_at } PROFILE { int id PK int userId FK,UK string firstName string lastName string address string avatar date lastConnectionAt int lastNewsDownloadedId FK int lastCommentId FK string lastSearch date created_at date updated_at }

Database backup

An automatic backup system will be maintained to ensure data integrity and recovery:

Backups will be stored in secure storage (e.g. S3 or equivalent) and the restore procedure will be documented.

Development with NestJS and PostgreSQL

The API will be developed with NestJS (Node.js + TypeScript) and PostgreSQL, as justified in the previous section. Below: efficiency aspects and capabilities of the chosen stack.

API efficiency analysis with NestJS

How the NestJS + TypeORM/Prisma + Redis stack translates into efficiency and maintainability for this API:

Criterion Efficiency impact / Why this technology
TypeORM/Prisma + relaciones Eager loading and well-defined relations avoid N+1 in news listings (with category, author, project). Fewer DB round-trips and faster API responses.
Redis as cache and queues (BullMQ) Response cache (listings, last-news flag) with TTL; BullMQ queues for AI verification, image processing or background notifications without blocking the HTTP request.
Indexes and queries in PostgreSQL Indexes on published_at, category_id, status and slugs. Optional full-text search. Optimisable execution plans.
Serialisation and DTOs DTOs y class-transformer permiten un formato de respuesta controlado y consistente, reduciendo tamaño de payload y tiempo de parsing en la app React Native.
Guards y rate limiting NestJS guards for JWT and roles; throttling by IP or user to avoid overload and keep response times stable.
Last-news flag “última noticia” en el API Lightweight endpoint (e.g. GET /api/v1/news/last-updated) that returns only timestamp or version. The app compares with its cache and only requests full listing when there is new content.
Modules and dependency injection — Structure by domains (news, projects, users, approvals) and injectable ports for adapters (DB, AI, S3), aligned with hexagonal architecture.
TypeORM/Prisma and migrations — Models and relations aligned with the ER; versioned migrations to evolve the schema without breaking environments; eager loading to avoid N+1.
Security and validation — class-validator in DTOs, input sanitisation, JWT and role guards; refresh tokens stored securely in refresh_tokens.
Queues and cache — BullMQ with Redis for jobs (AI verification, notifications, image processing); Redis cache for listings and last-news flag.
File storage — Integration with S3 (or compatible) via adapters; media associated with news and projects per the ER model.
Testing and deployment — Jest for unit and integration tests; port mocks to test the hexagonal core; CI/CD with GitHub Actions and deployment with Dokku (git push, PostgreSQL and Redis linked).

Development plan by phases

1 Initial setup and architecture
Project. Initialise with NestJS (Node.js + TypeScript). Structure by modules/domains (news, projects, users, categories, approvals) aligned with hexagonal architecture.
Git. Repository with Git flow, main, develop and feature branches. Conventional commits and branch protection with mandatory PRs.
Environment. Variable management with .env and validation on startup (e.g. @nestjs/config or similar). Secrets outside the code.
2 PostgreSQL database
Modelling. Schema design per the ER model (users with roles, nearby projects, news with approval/AI flow, categories, comments, media). Migrations for schema versioning.
Indexes. Indexes on foreign keys, dates and search/filter fields for news listings by category.
Optimisation. Efficient queries, avoiding N+1; pagination in listings; execution plan review when needed.
3 Redis: caché y colas
Cache. Use Redis for response cache (news listings, profiles) with TTL and invalidation strategy on create/update content.
Queues. BullMQ with Redis for background jobs: AI verification, sending notifications, image processing. Workers decoupled from the API (same NestJS runtime).
4 REST API and security
REST design. Clear resources (news, nearby projects, categories, users, approvals), correct HTTP codes, API versioning (e.g. /api/v1/). Documentation with Swagger/OpenAPI.
Validation and sanitisation. DTOs with class-validator and class-transformer, input sanitisation to prevent injection. Throttling (rate limiting) on public endpoints.
Security. Security headers (CORS, Helmet), OWASP best practices applied to the backend.
AI verification. Integration with AI provider (tokens) to review news submitted by unverified users; result stored in the state flow and available to the administrator for approval.
5 JWT authentication
Tokens. Access token (short-lived) and refresh token (stored in refresh_tokens, optional rotation). Login, refresh and logout endpoints.
Route protection. Guards/middlewares that validate JWT and roles/permissions for access to news, categories and user resources.
6 File storage (S3 or equivalent)
Storage service. Integration with S3 (or compatible) for images and attachments of news and nearby projects; polymorphic media table (news, project).
Flow. Signed upload or via API, URL storage in DB, deletion policy and permissions consistent with the rest of the system.
7 Testing (unit and integration)
Unit. Tests for services, validators and business logic with mocks of repositories and external dependencies (Jest).
Integration. Tests for critical endpoints (auth, news, projects, approval flow, AI verification) with test DB and Redis or containers. Minimum agreed coverage for hexagonal core and adapters.
8 CI/CD y despliegue
CI. GitHub Actions (or similar): lint, tests and build on each PR. Branch protection requiring green checks before merge.
CD. Deployment with Dokku: git push to server, Node buildpack, Procfile, PostgreSQL and Redis linked (add-ons or external services). Variables and secrets in Dokku; optional pipeline with GitHub Actions to deploy to the Dokku server.
9 Documentation and handover
Documentation. README with local setup, required variables and how to run tests. Documented API (Swagger/OpenAPI) accessible in staging environment.
Handover. Tidy repository, commit and PR conventions applied, and ability to work autonomously until project completion.

Summary

The project is a hybrid platform: social network and newspaper. Users upload nearby projects and can create news; verified journalists publish directly, and other users go through AI token verification and administrator approval. The mobile app is developed with React Native and the backend with hexagonal architecture (ports & adapters), REST API, PostgreSQL, Redis, S3 and AI provider integration.

Development is organised in the described phases, with efficiency, DB backups (every 12 h and on publish), tests, Git flow, CI/CD and cloud deployment. The data model includes roles (admin, editor, verified_journalist, user), nearby projects, news with flow states (pending_ai_review, pending_approval, published) and AI verification and approval fields.