Initial commit: NutriApp - Rust + Axum + Dioxus - CI/CD con Gitea Runner
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
// Middleware de autenticación
|
||||
// Extraerá CurrentUser de la sesión y lo inyectará en los handlers
|
||||
@@ -0,0 +1,4 @@
|
||||
// Auth module — login, registro, middleware de sesión
|
||||
// Se implementará con tower-sessions + bcrypt
|
||||
|
||||
pub mod middleware;
|
||||
@@ -0,0 +1,4 @@
|
||||
// Jobs programados con tokio-cron-scheduler
|
||||
// - Generar lista de compras cada domingo
|
||||
// - Limpiar sesiones expiradas
|
||||
// - Recordatorios de menú diario
|
||||
@@ -0,0 +1,128 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::get,
|
||||
response::Json,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use tower_http::{
|
||||
cors::CorsLayer,
|
||||
services::{ServeDir, ServeFile},
|
||||
trace::TraceLayer,
|
||||
compression::CompressionLayer,
|
||||
limit::RequestBodyLimitLayer,
|
||||
};
|
||||
use tower_sessions::{
|
||||
SessionManagerLayer,
|
||||
cookie::Key,
|
||||
};
|
||||
use tower_sessions_sqlx_store::PostgresStore;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
mod routes;
|
||||
mod models;
|
||||
mod auth;
|
||||
mod ws;
|
||||
mod jobs;
|
||||
|
||||
// ─── App State ────────────────────────────────────────────────
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub db: sqlx::PgPool,
|
||||
}
|
||||
|
||||
// ─── Health Endpoint ──────────────────────────────────────────
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HealthResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
db: &'static str,
|
||||
}
|
||||
|
||||
async fn health() -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
db: "connected",
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Entrypoint ───────────────────────────────────────────────
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// --- Logging ---
|
||||
tracing_subscriber::registry()
|
||||
.with(tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "nutriapp_backend=debug,tower_http=debug".into()))
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
.init();
|
||||
|
||||
// --- Config desde .env ---
|
||||
dotenvy::dotenv().ok();
|
||||
|
||||
let database_url = std::env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| {
|
||||
"postgres://joel:factory_admin_2026@192.168.1.87:5432/nutriapp".to_string()
|
||||
});
|
||||
|
||||
let host = std::env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
|
||||
let port: u16 = std::env::var("PORT")
|
||||
.unwrap_or_else(|_| "3100".to_string())
|
||||
.parse()
|
||||
.unwrap_or(3100);
|
||||
|
||||
// --- Pool PostgreSQL ---
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(10)
|
||||
.connect(&database_url)
|
||||
.await?;
|
||||
|
||||
tracing::info!("✅ PostgreSQL conectado");
|
||||
|
||||
// --- Migraciones automáticas ---
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&pool)
|
||||
.await?;
|
||||
|
||||
tracing::info!("✅ Migraciones aplicadas");
|
||||
|
||||
// --- Session store ---
|
||||
let session_store = PostgresStore::new(pool.clone());
|
||||
session_store.migrate().await?;
|
||||
|
||||
let session_layer = SessionManagerLayer::new(session_store)
|
||||
.with_secure(false); // false en dev (sin HTTPS), true en prod
|
||||
|
||||
// --- App state ---
|
||||
let state = AppState { db: pool };
|
||||
|
||||
// --- Router ---
|
||||
let app = Router::new()
|
||||
// API
|
||||
.route("/api/health", get(health))
|
||||
.nest("/api", routes::api_routes())
|
||||
// WebSocket
|
||||
.nest("/ws", ws::ws_routes())
|
||||
// Frontend estático (producción)
|
||||
.nest_service("/", ServeDir::new("../frontend/dist")
|
||||
.fallback(ServeFile::new("../frontend/dist/index.html")))
|
||||
// Middleware (orden importa: último = más externo)
|
||||
.layer(CompressionLayer::new())
|
||||
.layer(RequestBodyLimitLayer::new(10 * 1024 * 1024)) // 10MB
|
||||
.layer(CorsLayer::permissive())
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(session_layer)
|
||||
.with_state(state);
|
||||
|
||||
// --- Arranque ---
|
||||
let addr = format!("{host}:{port}");
|
||||
tracing::info!("🚀 NutriApp corriendo en http://{addr}");
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Familia {
|
||||
pub id: Uuid,
|
||||
pub nombre: String,
|
||||
pub codigo_invitacion: String,
|
||||
pub creador_id: Uuid,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Ingrediente {
|
||||
pub id: Uuid,
|
||||
pub nombre: String,
|
||||
pub categoria: Option<String>, // "verdura", "proteina", "lacteo", etc.
|
||||
pub unidad_medida: String, // "g", "ml", "unidad", "cucharada"
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod receta;
|
||||
pub mod ingrediente;
|
||||
pub mod usuario;
|
||||
pub mod familia;
|
||||
@@ -0,0 +1,18 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Receta {
|
||||
pub id: Uuid,
|
||||
pub familia_id: Uuid,
|
||||
pub creador_id: Uuid,
|
||||
pub nombre: String,
|
||||
pub descripcion: Option<String>,
|
||||
pub porciones: i32,
|
||||
pub tiempo_preparacion_min: Option<i32>,
|
||||
pub instrucciones: Option<String>,
|
||||
pub imagen_url: Option<String>,
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: NaiveDateTime,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Usuario {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub nombre: String,
|
||||
pub password_hash: String,
|
||||
pub familia_id: Option<Uuid>,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
pub fn api_routes() -> Router<crate::AppState> {
|
||||
Router::new()
|
||||
.route("/v1/recetas", get(list_recetas))
|
||||
// TODO: .route("/v1/recetas", post(create_receta))
|
||||
// TODO: .route("/v1/recetas/:id", get(get_receta))
|
||||
}
|
||||
|
||||
async fn list_recetas() -> axum::response::Json<serde_json::Value> {
|
||||
axum::response::Json(serde_json::json!({
|
||||
"recetas": [],
|
||||
"total": 0
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
pub fn ws_routes() -> Router<crate::AppState> {
|
||||
Router::new()
|
||||
.route("/familia/:familia_id", get(ws_familia_handler))
|
||||
}
|
||||
|
||||
// WebSocket colaborativo para edición en tiempo real del menú
|
||||
async fn ws_familia_handler(
|
||||
// ws: axum::extract::ws::WebSocketUpgrade,
|
||||
// Path(familia_id): axum::extract::Path<uuid::Uuid>,
|
||||
// State(state): axum::extract::State<crate::AppState>,
|
||||
) -> &'static str {
|
||||
"WebSocket endpoint — TODO: implementar broadcast por familia"
|
||||
}
|
||||
Reference in New Issue
Block a user