### Start PostgreSQL with Docker Compose Source: https://context7.com/desiders/rust-templates/llms.txt Initiates the PostgreSQL service defined in docker-compose.yaml, setting necessary environment variables for user, password, and database. ```bash POSTGRES_USER=postgres POSTGRES_PASSWORD=secret POSTGRES_DB=api \ docker compose -f deployment/docker-compose.yaml up -d ``` -------------------------------- ### Telegram Bot Start Command Handler (Rust) Source: https://context7.com/desiders/rust-templates/llms.txt A Rust function that handles the `/start` and `/help` commands for a Telegram bot. It sends a welcome message and demonstrates replying to the user's message. ```rust use telers:: Bot, event::{EventReturn, telegram::HandlerResult}, methods::SendMessage, types::{Message, ReplyParameters}; pub async fn start(bot: Bot, message: Message) -> HandlerResult { bot.send( SendMessage::new( message.chat().id(), "Hello. This template is ready for Telegram bot use-cases.", ) .reply_parameters( ReplyParameters::new(message.message_id()) .allow_sending_without_reply(true), ), ) .await?; Ok(EventReturn::Finish) } ``` -------------------------------- ### Get OpenAPI JSON Specification Source: https://context7.com/desiders/rust-templates/llms.txt Fetch the OpenAPI JSON specification for the API. ```bash curl http://127.0.0.1:3001/api-docs/openapi.json ``` -------------------------------- ### Get All Users with Pagination Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a paginated list of users with cursor-based pagination. ```APIDOC ## GET /users ### Description Retrieves a paginated list of users with cursor-based pagination. Supports `after_id` for cursor position, `limit` for page size (default 50, max 100), and `order` for sorting direction (asc/desc). ### Method GET ### Endpoint /users ### Query Parameters - **after_id** (string) - Optional - The ID of the last user from the previous page to fetch the next set of results. - **limit** (integer) - Optional - The number of users to return per page. Defaults to 50, maximum is 100. - **order** (string) - Optional - The sorting order for the results. Accepts 'asc' (ascending) or 'desc' (descending). Defaults to 'asc'. ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (array) - A list of user objects. - **id** (string) - The user's ID. - **username** (string | null) - The user's username. - **created_at** (string) - Timestamp of user creation. - **updated_at** (string) - Timestamp of last user update. #### Response Example ```json { "is_success": true, "result": [ { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" }, { "id": "019682ab-7c3f-7000-8000-000000000002", "username": null, "created_at": "2024-01-15T11:00:00Z", "updated_at": "2024-01-15T11:00:00Z" } ] } ``` ``` -------------------------------- ### User Not Found Error Response Source: https://context7.com/desiders/rust-templates/llms.txt Example of a 404 Not Found error response when a user ID does not exist. ```json { "is_success": false, "code": 1002, "name": "USER_BY_ID_NOT_FOUND", "message": "User with id 019682ab-7c3f-7000-8000-000000000001 not found" } ``` -------------------------------- ### Get All Users with Pagination - Web API Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a paginated list of users using cursor-based pagination. Supports custom limits and sorting orders. ```bash # Get first page of users (default: 50 items, ascending order) curl "http://127.0.0.1:3001/users" ``` ```bash # Get users with custom pagination curl "http://127.0.0.1:3001/users?limit=10&order=desc" ``` ```bash # Get next page using cursor (after_id) curl "http://127.0.0.1:3001/users?after_id=019682ab-7c3f-7000-8000-000000000001&limit=10" ``` ```json # Response (200 OK): { "is_success": true, "result": [ { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" }, { "id": "019682ab-7c3f-7000-8000-000000000002", "username": null, "created_at": "2024-01-15T11:00:00Z", "updated_at": "2024-01-15T11:00:00Z" } ] } ``` -------------------------------- ### Get User by ID Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a single user by their UUID v7 identifier. Returns 404 Not Found if the user does not exist. ```APIDOC ## GET /users/{id} ### Description Retrieves a single user by their UUID v7 identifier. Returns 404 Not Found if the user does not exist. ### Method GET ### Endpoint /users/{id} ### Path Parameters - **id** (string) - Required - The UUID v7 identifier of the user to retrieve. ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (object) - The user object. - **id** (string) - The user's ID. - **username** (string | null) - The user's username. - **created_at** (string) - Timestamp of user creation. - **updated_at** (string) - Timestamp of last user update. #### Response Example ```json { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` #### Error Response (404 Not Found) - **is_success** (boolean) - Indicates if the request was successful. - **code** (integer) - Error code. - **name** (string) - Error name. - **message** (string) - Error message. #### Error Response Example ```json { "is_success": false, "code": 1002, "name": "USER_BY_ID_NOT_FOUND", "message": "User with id 019682ab-7c3f-7000-8000-000000000099 not found" } ``` ``` -------------------------------- ### Get Server Status - Status Endpoint Source: https://context7.com/desiders/rust-templates/llms.txt This endpoint provides the current health status of the server, indicating normal operation. ```bash # Get server status curl http://127.0.0.1:3001/status ``` ```json # Response (200 OK): { "is_success": true, "result": { "status": "OK" } } ``` -------------------------------- ### Get User by ID - Web API Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a specific user using their UUID v7 identifier. Returns a 404 error if the user is not found. ```bash # Get user by ID curl http://127.0.0.1:3001/users/019682ab-7c3f-7000-8000-000000000001 ``` ```json # Response (200 OK): { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` ```json # Error Response (404 Not Found): { "is_success": false, "code": 1002, "name": "USER_BY_ID_NOT_FOUND", "message": "User with id 019682ab-7c3f-7000-8000-000000000099 not found" } ``` -------------------------------- ### Get User by Username Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a user by their username using the `@{username}` path pattern. Returns 404 Not Found if no user exists with the given username. ```APIDOC ## GET /users/@{username} ### Description Retrieves a user by their username using the `@{username}` path pattern. Returns 404 Not Found if no user exists with the given username. ### Method GET ### Endpoint /users/@{username} ### Path Parameters - **username** (string) - Required - The username of the user to retrieve. ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (object) - The user object. - **id** (string) - The user's ID. - **username** (string | null) - The user's username. - **created_at** (string) - Timestamp of user creation. - **updated_at** (string) - Timestamp of last user update. #### Response Example ```json { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` #### Error Response (404 Not Found) - **is_success** (boolean) - Indicates if the request was successful. - **code** (integer) - Error code. - **name** (string) - Error name. - **message** (string) - Error message. #### Error Response Example ```json { "is_success": false, "code": 1003, "name": "USER_BY_USERNAME_NOT_FOUND", "message": "User with username unknown_user not found" } ``` ``` -------------------------------- ### Get User by Username - Web API Source: https://context7.com/desiders/rust-templates/llms.txt Retrieves a user by their username. The username is specified in the path using the `@{username}` format. Returns 404 if the username is not found. ```bash # Get user by username curl http://127.0.0.1:3001/users/@john_doe ``` ```json # Response (200 OK): { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` ```json # Error Response (404 Not Found): { "is_success": false, "code": 1003, "name": "USER_BY_USERNAME_NOT_FOUND", "message": "User with username unknown_user not found" } ``` -------------------------------- ### Run Web Template with Config Source: https://context7.com/desiders/rust-templates/llms.txt Execute the web template application, specifying the configuration file path via the CONFIG_PATH environment variable. ```bash CONFIG_PATH=./configs/dev.template.toml cargo run -p web_template ``` -------------------------------- ### Web Template TOML Configuration Source: https://context7.com/desiders/rust-templates/llms.txt Configure the web server address, logging levels, and database connection parameters using this TOML file. ```toml # configs/dev.template.toml [serve] addr = "127.0.0.1:3001" [logging] dirs = "debug,froodi=info" [database] user = "postgres" password = "secret" host = "127.0.0.1" port = 5432 database = "api" ``` -------------------------------- ### Database Migration Commands Source: https://context7.com/desiders/rust-templates/llms.txt Provides commands for managing database migrations using SeaORM CLI, including applying, rolling back, checking status, generating new migrations, and regenerating entity models. ```bash # Apply all pending migrations car go run -p web_template_migration # Apply migrations explicitly car go run -p web_template_migration -- up # Rollback last migration car go run -p web_template_migration -- down # Check migration status car go run -p web_template_migration -- status # Generate new migration file car go run -p web_template_migration -- generate create_posts_table # Regenerate SeaORM entity models from database sea-orm-cli generate entity \ -o src/infra/db/models \ --date-time-crate time \ --with-copy-enums \ --with-prelude none \ --compact-format ``` -------------------------------- ### Run Telegram Bot with Config Source: https://context7.com/desiders/rust-templates/llms.txt Execute the Telegram bot application, specifying the configuration file path via the CONFIG_PATH environment variable. ```bash CONFIG_PATH=./configs/dev.template.toml cargo run -p tg_bot_template ``` -------------------------------- ### Setting Up DI Container with Froodi in Rust Source: https://context7.com/desiders/rust-templates/llms.txt Configures the Froodi dependency injection container with layered registries for configuration, database connections, transaction managers, and interactors. Uses `froodi` and `sea-orm` crates. ```rust use froodi::{ DefaultScope::{App, Request}, Inject, InjectTransient, Registry, async_impl::{Container, RegistryWithSync}, async_registry, boxed, instance, registry, }; use sea_orm::{ConnectOptions, Database, DatabaseConnection}; // Configuration registry (app-scoped singletons) pub fn cfg_registry(cfg: Config) -> Registry { registry! { scope(App) [ provide(instance(cfg.database)), ] } } // Database connection registry with finalizer for cleanup pub fn db_registry(cfg: Registry) -> RegistryWithSync { async_registry! { provide( App, |Inject(cfg): Inject| async move { let mut options = ConnectOptions::new(cfg.get_postgres_url()); options.sqlx_logging(false); Database::connect(options).await .map_err(|e| InstantiateErrorKind::Custom(e.into())) }, finalizer = |conn: Arc| async move { let _ = conn.close_by_ref().await; }, ), extend(cfg), } } // Interactors registry (request-scoped) pub fn interactors_registry(tx_manager: RegistryWithSync) -> RegistryWithSync { async_registry! { scope(Request) [ provide( |InjectTransient(tx_manager): InjectTransient>| async move { Ok(user::interactors::AddUser::new(tx_manager)) } ), provide( |InjectTransient(tx_manager): InjectTransient>| async move { Ok(user::interactors::GetUserById::new(tx_manager)) } ), ], extend(tx_manager), } } // Initialize container pub fn init(interactors: RegistryWithSync) -> Container { let registry = async_registry! { extend(interactors) }; Container::new(registry) } ``` -------------------------------- ### Generate New Migration File Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Use this command to create a new migration file with a specified name. ```sh cargo run -- generate MIGRATION_NAME ``` -------------------------------- ### Apply All Pending Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Executes all pending database migrations. This is the default behavior when no subcommand is specified. ```sh cargo run ``` ```sh cargo run -- up ``` -------------------------------- ### Fresh Database Migration Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Drops all existing tables in the database and then reapplies all migrations. Use with caution as it deletes all data. ```sh cargo run -- fresh ``` -------------------------------- ### Check Server Health - Ping Endpoint Source: https://context7.com/desiders/rust-templates/llms.txt Use this endpoint to verify if the server is running and responsive. It returns a simple 'pong' to confirm connectivity. ```bash # Check if server is alive curl http://127.0.0.1:3001/ping ``` ```json # Response (200 OK): { "is_success": true, "result": "pong" } ``` -------------------------------- ### Create User Source: https://context7.com/desiders/rust-templates/llms.txt Creates a new user with a UUID v7 identifier and optional username. Returns 409 Conflict if a user with the same ID or username already exists. ```APIDOC ## POST /users ### Description Creates a new user with a UUID v7 identifier and optional username. The ID must be a valid UUID version 7 (time-sortable). Returns 409 Conflict if a user with the same ID or username already exists. ### Method POST ### Endpoint /users ### Request Body - **id** (string) - Required - The UUID v7 identifier for the user. - **username** (string) - Optional - The username for the user. ### Request Example ```json { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe" } ``` ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (object) - The created user object. - **id** (string) - The user's ID. - **username** (string | null) - The user's username. - **created_at** (string) - Timestamp of user creation. - **updated_at** (string) - Timestamp of last user update. #### Response Example ```json { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` #### Error Response (409 Conflict) - **is_success** (boolean) - Indicates if the request was successful. - **code** (integer) - Error code. - **name** (string) - Error name. - **message** (string) - Error message. #### Error Response Example ```json { "is_success": false, "code": 1001, "name": "USER_ALREADY_EXISTS", "message": "User with id 019682ab-7c3f-7000-8000-000000000001 or username \"john_doe\" already exists" } ``` ``` -------------------------------- ### Create User - Web API Source: https://context7.com/desiders/rust-templates/llms.txt Creates a new user with a time-sortable UUID v7 identifier and an optional username. Handles conflicts if the user ID or username already exists. ```bash # Create a new user with UUID v7 and username curl -X POST http://127.0.0.1:3001/users \ -H "Content-Type: application/json" \ -d '{ "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe" }' ``` ```json # Response (200 OK): { "is_success": true, "result": { "id": "019682ab-7c3f-7000-8000-000000000001", "username": "john_doe", "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:30:00Z" } } ``` ```json # Error Response (409 Conflict): { "is_success": false, "code": 1001, "name": "USER_ALREADY_EXISTS", "message": "User with id 019682ab-7c3f-7000-8000-000000000001 or username \"john_doe\" already exists" } ``` -------------------------------- ### Docker Compose for PostgreSQL Source: https://context7.com/desiders/rust-templates/llms.txt Defines a Docker Compose service for deploying PostgreSQL, including environment variables for credentials and health checks. ```yaml # deployment/docker-compose.yaml services: postgres: container_name: web_template.postgres image: "postgres:18-alpine" restart: "unless-stopped" ports: - "127.0.0.1:${POSTGRES_PORT:-5432}:5432" environment: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?error} POSTGRES_USER: ${POSTGRES_USER:?error} POSTGRES_DB: ${POSTGRES_DB:?error} volumes: - postgres.data:/var/lib/postgresql/data:rw healthcheck: test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"] interval: 10s timeout: 60s retries: 5 ``` -------------------------------- ### Generate Models Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Generates Rust entity models from the database schema. Specify output directory, date-time crate, and other options. ```sh sea-orm-cli generate entity \ -o ../src/infra/db/models \ --date-time-crate time \ --with-copy-enums \ --with-prelude none \ --compact-format ``` -------------------------------- ### Telegram Bot TOML Configuration Source: https://context7.com/desiders/rust-templates/llms.txt Configure the bot token, logging levels, and database connection for the Telegram bot template. ```toml # configs/dev.template.toml [bot] token = "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz" [logging] dirs = "debug,froodi=info" [database] user = "postgres" password = "secret" host = "127.0.0.1" port = 5432 database = "api" ``` -------------------------------- ### Check Migration Status Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Displays the current status of all database migrations, indicating which have been applied and which are pending. ```sh cargo run -- status ``` -------------------------------- ### Apply First N Pending Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Applies a specified number of the most recent pending migrations. ```sh cargo run -- up -n 10 ``` -------------------------------- ### Create User Middleware in Rust Source: https://context7.com/desiders/rust-templates/llms.txt Middleware to automatically create or update user records. Extracts user info from Telegram updates and persists it using the DI container. Requires `froodi` and `telers` crates. ```rust use froodi::async_impl::Container; use telers::{ Request, errors::{EventErrorKind, MiddlewareError}, event::EventReturn, middlewares::outer::{Middleware, MiddlewareResponse}, }; use crate::application::{common::Interactor as _, user::interactors::SaveUser}; use crate::domain::user::entities::User; #[derive(Clone)] pub struct CreateUser; impl Middleware for CreateUser { async fn call(&mut self, request: Request) -> Result { let Some(from) = request.update.from() else { return Ok((request, EventReturn::Finish)); }; let Some(container) = request.extensions.get::() else { return Ok((request, EventReturn::Finish)); }; let save_user = container .get_transient::() .await .map_err(MiddlewareError::new)?; let user = User::new(from.id, from.username.as_ref().map(ToString::to_string)); let _ = save_user.execute(user).await; Ok((request, EventReturn::Finish)) } } ``` -------------------------------- ### Refresh Database Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Rolls back all applied migrations and then reapplies them. This is useful for ensuring a clean state. ```sh cargo run -- refresh ``` -------------------------------- ### Health Check - Ping Endpoint Source: https://context7.com/desiders/rust-templates/llms.txt Returns a simple 'pong' response to verify the server is alive and accepting connections. ```APIDOC ## GET /ping ### Description Returns a simple "pong" response to verify the server is alive and accepting connections. ### Method GET ### Endpoint /ping ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (string) - The value "pong" confirming the server is responsive. #### Response Example ```json { "is_success": true, "result": "pong" } ``` ``` -------------------------------- ### Reset Database Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Rolls back all applied migrations without reapplying them. This effectively empties the database schema. ```sh cargo run -- reset ``` -------------------------------- ### Health Check - Status Endpoint Source: https://context7.com/desiders/rust-templates/llms.txt Returns server health status indicating the application is running normally. ```APIDOC ## GET /status ### Description Returns server health status indicating the application is running normally. ### Method GET ### Endpoint /status ### Response #### Success Response (200 OK) - **is_success** (boolean) - Indicates if the request was successful. - **result** (object) - Contains the server status. - **status** (string) - The current status of the server (e.g., "OK"). #### Response Example ```json { "is_success": true, "result": { "status": "OK" } } ``` ``` -------------------------------- ### Delete User by ID API Request Source: https://context7.com/desiders/rust-templates/llms.txt Use this cURL command to delete a user by their unique ID. Expects a 204 No Content response on success. ```bash curl -X DELETE http://127.0.0.1:3001/users/019682ab-7c3f-7000-8000-000000000001 ``` -------------------------------- ### AddUser Interactor in Rust Source: https://context7.com/desiders/rust-templates/llms.txt Business logic for creating new users with transaction support. Handles rollback on failure and commits on success. Implements the `Interactor` trait. ```rust use crate::{ application::{common::interactor::Interactor, db::tx_manager::TxManager}, domain::{common::errors::ErrKind, user::{entities::User, errors::UserAlreadyExists}}, }; pub struct AddUser { tx_manager: Box, } impl AddUser { pub const fn new(tx_manager: Box) -> Self { Self { tx_manager } } } impl Interactor for &AddUser { type Output = User; type Err = ErrKind; async fn execute(self, user: User) -> Result { let tx_manager = self.tx_manager.begin().await?; let user = match { let repo = tx_manager.user_repo(); repo.add(user).await } { Ok(user) => user, Err(err) => { tx_manager.rollback().await?; return Err(err); } }; tx_manager.commit().await?; Ok(user) } } ``` -------------------------------- ### Rollback Last Applied Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Reverts the last applied database migrations. By default, it rolls back all migrations. ```sh cargo run -- down ``` -------------------------------- ### Delete User by ID Source: https://context7.com/desiders/rust-templates/llms.txt Deletes a user by their UUID v7 identifier. Returns 204 No Content on success, or 404 Not Found if the user does not exist. ```APIDOC ## DELETE /users/{id} ### Description Deletes a user by their UUID v7 identifier. Returns 204 No Content on success, or 404 Not Found if the user does not exist. ### Method DELETE ### Endpoint /users/{id} ### Path Parameters - **id** (string) - Required - The UUID v7 identifier of the user to delete. ### Response #### Success Response (204 No Content) No response body is returned on successful deletion. #### Error Response (404 Not Found) - **is_success** (boolean) - Indicates if the request was successful. - **code** (integer) - Error code. - **name** (string) - Error name. - **message** (string) - Error message. #### Error Response Example ```json { "is_success": false, "code": 1002, "name": "USER_BY_ID_NOT_FOUND", "message": "User with id 019682ab-7c3f-7000-8000-000000000099 not found" } ``` ``` -------------------------------- ### Delete User by ID - Web API Source: https://context7.com/desiders/rust-templates/llms.txt Deletes a user identified by their UUID v7 ID. Returns a 204 No Content status on successful deletion or 404 if the user does not exist. ```bash # Delete user by ID curl -X DELETE http://127.0.0.1:3001/users/019682ab-7c3f-7000-8000-000000000001 ``` -------------------------------- ### Rollback Last N Applied Migrations Source: https://github.com/desiders/rust-templates/blob/master/tg-bot-template/migration/README.md Reverts a specified number of the most recently applied database migrations. ```sh cargo run -- down -n 10 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.