reflow_api_services 0.2.0

Generated API-service actor catalog for Reflow — thousands of actors across ~90 third-party services.
Documentation
#![allow(clippy::all, unused_imports, dead_code)]

//! Auto-generated API actors for Open Movie Database
//!
//! Service: Open Movie Database (omdb)
//! Movie information and posters
//!
//! Required env var: OMDB_API_KEY (API key)
//!
//! Generated by api-schema-gen codegen — do not edit manually.

use crate::{Actor, ActorBehavior, Message, Port};
use anyhow::{Error, Result};
use reflow_actor::{message::EncodableValue, ActorContext};
use reflow_actor_macro::actor;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::time::Duration;

const BASE_URL: &str = "https://www.omdbapi.com";
const ENV_KEY: &str = "OMDB_API_KEY";

/// Apply authentication to the request builder.
fn apply_auth(
    config: &reflow_actor::ActorConfig,
    mut builder: reqwest::RequestBuilder,
) -> Result<reqwest::RequestBuilder> {
    let credential = config
        .get_config_or_env(ENV_KEY)
        .ok_or_else(|| anyhow::anyhow!("Missing env var: {}", ENV_KEY))?;
    builder = builder.query(&[("apikey", &credential)]);
    Ok(builder)
}

/// search movies via Open Movie Database API
///
/// Method: GET /
#[actor(
    OmdbSearchMoviesActor,
    inports::<100>(s, type_, y),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn omdb_search_movies(context: ActorContext) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.get(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut query_pairs: Vec<(&str, String)> = Vec::new();
    if let Some(val) = inputs.get("s") {
        query_pairs.push(("s", super::message_to_str(val)));
    }
    if let Some(val) = inputs.get("type_") {
        query_pairs.push(("type", super::message_to_str(val)));
    }
    if let Some(val) = inputs.get("y") {
        query_pairs.push(("y", super::message_to_str(val)));
    }
    if !query_pairs.is_empty() {
        builder = builder.query(&query_pairs);
    }

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(format!("GET / failed: {}", e).into()),
            );
        }
    }

    Ok(output)
}

/// read movie via Open Movie Database API
///
/// Method: GET /
#[actor(
    OmdbReadMovieActor,
    inports::<100>(i, plot),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn omdb_read_movie(context: ActorContext) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.get(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut query_pairs: Vec<(&str, String)> = Vec::new();
    if let Some(val) = inputs.get("i") {
        query_pairs.push(("i", super::message_to_str(val)));
    }
    if let Some(val) = inputs.get("plot") {
        query_pairs.push(("plot", super::message_to_str(val)));
    }
    if !query_pairs.is_empty() {
        builder = builder.query(&query_pairs);
    }

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(format!("GET / failed: {}", e).into()),
            );
        }
    }

    Ok(output)
}

/// Retrieve a movie poster image (Poster API at img.omdbapi.com, patrons only)
///
/// Method: GET /
#[actor(
    OmdbReadPosterActor,
    inports::<100>(apikey, i, h),
    outports::<50>(response, error),
    state(MemoryState)
)]
pub async fn omdb_read_poster(context: ActorContext) -> Result<HashMap<String, Message>, Error> {
    let inputs = context.get_payload();
    let actor_config = context.get_config();

    let endpoint = "/".to_string();

    let url = format!("{}{}", BASE_URL.trim_end_matches('/'), endpoint);

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(30))
        .build()?;

    let mut builder = client.get(&url);
    builder = builder.header("Content-Type", "application/json");
    builder = apply_auth(actor_config, builder)?;

    let mut query_pairs: Vec<(&str, String)> = Vec::new();
    if let Some(val) = inputs.get("apikey") {
        query_pairs.push(("apikey", super::message_to_str(val)));
    }
    if let Some(val) = inputs.get("i") {
        query_pairs.push(("i", super::message_to_str(val)));
    }
    if let Some(val) = inputs.get("h") {
        query_pairs.push(("h", super::message_to_str(val)));
    }
    if !query_pairs.is_empty() {
        builder = builder.query(&query_pairs);
    }

    let mut output = HashMap::new();
    match builder.send().await {
        Ok(resp) => {
            let status = resp.status().as_u16();
            let headers: HashMap<String, String> = resp
                .headers()
                .iter()
                .filter_map(|(k, v)| v.to_str().ok().map(|val| (k.to_string(), val.to_string())))
                .collect();
            let body_text = resp.text().await.unwrap_or_default();
            let body_value: Value =
                serde_json::from_str(&body_text).unwrap_or(Value::String(body_text));
            output.insert(
                "response".to_string(),
                Message::object(EncodableValue::from(json!({
                    "status": status,
                    "headers": headers,
                    "body": body_value,
                }))),
            );
        }
        Err(e) => {
            output.insert(
                "error".to_string(),
                Message::Error(format!("GET / failed: {}", e).into()),
            );
        }
    }

    Ok(output)
}