init
Run a function once at cold start. Can be side-effects only (logger, dotenv) or return shared
state (DB pool, HTTP client) injected as &T parameter. Works with both queries and mutations.
Side-Effects Only
When the init function returns nothing, it runs once for setup (logging, env vars, tracing).
// Side-effects only — logger, dotenv, tracing
async fn setup_logger() {
env_logger::init();
}
#[rpc_query(init = "setup_logger")]
async fn get_data() -> Data { ... }
#[rpc_mutation(init = "setup_logger")]
async fn create_item(input: ItemInput) -> Item { ... }Shared State
When the init function returns a value, it's stored and injected as &T into the handler. The init function runs once per cold start — the result is reused
across requests.
// Return shared state — DB pool, HTTP client, config
async fn setup_db() -> PgPool {
PgPool::connect(&env::var("DATABASE_URL").unwrap()).await.unwrap()
}
// The return type is injected as &T parameter
#[rpc_query(init = "setup_db")]
async fn get_users(pool: &PgPool) -> Vec<User> {
sqlx::query_as("SELECT * FROM users")
.fetch_all(pool).await.unwrap()
}
#[rpc_mutation(init = "setup_db")]
async fn create_user(pool: &PgPool, input: UserInput) -> User {
sqlx::query_as("INSERT INTO users ...")
.fetch_one(pool).await.unwrap()
}HTTP Client
// HTTP client for external API calls
async fn setup_client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.build()
.unwrap()
}
#[rpc_query(init = "setup_client")]
async fn get_weather(client: &reqwest::Client, city: String) -> Weather {
client.get(&format!("https://api.weather.com/{city}"))
.send().await.unwrap()
.json().await.unwrap()
}Combining Attributes
// Combine with other attributes
#[rpc_query(init = "setup_db", cache = "5m", timeout = "10s")]
async fn get_stats(pool: &PgPool) -> Stats { ... }Try it
Cold Start & Shared State
The setup() function runs once at cold start, measuring its own duration. Subsequent
requests reuse the same state — watch the request count increment while cold start time stays the
same.