proto-blue-api 0.3.1

AT Protocol high-level API: agent, rich text, moderation, generated types
Documentation
// Generated by atproto-codegen. Do not edit.
//! Lexicon: com.atproto.temp.checkHandleAvailability
#![allow(clippy::pedantic, clippy::nursery, clippy::all)]

use serde::{Deserialize, Serialize};

/// Checks whether the provided handle is available. If the handle is not available, available suggestions will be returned. Optional inputs will be used to generate suggestions.
/// XRPC Query: com.atproto.temp.checkHandleAvailability
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Params {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub birth_date: Option<proto_blue_syntax::Datetime>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    pub handle: proto_blue_syntax::Handle,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "$type")]
pub enum OutputResultRefs {
    #[serde(rename = "com.atproto.temp.checkHandleAvailability#resultAvailable")]
    AtprotoTempCheckHandleAvailabilityResultAvailable(Box<ResultAvailable>),
    #[serde(rename = "com.atproto.temp.checkHandleAvailability#resultUnavailable")]
    AtprotoTempCheckHandleAvailabilityResultUnavailable(Box<ResultUnavailable>),
    #[serde(other)]
    Other,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Output {
    pub handle: proto_blue_syntax::Handle,
    pub result: OutputResultRefs,
}

/// Errors a `call()` on this method can return.
#[derive(Debug, thiserror::Error)]
pub enum CallError {
    /// An invalid email was provided.
    #[error("InvalidEmail")]
    InvalidEmail,
    #[error("{0}")]
    Xrpc(proto_blue_xrpc::XrpcError),
    #[error(transparent)]
    Transport(#[from] proto_blue_xrpc::Error),
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

fn map_xrpc_error(err: proto_blue_xrpc::XrpcError) -> CallError {
    match err.error.as_deref() {
        Some("InvalidEmail") => CallError::InvalidEmail,
        _ => CallError::Xrpc(err),
    }
}

fn to_query_params(p: &Params) -> proto_blue_xrpc::QueryParams {
    let mut qp = proto_blue_xrpc::QueryParams::new();
    if let Some(v) = &p.birth_date {
        qp.insert(
            "birthDate".to_string(),
            proto_blue_xrpc::QueryValue::String(v.to_string()),
        );
    }
    if let Some(v) = &p.email {
        qp.insert(
            "email".to_string(),
            proto_blue_xrpc::QueryValue::String(v.to_string()),
        );
    }
    {
        let v = &p.handle;
        qp.insert(
            "handle".to_string(),
            proto_blue_xrpc::QueryValue::String(v.to_string()),
        );
    }
    qp
}

/// Execute the query.
pub async fn call(
    client: &proto_blue_xrpc::XrpcClient,
    params: Option<&Params>,
    opts: Option<&proto_blue_xrpc::CallOptions>,
) -> Result<Output, CallError> {
    let qp = params.map(to_query_params);
    let response = match client
        .query(
            "com.atproto.temp.checkHandleAvailability",
            qp.as_ref(),
            opts,
        )
        .await
    {
        Ok(r) => r,
        Err(proto_blue_xrpc::Error::Xrpc(x)) => return Err(map_xrpc_error(x)),
        Err(e) => return Err(CallError::Transport(e)),
    };
    Ok(serde_json::from_value(response.data)?)
}

/// Register a typed handler for this method on an [`proto_blue_xrpc::XrpcServer`].
#[cfg(feature = "server")]
pub fn register<F, Fut>(
    server: proto_blue_xrpc::XrpcServer,
    handler: F,
) -> proto_blue_xrpc::XrpcServer
where
    F: Fn(proto_blue_xrpc::HandlerContext, Option<Params>) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Output, proto_blue_xrpc::XrpcServerError>>
        + Send
        + 'static,
{
    let handler = std::sync::Arc::new(handler);
    server.query("com.atproto.temp.checkHandleAvailability", move |ctx| {
        let handler = handler.clone();
        async move {
            let params = params_from_ctx(&ctx);
            let out = handler(ctx, params).await?;
            let value = serde_json::to_value(&out).map_err(|e| {
                proto_blue_xrpc::XrpcServerError::new(
                    proto_blue_xrpc::ResponseType::InternalServerError,
                    format!("output serialize: {e}"),
                )
            })?;
            Ok::<_, proto_blue_xrpc::XrpcServerError>(value)
        }
    })
}

#[cfg(feature = "server")]
fn params_from_ctx(ctx: &proto_blue_xrpc::HandlerContext) -> Option<Params> {
    // Always construct a `Params` — required fields are
    // validated upstream by the lexicon validator when enabled;
    // missing values surface as runtime errors from the handler.
    Some(Params {
        birth_date: ctx
            .params
            .get("birthDate")
            .and_then(|v| proto_blue_syntax::Datetime::new(v).ok()),
        email: ctx.params.get("email").cloned(),
        handle: (ctx
            .params
            .get("handle")
            .and_then(|v| proto_blue_syntax::Handle::new(v).ok()))?,
    })
}

/// Indicates the provided handle is available.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultAvailable {}

/// Indicates the provided handle is unavailable and gives suggestions of available handles.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultUnavailable {
    pub suggestions: Vec<Suggestion>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Suggestion {
    pub handle: proto_blue_syntax::Handle,
    pub method: String,
}