### Installation and Project Setup Source: https://context7.com/loco-rs/loco/llms.txt Instructions for installing the Loco CLI and setting up a new Loco application, including starting the development server and testing the basic ping endpoint. ```APIDOC ## Installation and Project Setup Install the Loco CLI and create a new application. ```sh # Install Loco CLI and SeaORM CLI `cargo install loco` `cargo install sea-orm-cli` # Create a new Loco application `loco new` # Follow the prompts to select app type, database, and worker configuration # Start the development server `cd myapp` `cargo loco start` # Test the server `curl localhost:5150/_ping` # Expected output: `{"ok":true}` ``` ``` -------------------------------- ### Install Frontend Dependencies and Start Dev Server Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Navigate to the frontend directory, install project dependencies using `pnpm install`, and then start the Vite development server with `pnpm dev`. ```sh cd todolist/frontend $ pnpm install $ pnpm dev ``` -------------------------------- ### Install and Build Frontend Dependencies Source: https://github.com/loco-rs/loco/blob/master/DEVELOPMENT.md Navigate to the frontend directory, install pnpm globally if not already present, then install and build the frontend assets. ```bash $ cd starters/saas/frontend $ npm i -g pnpm $ pnpm i && pnpm build ``` -------------------------------- ### Run Loco Application on Server Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/infrastructure/deployment.md After copying the compiled binary and configuration files to your server, execute your application using its binary name followed by `start`. For example, if your application is named 'myapp', run `./target/release/myapp start`. ```sh ./target/release/myapp start ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/loco-rs/loco/blob/master/loco-new/base_template/frontend/README.md Use pnpm to install all required project packages. ```sh pnpm install ``` -------------------------------- ### Run Development Server Source: https://github.com/loco-rs/loco/blob/master/loco-new/base_template/frontend/README.md Starts the frontend development server. ```sh pnpm dev ``` -------------------------------- ### Define Starter Options Source: https://github.com/loco-rs/loco/blob/master/loco-cli/README.md Example of declaring available options for a starter template. ```yaml --- description: SaaS app (with DB and user auth) options: - db - bg - assets rules: # ... ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Install the necessary React libraries for routing, data fetching, and HTTP requests. ```sh $ pnpm install react-router-dom react-query axios ``` -------------------------------- ### Start the Loco Server Source: https://github.com/loco-rs/loco/blob/master/README.md Launch the development server to begin running the application. ```sh $ cargo loco start ▄ ▀ ▀ ▄ ▄ ▀ ▄ ▄ ▄▀ ▄ ▀▄▄ ▄ ▀ ▀ ▀▄▀█▄ ▀█▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▀▀█ ██████ █████ ███ █████ ███ █████ ███ ▀█ ██████ █████ ███ █████ ▀▀▀ █████ ███ ▄█▄ ██████ █████ ███ █████ █████ ███ ████▄ ██████ █████ ███ █████ ▄▄▄ █████ ███ █████ ██████ █████ ███ ████ ███ █████ ███ ████▀ ▀▀▀██▄ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ██▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ https://loco.rs listening on port 5150 ``` -------------------------------- ### Create New Loco Project Source: https://github.com/loco-rs/loco/blob/master/loco-new/README.md Initiates a guided wizard to create a new Loco project. This command should be run after the CLI is installed. ```sh loco new ``` -------------------------------- ### Install Insta CLI Tool Source: https://github.com/loco-rs/loco/blob/master/CONTRIBUTING.md Installs the 'insta' command-line interface tool, which is used for snapshot testing in the project. ```sh cargo install cargo-insta ``` -------------------------------- ### Install Loco CLI Source: https://github.com/loco-rs/loco/blob/master/README.md Install the Loco CLI and the SeaORM CLI for database management. ```sh cargo install loco cargo install sea-orm-cli # Only when DB is needed ``` -------------------------------- ### Start the Loco development server Source: https://github.com/loco-rs/loco/blob/master/loco-new/base_template/README.md Use the CLI to initialize and run the Loco development server. ```sh cargo loco start ``` ```sh $ cargo loco start Finished dev [unoptimized + debuginfo] target(s) in 21.63s Running `target/debug/myapp start` : : : controller/app_routes.rs:203: [Middleware] Adding log trace id ▄ ▀ ▀ ▄ ▄ ▀ ▄ ▄ ▄▀ ▄ ▀▄▄ ▄ ▀ ▀ ▀▄▀█▄ ▀█▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▀▀█ ██████ █████ ███ █████ ███ █████ ███ ▀█ ██████ █████ ███ █████ ▀▀▀ █████ ███ ▄█▄ ██████ █████ ███ █████ █████ ███ ████▄ ██████ █████ ███ █████ ▄▄▄ █████ ███ █████ ██████ █████ ███ ████ ███ █████ ███ ████▀ ▀▀▀██▄ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ██▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ https://loco.rs environment: development database: automigrate logger: debug compilation: debug modes: server listening on http://localhost:5150 ``` -------------------------------- ### Install Loco CLI and SeaORM CLI Source: https://context7.com/loco-rs/loco/llms.txt Install the Loco CLI for framework operations and the SeaORM CLI for database migrations and management. ```sh cargo install loco cargo install sea-orm-cli ``` -------------------------------- ### Configure Secure Headers from Scratch Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/controller.md Starts the secure_headers middleware configuration from an 'empty' preset and applies custom overrides. Useful for a completely custom security header setup. ```yaml server: middleware: secure_headers: preset: empty overrides: foo: bar ``` -------------------------------- ### Create and Start a New Loco Application Source: https://context7.com/loco-rs/loco/llms.txt Create a new Loco application by running 'loco new' and following the prompts. Then, navigate to the application directory and start the development server with 'cargo loco start'. ```sh loco new # Follow the prompts to select app type, database, and worker configuration cd myapp cargo loco start ``` -------------------------------- ### Start Loco Server Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/tour/index.md Starts the Loco development server on the default port. ```sh $ cargo loco start ``` -------------------------------- ### Install Loco CLI Source: https://github.com/loco-rs/loco/blob/master/loco-cli/README.md Install the CLI tool using Cargo. ```sh cargo install loco-cli ``` -------------------------------- ### Start Loco Development Server Source: https://github.com/loco-rs/loco/blob/master/docs-site/templates/index.html This command starts the Loco development server. It displays environment details, database status, logger configuration, and compilation mode, then indicates the listening address. ```bash $ cargo loco start ▄ ▀ ▀ ▄ ▄ ▀ ▄ ▄ ▄▀ ▄ ▀▄▄ ▄ ▀ ▀ ▀▄▀█▄ ▀█▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▀▀█ ██████ █████ ███ █████ ███ █████ ███ ▀█ ██████ █████ ███ █████ ▀▀▀ █████ ███ ▄█▄ ██████ █████ ███ █████ █████ ███ ████▄ ██████ █████ ███ █████ ▄▄▄ █████ ███ █████ ██████ █████ ███ ████ ███ █████ ███ ████▀ ▀▀▀██▄ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ██▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ https://loco.rs environment: development database: automigrate logger: disabled compilation: debug modes: server listening on localhost:5150 ``` -------------------------------- ### Start Loco Development Server Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Initiate the Loco development server using `cargo loco start`. This command compiles and runs your backend application, making it ready to handle API requests. ```sh $ cargo loco start Updating crates.io index . . . ▄ ▀ ▀ ▄ ▄ ▀ ▄ ▄ ▄▀ ▄ ▀▄▄ ▄ ▀ ▀ ▀▄▀█▄ ▀█▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄ ▀▀█ ██████ █████ ███ █████ ███ █████ ███ ▀█ ██████ █████ ███ █████ ▀▀▀ █████ ███ ▄█▄ ██████ █████ ███ █████ █████ ███ ████▄ ██████ █████ ███ █████ ▄▄▄ █████ ███ █████ ██████ █████ ███ ████ ███ █████ ███ ████▀ ▀▀▀██▄ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ██▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ https://loco.rs environment: development database: automigrate logger: debug modes: server listening on port 5150 ``` -------------------------------- ### Build and Run Docker Container Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Commands to build the container image and start the production server. ```sh $ docker build . -t loco-todo-list ``` ```sh $ docker run -e LOCO_ENV=production -p 5150:5150 loco-todo-list start ``` -------------------------------- ### Initialize a new Loco project Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/deploy-aws.md Install the Loco CLI and create a new project using the interactive generator. ```sh $ cargo install loco $ loco new ✔ ❯ App name? · myapp ? ❯ What would you like to build? › lightweight-service (minimal, only controllers and views) ❯ Rest API (with DB and user auth) SaaS app (with DB and user auth) ``` -------------------------------- ### Start Loco Application Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/your-project.md Run `cargo loco start` to launch your Loco application. Ensure you are in the application's root directory. ```sh cargo loco start ``` -------------------------------- ### Install Loco CLI Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/axum-session.md Install the Loco command-line interface to manage your Loco projects. ```sh cargo install loco ``` -------------------------------- ### Terraform Apply Output Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/deploy-aws.md Example output showing successful resource creation and the application load balancer URL. ```text Apply complete! Resources: 20 added, 0 changed, 0 destroyed. Outputs: alb_url = https://myapp-lb-1234567890.us-east-2.elb.amazonaws.com ``` -------------------------------- ### View directory structure Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/views.md Example project directory layout showing the location of assets and template views. ```text assets/ ├── i18n │   ├── de-DE │   │   └── main.ftl │   ├── en-US │   │   └── main.ftl │   └── shared.ftl ├── static │   ├── 404.html │   └── image.png └── views └── home └── hello.html config/ : src/ ├── controllers/ ├── models/ : └── views/ ``` -------------------------------- ### Start worker processes Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/workers.md Commands to start standalone workers or combined server/worker processes. ```bash $ cargo loco start --worker # starts a standalone worker job executing process $ cargo loco start # starts a standalone API service or Web server, no workers ``` ```bash $ cargo loco start --server-and-worker # both API service and workers will execute ``` -------------------------------- ### View worker CLI usage Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/workers.md Display the command line interface options for starting workers. ```text Usage: demo_app start [OPTIONS] Options: -w, --worker [...] Start worker. Optionally provide tags to run specific jobs (e.g. --worker=tag1,tag2) -s, --server-and-worker start same-process server and worker ``` -------------------------------- ### Login Response Format Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/authentication.md Example JSON response received after a successful login. ```json { "token": "...", "pid": "2b20f998-b11e-4aeb-96d7-beca7671abda", "name": "Loco user", "is_verified": false } ``` -------------------------------- ### Install Nightly Rustfmt Source: https://github.com/loco-rs/loco/blob/master/CONTRIBUTING.md Installs the nightly version of rustfmt required for specific code style configurations. ```sh rustup component add rustfmt --toolchain nightly ``` -------------------------------- ### Create New Loco App with SaaS Starter Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Use the `loco new` command to generate a new Loco application with the SaaS starter, which includes database and user authentication setup. Follow the prompts to name your app. ```sh & loco new ✔ ❯ App name? · todolist ✔ ❯ What would you like to build? · SaaS app (with DB and user auth) 🚂 Loco app generated successfully in: /tmp/todolist ``` -------------------------------- ### Example `cargo loco routes` Output Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/views.md Demonstrates the output of the `cargo loco routes` command, showing the newly added '/home' route. ```bash $ cargo loco routes [GET] /_health [GET] /_ping [POST] /api/auth/forgot [POST] /api/auth/login [POST] /api/auth/register [POST] /api/auth/reset [POST] /api/auth/verify [GET] /api/auth/current [GET] /home <-- the corresponding URL for our new view ``` -------------------------------- ### Run Scheduler Integrated with Application Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/scheduler.md Commands to start the scheduler alongside the main application, optionally specifying a custom configuration file. ```sh cargo loco start --all ``` ```sh SCHEDULER_CONFIG=config/scheduler.yaml cargo loco start --all ``` -------------------------------- ### Database Connection Setup in Axum Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/axum-users.md Manually establish a database connection pool using `PgPoolOptions` in an Axum application's main function. Requires explicit wiring to application context. ```rust let db = PgPoolOptions::new() .max_connections(50) .connect(&config.database_url) .await .context("could not connect to database_url")?; ``` ```rust .layer(AddExtensionLayer::new(ApiContext { config: Arc::new(config), db, })) ``` -------------------------------- ### Example .env file for Axum Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/axum-users.md A sample environment file used with `dotenv` in Axum applications. Contains database credentials and logging levels. ```env DATABASE_URL=postgresql://postgres:{password}@localhost/realworld_axum_sqlx HMAC_KEY={random-string} RUST_LOG=realworld_axum_sqlx=debug,tower_http=debug ``` -------------------------------- ### Fetch All Articles using Playground Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/guide.md Example of how to fetch all records from the 'articles' table using the playground script. Ensure correct imports for your application's models. ```rust // located in examples/playground.rs // use this file to experiment with stuff use loco_rs::{cli::playground, prelude::*}; // to refer to articles::ActiveModel, your imports should look like this: use myapp::{app::App, models::_entities::articles}; #[tokio::main] async fn main() -> loco_rs::Result<()> { let ctx = playground::().await?; // add this: let res = articles::Entity::find().all(&ctx.db).await.unwrap(); println!("{:?}", res); Ok(()) } ``` -------------------------------- ### Configure Axum Logging Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/axum-users.md Standard logging setup patterns used in Axum applications. ```rust // Enables logging. Use `RUST_LOG=tower_http=debug` .layer(TraceLayer::new_for_http()), ``` ```rust // Initialize the logger. env_logger::init(); ``` ```rust log::error!("SQLx error: {:?}", e); ``` -------------------------------- ### Organize Application Routes with Prefixes and Nesting Source: https://context7.com/loco-rs/loco/llms.txt Configure and organize routes in the main application hooks using `AppRoutes`. This example demonstrates prefixing, adding nested routes, and applying middleware. ```rust // src/app.rs use loco_rs::prelude::*; pub struct App; #[async_trait] impl Hooks for App { fn routes(_ctx: &AppContext) -> AppRoutes { AppRoutes::with_default_routes() .prefix("api") .add_route(controllers::auth::routes()) .add_route(controllers::articles::routes()) // Nest routes under a version prefix .nest_prefix("v1") .nest_route("/notes", controllers::notes::routes()) } } // Example route with middleware layer pub fn routes() -> Routes { Routes::new() .prefix("auth") .add("/register", post(register).layer(middlewares::log::LogLayer::new())) } ``` -------------------------------- ### Check Server Status with _ping Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/guide.md After starting the server, you can verify it's running by sending a request to the `_ping` endpoint. This endpoint is useful for load balancers. ```sh curl localhost:5150/_ping ``` -------------------------------- ### Implement Session Controller Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/axum-session.md Create a controller function that accesses and prints the session data. This example uses `SessionNullPool` and returns an empty response. ```rust #![allow(clippy::unused_async)] use axum_session::{Session, SessionNullPool}; use loco_rs::prelude::*; pub async fn get_session(session: Session) -> Result<()> { println!("{:#?}", session); format::empty() } pub fn routes() -> Routes { Routes::new().prefix("mysession").add("/", get(get_session)) } ``` -------------------------------- ### Implement Axum Session Initializer in Rust Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/pluggability.md Example of an initializer that integrates `axum-session` by adding a session layer to the Axum router. This demonstrates how to use the `after_routes` hook. ```rust // place this in `src/initializers/axum_session.rs` #[async_trait] impl Initializer for AxumSessionInitializer { fn name(&self) -> String { "axum-session".to_string() } async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result { let session_config = axum_session::SessionConfig::default().with_table_name("sessions_table"); let session_store = axum_session::SessionStore::::new(None, session_config) .await .unwrap(); let router = router.layer(axum_session::SessionLayer::new(session_store)); Ok(router) } } ``` -------------------------------- ### Test API Endpoints with Curl Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/guide.md Examples for creating a new article and listing existing articles via HTTP requests. ```sh $ curl -X POST -H "Content-Type: application/json" -d '{ "title": "Your Title", "content": "Your Content xxx" }' localhost:5150/api/articles {"created_at":"...","updated_at":"...","id":2,"title":"Your Title","content":"Your Content xxx"} ``` ```sh $ curl localhost:5150/api/articles [{"created_at":"...","updated_at":"...","id":1,"title":"how to build apps in 3 steps","content":"use Loco: https://loco.rs"},{"created_at":"...","updated_at":"...","id":2,"title":"Your Title","content":"Your Content xxx"} ``` -------------------------------- ### GET /api/user/current-api Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/authentication.md An example of an authenticated endpoint that requires an API key provided in the Authorization header. ```APIDOC ## GET /api/user/current-api ### Description Retrieves current user details using API key authentication. ### Method GET ### Endpoint /api/user/current-api ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer API_KEY ### Request Example curl --location '127.0.0.1:5150/api/user/current-api' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer API_KEY' ``` -------------------------------- ### Register User API Call Source: https://context7.com/loco-rs/loco/llms.txt Example `curl` command to register a new user. Requires `name`, `email`, and `password` in the JSON payload. ```bash curl -X POST http://localhost:5150/api/auth/register \ -H "Content-Type: application/json" \ -d '{"name": "User", "email": "user@example.com", "password": "password123"}' ``` -------------------------------- ### Request Articles from API Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/guide.md Example of making an HTTP GET request to the /api/articles endpoint using curl to retrieve the list of articles. The response is in JSON format. ```sh $ curl localhost:5150/api/articles [{"created_at":"...","updated_at":"...","id":1,"title":"how to build apps in 3 steps","content":"use Loco: https://loco.rs"}] ``` -------------------------------- ### Create Starter with Specific Options Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/starters.md Generate a new Loco app with a SQLite database, async background worker, and server-side assets. ```sh loco new --db sqlite --bg async --assets serverside ``` -------------------------------- ### Loco CLI Command Reference Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/your-project.md This output details the available commands for a Loco application's CLI, including options for starting the app, managing the database, describing routes and middleware, running tasks, and more. ```sh The one-person framework for Rust Usage: demo_app-cli [OPTIONS] Commands: start Start an app db Perform DB operations routes Describe all application endpoints middleware Describe all application middlewares task Run a custom task jobs Managing jobs queue scheduler Run the scheduler generate code generation creates a set of files and code templates based on a predefined set of rules doctor Validate and diagnose configurations version Display the app version watch Watch and restart the app help Print this message or the help of the given subcommand(s) Options: -e, --environment Specify the environment [default: development] -h, --help Print help -V, --version Print version ``` -------------------------------- ### Fetch Comments for an Article via API Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/guide.md Example using `curl` to send a GET request to the nested route `/api/articles/1/comments` to retrieve all comments associated with article ID 1. ```sh $ curl localhost:5150/api/articles/1/comments [{"created_at":"...","updated_at":"...","id":4,"content":"this rocks","article_id":1}] ``` -------------------------------- ### Generate a Controller Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/controller.md Use this command to generate a starter controller and its associated test file. ```sh cargo loco generate controller [OPTIONS] ``` -------------------------------- ### Verify Loco Project Setup Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Run `cargo loco doctor` to ensure all necessary dependencies and connections (SeaORM CLI, database, Redis) are correctly configured. This command checks for potential issues before starting the development server. ```sh cd todolist $ cargo loco doctor ✅ SeaORM CLI is installed ✅ DB connection: success ✅ Redis connection: success ``` -------------------------------- ### Create a New Loco Application Source: https://github.com/loco-rs/loco/blob/master/README.md Initialize a new project using the interactive CLI wizard. ```sh ❯ loco new ✔ ❯ App name? · myapp ✔ ❯ What would you like to build? · Saas App with client side rendering ✔ ❯ Select a DB Provider · Sqlite ✔ ❯ Select your background worker type · Async (in-process tokio async tasks) 🚂 Loco app generated successfully in: myapp/ - assets: You've selected `clientside` for your asset serving configuration. Next step, build your frontend: $ cd frontend/ $ npm install && npm run build ``` -------------------------------- ### Generate a New Website Source: https://github.com/loco-rs/loco/blob/master/loco-cli/README.md Commands to initialize a new project in the current or a specified directory. ```sh loco new ``` ```sh loco new --path /my-work/websites/ ``` -------------------------------- ### Configure Database Connection and Migrations Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/infrastructure/deployment.md Set up your database connection using a URI, and configure connection pooling and migration settings. `auto_migrate` will run migrations on load. Use `dangerously_truncate` or `dangerously_recreate` with extreme caution, primarily in development. ```yaml database: # Database connection URI uri: {{get_env(name="DATABASE_URL", default="postgres://loco:loco@localhost:5432/loco_app")}} # When enabled, the sql query will be logged. enable_logging: false # Set the timeout duration when acquiring a connection. connect_timeout: 500 # Set the idle duration before closing a connection. idle_timeout: 500 # Minimum number of connections for a pool. min_connections: 1 # Maximum number of connections for a pool. max_connections: 1 # Run migration up when application loaded auto_migrate: true # Truncate database when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode dangerously_truncate: false # Recreating schema when application loaded. This is a dangerous operation, make sure that you using this flag only on dev environments or test mode dangerously_recreate: false ``` -------------------------------- ### Build Application Source: https://github.com/loco-rs/loco/blob/master/loco-new/base_template/frontend/README.md Compiles the application into the dist folder for production deployment. ```sh pnpm build ``` -------------------------------- ### Get Current User with Bearer Token Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/tour/index.md Use this cURL command to make an authenticated GET request to the /api/auth/current endpoint. Replace TOKEN with your actual JWT token. This is typically the first authenticated request you'll make. ```sh $ curl --location --request GET 'localhost:5150/api/auth/current' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer TOKEN' ``` -------------------------------- ### Generate Deployment Help Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/infrastructure/deployment.md View help information for the 'generate deployment' command, including available deployment kinds. ```sh $ cargo loco generate deployment --help Generate a deployment infrastructure Usage: myapp-cli generate deployment [OPTIONS] Arguments: [possible values: docker, nginx] ``` -------------------------------- ### Get Current User Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/authentication.md Retrieves the currently authenticated user's information. ```sh curl --location --request GET '127.0.0.1:5150/api/auth/current' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer TOKEN' ``` -------------------------------- ### Create Vite React Frontend Project Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/frontend-website.md Set up a new frontend project using Vite with React. This command initiates the project creation process, prompting for the project name and framework selection. ```sh $ npm create vite@latest Need to install the following packages: create-vite@5.1.0 Ok to proceed? (y) y ✔ Project name: … frontend ✔ Select a framework: › React ✔ Select a variant: › JavaScript ``` -------------------------------- ### Define Generator Rules Source: https://github.com/loco-rs/loco/blob/master/loco-cli/README.md Example of regex-based replacement rules defined in generator.yaml. ```yaml ... rules: - pattern: loco_starter_template kind: LibName file_patterns: - rs - toml - trycmd - pattern: PqRwLF2rhHe8J22oBeHy kind: JwtToken file_patterns: - config/test.yaml - config/development.yaml ``` -------------------------------- ### Run Loco CLI Locally Source: https://github.com/loco-rs/loco/blob/master/loco-cli/README.md Use the STARTERS_LOCAL_PATH environment variable to point to a local repository instead of fetching from GitHub. ```sh cd loco-cli $ STARTERS_LOCAL_PATH=[FULL_PATH]/loco-rs/loco cargo run new --path /tmp ``` -------------------------------- ### Filter workers by tags Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/workers.md Start workers configured to process only specific job tags. ```bash # Start a worker that only processes jobs with no tags $ cargo loco start --worker # Start a worker that only processes jobs with the "email" tag $ cargo loco start --worker email # Start a worker that processes jobs with either "report" or "analytics" tags $ cargo loco start --worker report,analytics ``` -------------------------------- ### Middleware Execution Log Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/pluggability.md Example output generated when a request passes through the logging middleware. ```shell 2024-XX-XXTXX:XX:XX.XXXXXZ INFO http-request: xx::controllers::middleware::log Request: POST "/auth/register" http.method=POST http.uri=/auth/register http.version=HTTP/1.1 environment=development request_id=xxxxx ``` -------------------------------- ### Configure AWS Provider and Core Resources Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/deploy-aws.md Sets up the AWS provider and initializes the ECR repository, ECS cluster, and CloudWatch log group. ```hcl provider "aws" { region = "us-east-1" // Change this to your region access_key = "" // Change this to your access key secret_key = "your secret key" // Change this to your secret key } resource "aws_ecr_repository" "myapp" { name = "myapp" } resource "aws_ecs_cluster" "myapp_cluster" { name = "myapp_cluster" } resource "aws_cloudwatch_log_group" "myapp" { name = "/ecs/myapp" } ``` -------------------------------- ### Manage database migrations Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/models.md Commands for creating, applying, and generating entities from migration files. ```bash $ cargo loco generate migration [name:type, name:type ...] ``` ```bash $ cargo loco db migrate ``` ```bash $ cargo loco db entities ``` -------------------------------- ### GET /api/auth/current Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/getting-started/tour/index.md Retrieves the details of the currently authenticated user using a JWT bearer token. ```APIDOC ## GET /api/auth/current ### Description Retrieves the profile information for the user associated with the provided JWT bearer token. ### Method GET ### Endpoint localhost:5150/api/auth/current ### Parameters #### Headers - **Authorization** (string) - Required - Bearer ### Request Example curl --location --request GET 'localhost:5150/api/auth/current' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer TOKEN' ``` -------------------------------- ### Advanced Middleware Execution Log Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/pluggability.md Example output showing user information logged by the advanced middleware. ```shell 2024-XX-XXTXX:XX:XX.XXXXXZ INFO http-request: xx::controllers::middleware::log User: John Doe environment=development request_id=xxxxx ``` -------------------------------- ### Generate a Task via CLI Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/task.md Use the Loco CLI to generate a starter task file. ```sh Generate a Task based on the given name Usage: demo_app-cli generate task [OPTIONS] Arguments: Name of the thing to generate Options: -e, --environment Specify the environment [default: development] -h, --help Print help -V, --version Print version ``` -------------------------------- ### Example Health Check Output Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/pluggability.md The output format displayed when running health checks via the CLI. ```text ✅ Database connection: success ✅ Initializer my_custom_initializer: My custom service: success ❌ Initializer failing_service: Service connection: failed connection timeout after 30 seconds ``` -------------------------------- ### Configure Load Balancer and Listeners Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/deploy-aws.md Sets up the Application Load Balancer, target groups, and HTTP/HTTPS listeners. ```hcl resource "aws_alb" "myapp" { name = "myapp-lb" internal = false load_balancer_type = "application" enable_deletion_protection = true subnets = [ aws_subnet.public_d.id, aws_subnet.public_e.id, ] security_groups = [ aws_security_group.http.id, aws_security_group.https.id, aws_security_group.egress_all.id, ] depends_on = [aws_internet_gateway.igw] } resource "aws_security_group" "load_balancer_security_group" { ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_lb_target_group" "myapp" { name = "myapp-tg" port = 5150 protocol = "HTTP" target_type = "ip" vpc_id = aws_vpc.myapp_vpc.id health_check { enabled = true path = "/_health" matcher = "200,202" } depends_on = [aws_alb.myapp] } resource "aws_alb_listener" "myapp_http" { load_balancer_arn = aws_alb.myapp.arn port = "80" protocol = "HTTP" default_action { type = "redirect" redirect { port = "443" protocol = "HTTPS" status_code = "HTTP_301" } } } resource "aws_alb_listener" "myapp_https" { load_balancer_arn = aws_alb.myapp.arn port = "443" protocol = "HTTPS" ssl_policy = "ELBSecurityPolicy-2016-08" certificate_arn = "" // Change this to your certificate ARN default_action { type = "forward" target_group_arn = aws_lb_target_group.myapp.arn } } output "alb_url" { value = "https://${aws_alb.myapp.dns_name}" } ``` -------------------------------- ### Define Controller Routes in Rust Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/controller.md Use the Routes struct to register GET and POST endpoints within a controller. ```rust use axum::routing::{get, post}; Routes::new() .add("/", get(hello)) .add("/echo", post(echo)) ``` -------------------------------- ### Define Scheduler Jobs in YAML Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/scheduler.md Example configuration for scheduling shell commands and tasks within a YAML file. ```yaml scheduler: # Location of shipping the command stdout and stderr. output: stdout # A list of jobs to be scheduled. jobs: # The name of the job. write_content: # by default false meaning executing the the run value as a task. if true execute the run value as shell command shell: true # command to run run: "echo loco >> ./scheduler.txt" # The cron expression that defines the job's schedule. schedule: run every 1 second output: silent tags: ["base", "infra"] run_task: run: "foo" schedule: "at 10:00 am" run_on_start: true list_if_users: run: "user_report" shell: true schedule: "* 2 * * * *" tags: ["base", "users"] ``` -------------------------------- ### Rust Error Handling with ThisError Source: https://github.com/loco-rs/loco/blob/master/DEVELOPMENT.md Example of using `thiserror` for transparent error conversion, specifically for `serde_json::Error`. ```rust #[error(transparent)] JSON(#[from] serde_json::Error), ``` -------------------------------- ### Log in to ECR Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/blog/deploy-aws.md Authenticates your Docker client with ECR using AWS credentials. Ensure you have the AWS CLI installed and configured. ```sh $ aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com ``` -------------------------------- ### Configure Server Binding and Host Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/infrastructure/deployment.md Configure the server settings, including the port it listens on and the UI hostname. The server binds to `0.0.0.0:{PORT}`. Environment variables can be used for dynamic configuration. ```yaml server: # Port on which the server will listen. the server binding is 0.0.0.0:{PORT} port: {{ get_env(name="NODE_PORT", default=5150) }} # The UI hostname or IP address that mailers will point to. host: http://localhost ``` -------------------------------- ### Implement Model Test Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/models.md Use boot_test and seed to prepare the application context for model testing. ```rust use loco_rs::testing::prelude::*; #[tokio::test] #[serial] async fn can_find_by_pid() { configure_insta!(); let boot = boot_test::().await; seed::(&boot.app_context).await.unwrap(); let existing_user = Model::find_by_pid(&boot.app_context.db, "11111111-1111-1111-1111-111111111111").await; let non_existing_user_results = Model::find_by_email(&boot.app_context.db, "23232323-2323-2323-2323-232323232323").await; assert_debug_snapshot!(existing_user); assert_debug_snapshot!(non_existing_user_results); } ``` -------------------------------- ### Generate Docker Deployment Files Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/infrastructure/deployment.md Generates a Dockerfile and a .dockerignore file for Docker deployments. Ensure you have Docker installed and configured. ```sh cargo loco generate deployment docker added: "Dockerfile" added: ".dockerignore" * Dockerfile generated successfully. * Dockerignore generated successfully ``` -------------------------------- ### Test Loco Development Server Source: https://context7.com/loco-rs/loco/llms.txt After starting the development server, you can test its basic functionality by sending a request to the '_ping' endpoint. ```sh curl localhost:5150/_ping # {"ok":true} ``` -------------------------------- ### Create a database table Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/models.md Implement the MigrationTrait to define table creation and deletion logic. ```rust impl MigrationTrait for Migration { async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { create_table( m, "posts", &[ ("title", ColType::StringNull), ("content", ColType::StringNull), ], &[], ) .await } async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { drop_table(m, "posts").await } } ``` -------------------------------- ### Get Current User Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/extras/authentication.md Retrieves the details of the currently authenticated user. Requires a valid JWT token in the Authorization header. ```APIDOC ## GET /api/auth/current ### Description Retrieves the details of the currently authenticated user. Requires authentication. ### Method GET ### Endpoint /api/auth/current ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer TOKEN`). ### Response #### Success Response (200) - **pid** (string) - Unique user identifier. - **name** (string) - The user's name. - **email** (string) - The user's email address. - **is_verified** (boolean) - Indicates if the user's account is verified. #### Response Example ```json { "pid": "2b20f998-b11e-4aeb-96d7-beca7671abda", "name": "Loco user", "email": "user@loco.rs", "is_verified": false } ``` ``` -------------------------------- ### Configure queue backends Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/workers.md Define the queue backend and connection settings for Redis, Postgres, or SQLite. ```yaml queue: kind: Redis # Redis connection URI. uri: "{{ get_env(name="REDIS_URL", default="redis://127.0.0.1") }}" # Dangerously flush all data. dangerously_flush: false # represents the number of tasks a worker can handle simultaneously. num_workers: 2 ``` ```yaml queue: kind: Postgres # Postgres Queue connection URI. uri: "{{ get_env(name="PGQ_URL", default="postgres://localhost:5432/mydb") }}" # Dangerously flush all data. dangerously_flush: false # represents the number of tasks a worker can handle simultaneously. num_workers: 2 ``` ```yaml queue: kind: Sqlite # SQLite Queue connection URI. uri: "{{ get_env(name="SQLTQ_URL", default="sqlite://loco_development.sqlite? mode=rwc") }}" # Dangerously flush all data. dangerously_flush: false # represents the number of tasks a worker can handle simultaneously. num_workers: 2 ``` -------------------------------- ### Configure Fallback Behavior Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/controller.md Customize or disable the development-mode welcome screen and 404 error handling. ```yaml # the default pre-baked welcome screen fallback: enable: true ``` ```yaml # a different predefined 404 page fallback: enable: true file: assets/404.html ``` ```yaml # a message, and customizing the status code to return 200 instead of 404 fallback: enable: true code: 200 not_found: cannot find this resource ``` ```yaml # disable. you can also remove the `fallback` section entirely to disable fallback: enable: false ``` -------------------------------- ### Run Scheduler as a Dedicated Process Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/processing/scheduler.md Commands to start the scheduler independently using either a specific config file or environment settings. ```sh cargo loco scheduler --config config/scheduler.yaml ``` ```sh cargo loco scheduler ``` ```sh LOCO_ENV=production cargo loco scheduler ``` -------------------------------- ### List enabled middleware Source: https://github.com/loco-rs/loco/blob/master/docs-site/content/docs/the-app/controller.md Use the CLI to view the current middleware stack configuration. ```sh cargo loco middleware --config ``` ```sh $ cargo loco middleware --config limit_payload {"body_limit":{"Limit":1000000}} cors {"enable":true,"allow_origins":["any"],"allow_headers":["*"],"allow_methods":["*"],"expose_header":[""],"max_age":null,"vary":["origin","access-control-request-method","access-control-request-headers"]} catch_panic {"enable":true} etag {"enable":true} logger {"config":{"enable":true},"environment":"development"} request_id {"enable":true} fallback {"enable":true,"code":200,"file":null,"not_found":null} powered_by {"ident":"loco.rs"} remote_ip (disabled) compression (disabled) timeout (disabled) static_assets (disabled) secure_headers (disabled) ```