Skip to main content

proto_blue_api/generated/com/atproto/temp/
checkHandleAvailability.rs

1// Generated by atproto-codegen. Do not edit.
2//! Lexicon: com.atproto.temp.checkHandleAvailability
3#![allow(clippy::pedantic, clippy::nursery, clippy::all)]
4
5use serde::{Deserialize, Serialize};
6
7/// 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.
8/// XRPC Query: com.atproto.temp.checkHandleAvailability
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Params {
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub birth_date: Option<proto_blue_syntax::Datetime>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub email: Option<String>,
16    pub handle: proto_blue_syntax::Handle,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(tag = "$type")]
21pub enum OutputResultRefs {
22    #[serde(rename = "com.atproto.temp.checkHandleAvailability#resultAvailable")]
23    AtprotoTempCheckHandleAvailabilityResultAvailable(Box<ResultAvailable>),
24    #[serde(rename = "com.atproto.temp.checkHandleAvailability#resultUnavailable")]
25    AtprotoTempCheckHandleAvailabilityResultUnavailable(Box<ResultUnavailable>),
26    #[serde(other)]
27    Other,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub struct Output {
33    pub handle: proto_blue_syntax::Handle,
34    pub result: OutputResultRefs,
35}
36
37/// Errors a `call()` on this method can return.
38#[derive(Debug, thiserror::Error)]
39pub enum CallError {
40    /// An invalid email was provided.
41    #[error("InvalidEmail")]
42    InvalidEmail,
43    #[error("{0}")]
44    Xrpc(proto_blue_xrpc::XrpcError),
45    #[error(transparent)]
46    Transport(#[from] proto_blue_xrpc::Error),
47    #[error(transparent)]
48    Json(#[from] serde_json::Error),
49}
50
51fn map_xrpc_error(err: proto_blue_xrpc::XrpcError) -> CallError {
52    match err.error.as_deref() {
53        Some("InvalidEmail") => CallError::InvalidEmail,
54        _ => CallError::Xrpc(err),
55    }
56}
57
58fn to_query_params(p: &Params) -> proto_blue_xrpc::QueryParams {
59    let mut qp = proto_blue_xrpc::QueryParams::new();
60    if let Some(v) = &p.birth_date {
61        qp.insert(
62            "birthDate".to_string(),
63            proto_blue_xrpc::QueryValue::String(v.to_string()),
64        );
65    }
66    if let Some(v) = &p.email {
67        qp.insert(
68            "email".to_string(),
69            proto_blue_xrpc::QueryValue::String(v.to_string()),
70        );
71    }
72    {
73        let v = &p.handle;
74        qp.insert(
75            "handle".to_string(),
76            proto_blue_xrpc::QueryValue::String(v.to_string()),
77        );
78    }
79    qp
80}
81
82/// Execute the query.
83pub async fn call(
84    client: &proto_blue_xrpc::XrpcClient,
85    params: Option<&Params>,
86    opts: Option<&proto_blue_xrpc::CallOptions>,
87) -> Result<Output, CallError> {
88    let qp = params.map(to_query_params);
89    let response = match client
90        .query(
91            "com.atproto.temp.checkHandleAvailability",
92            qp.as_ref(),
93            opts,
94        )
95        .await
96    {
97        Ok(r) => r,
98        Err(proto_blue_xrpc::Error::Xrpc(x)) => return Err(map_xrpc_error(x)),
99        Err(e) => return Err(CallError::Transport(e)),
100    };
101    Ok(serde_json::from_value(response.data)?)
102}
103
104/// Register a typed handler for this method on an [`proto_blue_xrpc::XrpcServer`].
105#[cfg(feature = "server")]
106pub fn register<F, Fut>(
107    server: proto_blue_xrpc::XrpcServer,
108    handler: F,
109) -> proto_blue_xrpc::XrpcServer
110where
111    F: Fn(proto_blue_xrpc::HandlerContext, Option<Params>) -> Fut + Send + Sync + 'static,
112    Fut: std::future::Future<Output = Result<Output, proto_blue_xrpc::XrpcServerError>>
113        + Send
114        + 'static,
115{
116    let handler = std::sync::Arc::new(handler);
117    server.query("com.atproto.temp.checkHandleAvailability", move |ctx| {
118        let handler = handler.clone();
119        async move {
120            let params = params_from_ctx(&ctx);
121            let out = handler(ctx, params).await?;
122            let value = serde_json::to_value(&out).map_err(|e| {
123                proto_blue_xrpc::XrpcServerError::new(
124                    proto_blue_xrpc::ResponseType::InternalServerError,
125                    format!("output serialize: {e}"),
126                )
127            })?;
128            Ok::<_, proto_blue_xrpc::XrpcServerError>(value)
129        }
130    })
131}
132
133#[cfg(feature = "server")]
134fn params_from_ctx(ctx: &proto_blue_xrpc::HandlerContext) -> Option<Params> {
135    // Always construct a `Params` — required fields are
136    // validated upstream by the lexicon validator when enabled;
137    // missing values surface as runtime errors from the handler.
138    Some(Params {
139        birth_date: ctx
140            .params
141            .get("birthDate")
142            .and_then(|v| proto_blue_syntax::Datetime::new(v).ok()),
143        email: ctx.params.get("email").cloned(),
144        handle: (ctx
145            .params
146            .get("handle")
147            .and_then(|v| proto_blue_syntax::Handle::new(v).ok()))?,
148    })
149}
150
151/// Indicates the provided handle is available.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase")]
154pub struct ResultAvailable {}
155
156/// Indicates the provided handle is unavailable and gives suggestions of available handles.
157#[derive(Debug, Clone, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159pub struct ResultUnavailable {
160    pub suggestions: Vec<Suggestion>,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
164#[serde(rename_all = "camelCase")]
165pub struct Suggestion {
166    pub handle: proto_blue_syntax::Handle,
167    pub method: String,
168}