Attribute Macro ic_cdk_macros::query

source ·
#[query]
Expand description

Register a query call entry point.

This attribute macro will export a function with name canister_query <name> in the canister module.

§Example

#[query]
fn query_function() {
    // ...
}

You can also specify the name of the exported function.

#[query(name = "some_name")]
fn query_function() {
    // ...
}

If you want to hide this method in the Candid generated by export_candid!, you will need to set hidden to true. The entry point still exists in the canister.

#[query(hidden = true)]
fn query_function() {
    // ...
}

You can specify a guard function to be executed before the query function. When the guard function returns an error, the query function will not proceed.

fn guard_function() -> Result<(), String> {
    // ...
}
#[query(guard = "guard_function")]
fn query_function() {
    // ...
}

To be able to make inter-canister calls from a query call, it must be a composite query (which cannot be executed in replicated mode).

#[query(composite = true)]
async fn composite_query_function() {
   let (wallet_name,): (Option<String>,) = ic_cdk::call(wallet_canister_principal(), "name", ()).await.unwrap();
}

If you would rather call the call::reply function than return a value, you will need to set manual_reply to true so that the canister does not trap.

use ic_cdk::api::call::{self, ManualReply};
#[query(manual_reply = true)]
fn query_function() -> ManualReply<MyResult> {
    let result = calculate_result();
    ManualReply::one(result)
}