Back to Iii

Use Conditions with Triggers

docs/how-to/use-trigger-conditions.mdx

0.13.04.3 KB
Original Source

Goal

Run a condition Function before a Trigger runs, and only execute the handler Function when the condition passes.

Steps

1. Register the handler and condition Functions

Register a normal handler Function and a condition Function that returns true or false.

<Info title="All functions are the same"> Both Functions are declared in the same way. They only differ in how they are used. </Info> <Tabs> <Tab title="Node / TypeScript"> ```typescript title="conditions-functions.ts" import { registerWorker } from 'iii-sdk'

const iii = registerWorker(process.env.III_URL ?? 'ws://localhost:49134')

// condition iii.registerFunction( { id: 'conditions::is-high-value' }, async (event) => (event.new_value?.amount ?? 0) >= 1000, )

// handler iii.registerFunction( { id: 'orders::process-high-value' }, async (event) => ({ status_code: 200, body: { processed: true, amount: event.new_value?.amount ?? 0 }, }), )

</Tab>
<Tab title="Python">
```python title="conditions_functions.py"
from iii import register_worker

iii = register_worker("ws://localhost:49134")


# condition
def is_high_value(event):
    if not isinstance(event, dict):
        return False
    return (event.get("new_value") or {}).get("amount", 0) >= 1000


# handler
def process_high_value(event):
    amount = (event.get("new_value") or {}).get("amount", 0) if isinstance(event, dict) else 0
    return {"status_code": 200, "body": {"processed": True, "amount": amount}}


iii.register_function({"id": "conditions::is-high-value"}, is_high_value)
iii.register_function({"id": "orders::process-high-value"}, process_high_value)
</Tab> <Tab title="Rust"> ```rust title="conditions_functions.rs" use iii_sdk::{register_worker, InitOptions, RegisterFunctionMessage}; use serde_json::json;

#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let url = std::env::var("III_URL").unwrap_or_else(|_| "ws://127.0.0.1:49134".to_string()); let iii = register_worker(&url, InitOptions::default());

// condition
iii.register_function(
    RegisterFunctionMessage {
        id: "conditions::is-high-value".into(),
        description: None,
        request_format: None,
        response_format: None,
        metadata: None,
        invocation: None,
    },
    |input| async move {
        let amount = input["new_value"]["amount"].as_f64().unwrap_or(0.0);
        Ok(json!(amount >= 1000.0))
    },
);

// handler
iii.register_function(
    RegisterFunctionMessage {
        id: "orders::process-high-value".into(),
        description: None,
        request_format: None,
        response_format: None,
        metadata: None,
        invocation: None,
    },
    |input| async move {
        let amount = input["new_value"]["amount"].as_f64().unwrap_or(0.0);
        Ok(json!({
            "status_code": 200,
            "body": { "processed": true, "amount": amount }
        }))
    },
);

Ok(())

}

</Tab>
</Tabs>

### 2. Register triggers with the correct condition key

Create a Trigger and specify its condition with `condition_function_id`.

Example (`state` trigger):

<Tabs>
<Tab title="Node / TypeScript">
```typescript title="state-trigger-with-condition.ts"
iii.registerTrigger({
  type: 'state',
  function_id: 'orders::process-high-value',
  config: {
    scope: 'orders',
    key: 'status',
    condition_function_id: 'conditions::is-high-value',
  },
})
</Tab> <Tab title="Python"> ```python title="state_trigger_with_condition.py" iii.register_trigger({ "type": "state", "function_id": "orders::process-high-value", "config": { "scope": "orders", "key": "status", "condition_function_id": "conditions::is-high-value", }, }) ``` </Tab> <Tab title="Rust"> ```rust title="state_trigger_with_condition.rs" iii.register_trigger(RegisterTriggerInput { trigger_type: "state".into(), function_id: "orders::process-high-value".into(), config: json!({ "scope": "orders", "key": "status", "condition_function_id": "conditions::is-high-value" }), })?; ``` </Tab> </Tabs>

Result

When the trigger fires, iii calls the condition Function first. The handler Function runs only when the condition passes.