emailit 2.0.3

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

use std::sync::Arc;

use crate::client::BaseClient;
use crate::collection::Collection;
use crate::error::Error;
use crate::types::{Contact, CreateContactParams, ListParams, UpdateContactParams};

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

impl ContactService {
    /// Creates a new contact.
    ///
    /// `POST /v2/contacts`
    pub async fn create(&self, params: CreateContactParams) -> Result<Contact, Error> {
        self.client
            .request("POST", "/v2/contacts", to_body(&params), None)
            .await
    }

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

    /// Updates a contact by ID.
    ///
    /// `POST /v2/contacts/:id`
    pub async fn update(&self, id: &str, params: UpdateContactParams) -> Result<Contact, Error> {
        let path = format!("/v2/contacts/{}", urlencoding::encode(id));
        self.client
            .request("POST", &path, to_body(&params), None)
            .await
    }

    /// Lists contacts with optional pagination.
    ///
    /// `GET /v2/contacts`
    pub async fn list(&self, params: Option<ListParams>) -> Result<Collection<Contact>, 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<Contact>>("GET", "/v2/contacts", None, query.as_deref())
            .await
    }

    /// Deletes a contact by ID.
    ///
    /// `DELETE /v2/contacts/:id`
    pub async fn delete(&self, id: &str) -> Result<Contact, Error> {
        let path = format!("/v2/contacts/{}", 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()
}