Skip to main content

proto_blue_api/generated/com/atproto/label/
queryLabels.rs

1// Generated by atproto-codegen. Do not edit.
2//! Lexicon: com.atproto.label.queryLabels
3#![allow(clippy::pedantic, clippy::nursery, clippy::all)]
4
5use serde::{Deserialize, Serialize};
6
7/// Find labels relevant to the provided AT-URI patterns. Public endpoint for moderation services, though may return different or additional results with auth.
8/// XRPC Query: com.atproto.label.queryLabels
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Params {
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub cursor: Option<String>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub limit: Option<i64>,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub sources: Option<Vec<proto_blue_syntax::Did>>,
18    pub uri_patterns: Vec<String>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct Output {
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub cursor: Option<String>,
26    pub labels: Vec<crate::com::atproto::label::defs::Label>,
27}
28
29/// Errors a `call()` on this method can return.
30#[derive(Debug, thiserror::Error)]
31pub enum CallError {
32    #[error("{0}")]
33    Xrpc(proto_blue_xrpc::XrpcError),
34    #[error(transparent)]
35    Transport(#[from] proto_blue_xrpc::Error),
36    #[error(transparent)]
37    Json(#[from] serde_json::Error),
38}
39
40fn map_xrpc_error(err: proto_blue_xrpc::XrpcError) -> CallError {
41    CallError::Xrpc(err)
42}
43
44fn to_query_params(p: &Params) -> proto_blue_xrpc::QueryParams {
45    let mut qp = proto_blue_xrpc::QueryParams::new();
46    if let Some(v) = &p.cursor {
47        qp.insert(
48            "cursor".to_string(),
49            proto_blue_xrpc::QueryValue::String(v.to_string()),
50        );
51    }
52    if let Some(v) = &p.limit {
53        qp.insert(
54            "limit".to_string(),
55            proto_blue_xrpc::QueryValue::Integer(*v),
56        );
57    }
58    if let Some(v) = &p.sources {
59        qp.insert(
60            "sources".to_string(),
61            proto_blue_xrpc::QueryValue::Array(
62                v.iter()
63                    .map(|x| proto_blue_xrpc::QueryValue::String(x.to_string()))
64                    .collect(),
65            ),
66        );
67    }
68    {
69        let v = &p.uri_patterns;
70        qp.insert(
71            "uriPatterns".to_string(),
72            proto_blue_xrpc::QueryValue::Array(
73                v.iter()
74                    .map(|x| proto_blue_xrpc::QueryValue::String(x.to_string()))
75                    .collect(),
76            ),
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("com.atproto.label.queryLabels", qp.as_ref(), opts)
91        .await
92    {
93        Ok(r) => r,
94        Err(proto_blue_xrpc::Error::Xrpc(x)) => return Err(map_xrpc_error(x)),
95        Err(e) => return Err(CallError::Transport(e)),
96    };
97    Ok(serde_json::from_value(response.data)?)
98}
99
100/// Register a typed handler for this method on an [`proto_blue_xrpc::XrpcServer`].
101#[cfg(feature = "server")]
102pub fn register<F, Fut>(
103    server: proto_blue_xrpc::XrpcServer,
104    handler: F,
105) -> proto_blue_xrpc::XrpcServer
106where
107    F: Fn(proto_blue_xrpc::HandlerContext, Option<Params>) -> Fut + Send + Sync + 'static,
108    Fut: std::future::Future<Output = Result<Output, proto_blue_xrpc::XrpcServerError>>
109        + Send
110        + 'static,
111{
112    let handler = std::sync::Arc::new(handler);
113    server.query("com.atproto.label.queryLabels", move |ctx| {
114        let handler = handler.clone();
115        async move {
116            let params = params_from_ctx(&ctx);
117            let out = handler(ctx, params).await?;
118            let value = serde_json::to_value(&out).map_err(|e| {
119                proto_blue_xrpc::XrpcServerError::new(
120                    proto_blue_xrpc::ResponseType::InternalServerError,
121                    format!("output serialize: {e}"),
122                )
123            })?;
124            Ok::<_, proto_blue_xrpc::XrpcServerError>(value)
125        }
126    })
127}
128
129#[cfg(feature = "server")]
130fn params_from_ctx(ctx: &proto_blue_xrpc::HandlerContext) -> Option<Params> {
131    // Always construct a `Params` — required fields are
132    // validated upstream by the lexicon validator when enabled;
133    // missing values surface as runtime errors from the handler.
134    Some(Params {
135        cursor: ctx.params.get("cursor").cloned(),
136        limit: ctx.params.get("limit").and_then(|v| v.parse::<i64>().ok()),
137        sources: ctx.params.get("sources").and_then(|v| {
138            v.split(',')
139                .map(proto_blue_syntax::Did::new)
140                .collect::<Result<Vec<_>, _>>()
141                .ok()
142        }),
143        uri_patterns: (Some(
144            ctx.params
145                .get("uriPatterns")
146                .map(|v| v.split(',').map(String::from).collect::<Vec<_>>())
147                .unwrap_or_default(),
148        ))?,
149    })
150}