encore-dev 0.1.0

Rust SDK for Encore applications
Documentation
//! A minimal milestone-1 Encore Rust app: it declares a database, a pub/sub
//! topic, and a secret, and a `users` service (via `users/encore.service.json`)
//! whose `create` function uses all three.
//!
//! Endpoint serving is a later milestone, so `create` is an ordinary async
//! function here rather than a served HTTP endpoint.

use encore::pubsub::Topic;
use encore::secrets::SharedSecret;
use encore::storage::postgres::Database;
use serde::{Deserialize, Serialize};

// --- infrastructure declarations (discovered by the parser) ---

static DB: Database = Database::new("hello").migrations("./migrations");

#[derive(Serialize, Deserialize)]
struct SignupEvent {
    user_id: String,
}

static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");

static API_KEY: SharedSecret = SharedSecret::new("ApiKey");

// --- service code (the `users` service) ---

#[derive(Serialize, Deserialize)]
struct CreateUserReq {
    name: String,
}

#[derive(Serialize, Deserialize)]
struct User {
    id: String,
    name: String,
}

async fn create(req: CreateUserReq) -> Result<User, encore::Error> {
    let id = format!("user_{}", req.name.len());
    DB.execute(
        "INSERT INTO users (id, name) VALUES ($1, $2)",
        &[&id, &req.name],
    )
    .await?;
    SIGNUPS
        .publish(&SignupEvent {
            user_id: id.clone(),
        })
        .await?;
    // A secret read, just to exercise the secrets path.
    let _api_key = API_KEY.value()?;
    Ok(User { id, name: req.name })
}

#[tokio::main]
async fn main() {
    // Fail fast if the runtime isn't configured.
    encore::initialize();

    // Demonstrate the service function end-to-end against the local infra.
    match create(CreateUserReq {
        name: "ada".to_string(),
    })
    .await
    {
        Ok(user) => println!("created user {} ({})", user.name, user.id),
        Err(e) => eprintln!("create failed: {e}"),
    }

    // Milestone 1 has no endpoint serving; block to drain infra on shutdown.
    encore::run_blocking();
}