Loco Framework

repository·master·Indexed 27 days ago

https://github.com/loco-rs/loco

A full-stack Rust web framework inspired by Ruby on Rails, designed for rapid development using 'Convention Over Configuration'. Loco provides a 'batteries included' experience featuring ORM integration, background jobs, mailers, storage abstractions, and a dedicated CLI for scaffolding projects. It supports various application types, including SaaS applications with user authentication, REST APIs, and lightweight services.

Tokens
58.8K
Snippets
220
Records
335
Agent score
92%

What's inside loco-rs

  1. Overview of Loco Starter Templates

    master

    Loco provides several predefined boilerplates:

    • SaaS Starter: An all-inclusive setup for projects requiring both a UI and a REST API. Includes a React/Vite frontend (or server-side templates), authentication middleware, Users table, forgot password flow, and a Mailer. It includes health check endpoints (_ping, _health, _readiness).
    • Rest API Starter: Designed for projects that only need a REST API without a frontend. You can add a frontend later by enabling the static middleware and pointing it to your frontend distribution folder.
    • Lightweight Service Starter: A minimalistic choice focused on controllers and views. Ideal for REST API services that do not require a database, frontend, or background workers.
  2. Overview of Loco features

    master

    Loco is a Rust framework inspired by Ruby on Rails, designed to reduce boilerplate and increase productivity through 'Convention over Configuration'. Key features include:

    • ORM Integration: Uses entities to represent business models, handling relations, validations, and custom logic without writing raw SQL.
    • Controllers: Built on Axum for high performance, handling web request parameters, body validation, and responses.
    • Views: Integrates with template engines to generate dynamic HTML.
    • Background Jobs: Uses Redis or threads to run intensive tasks; implement the Worker trait's perform function to create workers.
    • Scheduler: Simplifies task and shell script scheduling.
    • Mailers: Handles email delivery via the background worker infrastructure.
    • Storage: Simplifies file operations across local disk or cloud services like AWS S3, GCP, or Azure.
    • Caching: Provides a layer to improve performance by storing frequently accessed data.
  3. Overview of Loco Framework Features

    master

    Loco is a Rails-inspired web framework for Rust designed as a 'one person framework'. It provides a batteries-included experience with the following integrated components:

    • Routing & Controllers: Powered by axum.
    • Database & Models: Uses SeaORM for models, migrations, and ActiveRecord-style patterns.
    • Views: Uses serde for serialization.
    • Background Jobs: Supports in-process, out-of-process, and async execution via Tokio.
    • Authentication: Includes built-in authentication (similar to Rails' devise).
    • Core Utilities: Includes Mailers, Tasks, Seeding, and Environment-aware configuration.
    • Observability: Seamlessly integrated via tracing.
    • Code Generation: Uses rrgen for generators.
    • Testing: A comprehensive kit featuring automatic truncation, fixture seeding, auto migration, snapshotting, and redaction.
  4. Overview of Loco Application Types

    master

    Loco provides templates for different architectural needs:

    • SaaS Applications: Includes user authentication, database integration, and scalable background processing.
    • REST APIs: Focused on robust API development with database support, authentication, and modular controllers.
    • Lightweight Services: Minimal setups containing only essential controllers and views for simple tasks.
  5. Overview of Loco features

    master

    Loco is a Rust-based web framework inspired by Rails, designed for rapid web application development. Key features include:

    • Simple API: Leverages Rust's strong type system for safety and reliability.
    • Rapid Development: Provides tools and templates to build web applications quickly.
    • CLI Support: Enables the creation and execution of custom CLI tasks.
    • Flexibility: Supports custom configurations and extensions.
  6. Supported Cache Drivers in Loco

    master

    Loco provides three built-in cache drivers to improve application performance:

    1. Null Cache: A no-op driver that stores nothing. It is the default. get() always returns None, and write operations like insert() or remove() return errors.
    2. In-Memory Cache: A local cache using the moka crate. Requires the cache_inmem feature.
    3. Redis Cache: A distributed cache using Redis. Requires the cache_redis feature.
  7. Reset password flow

    master

    The password reset process involves two steps:

    1. Forgot Password: Call /api/auth/forgot with the user's email. This sends a reset link and stores a reset_token in the database.
    2. Reset Password: Call /api/auth/reset with the token and the new password.
    # 1. Request reset
    curl --location '127.0.0.1:5150/api/auth/forgot' \
         --header 'Content-Type: application/json' \
         --data-raw '{"email": "user@loco.rs"}'
    
    # 2. Submit new password
    curl --location '127.0.0.1:5150/api/auth/reset' \
         --header 'Content-Type: application/json' \
         --data '{ "token": "TOKEN", "password": "new-password" }'
  8. Configure Loco environments and configuration files

    master

    Loco uses YAML files located in the config/ directory to manage environment-specific settings. By default, it provides:

    • config/development.yaml
    • config/production.yaml
    • config/test.yaml

    Selecting an environment

    Loco determines the active environment using the following priority:

    1. The --environment flag: cargo loco start --environment production
    2. Environment variables: LOCO_ENV, RAILS_ENV, or NODE_ENV
    3. Default: development

    Custom environments

    To add a custom environment (e.g., qa), create a corresponding file config/qa.yaml and run the app using:

    LOCO_ENV=qa cargo loco start
  9. Fetch Related Models (Lazy Loading)

    master

    To fetch associated records (e.g., fetching all comments for a specific article), use the find_related method on a model instance. This is known as "lazy loading."

    Pattern:

    1. Load the parent item using its ID.
    2. Call .find_related(RelatedEntity::Entity).all(&ctx.db).await? on the parent item.
    // Inside a controller handler
    pub async fn comments(
        Path(id): Path<i32>,
        State(ctx): State<AppContext>,
    ) -> Result<Response> {
        let item = load_item(&ctx, id).await?;
        let comments = item.find_related(comments::Entity).all(&ctx.db).await?;
        format::json(comments)
    }
  10. Send emails using Mailers

    master

    Loco uses background workers to deliver emails seamlessly. To send an email, call the mailer's static method (e.g., send_welcome) from your controller, passing the AppContext. This enqueues a delivery job that is processed in the background.

    use crate::mailers::auth::AuthMailer;
    
    // in your controllers/auth.rs
    async fn register(
        State(ctx): State<AppContext>,
        Json(params): Json<RegisterParams>,
    ) -> Result<Response> {
        // .. register a user ..
        AuthMailer::send_welcome(&ctx, &user.email).await.unwrap();
    }