emailit 2.0.3

The official Rust SDK for the Emailit Email API
Documentation
//! API key management service.

use std::sync::Arc;

use crate::client::BaseClient;
use crate::collection::Collection;
use crate::error::Error;
use crate::types::{ApiKey, CreateApiKeyParams, ListParams, UpdateApiKeyParams};

/// Service for managing API keys.
///
/// Accessed via [`Emailit::api_keys`](crate::Emailit::api_keys).
pub struct ApiKeyService {
    pub(crate) client: Arc<BaseClient>,
}

impl ApiKeyService {
    /// Creates a new API key.
    ///
    /// `POST /v2/api-keys`
    pub async fn create(&self, params: CreateApiKeyParams) -> Result<ApiKey, Error> {
        self.client
            .request("POST", "/v2/api-keys", to_body(&params), None)
            .await
    }

    /// Retrieves an API key by ID.
    ///
    /// `GET /v2/api-keys/:id`
    pub async fn get(&self, id: &str) -> Result<ApiKey, Error> {
        let path = format!("/v2/api-keys/{}", urlencoding::encode(id));
        self.client.request("GET", &path, None, None).await
    }

    /// Lists API keys with optional pagination.
    ///
    /// `GET /v2/api-keys`
    pub async fn list(&self, params: Option<ListParams>) -> Result<Collection<ApiKey>, Error> {
        let query = params.map(|p| {
            let mut q = Vec::new();
            if let Some(page) = p.page {
                q.push(("page", page.to_string()));
            }
            if let Some(limit) = p.limit {
                q.push(("limit", limit.to_string()));
            }
            q
        });
        self.client
            .request::<Collection<ApiKey>>("GET", "/v2/api-keys", None, query.as_deref())
            .await
    }

    /// Updates an API key by ID.
    ///
    /// `POST /v2/api-keys/:id`
    pub async fn update(&self, id: &str, params: UpdateApiKeyParams) -> Result<ApiKey, Error> {
        let path = format!("/v2/api-keys/{}", urlencoding::encode(id));
        self.client
            .request("POST", &path, to_body(&params), None)
            .await
    }

    /// Deletes an API key by ID.
    ///
    /// `DELETE /v2/api-keys/:id`
    pub async fn delete(&self, id: &str) -> Result<ApiKey, Error> {
        let path = format!("/v2/api-keys/{}", urlencoding::encode(id));
        self.client.request("DELETE", &path, None, None).await
    }
}

fn to_body(v: &impl serde::Serialize) -> Option<serde_json::Value> {
    serde_json::to_value(v).ok()
}