emailit 2.0.3

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

use std::sync::Arc;

use crate::client::BaseClient;
use crate::collection::Collection;
use crate::error::Error;
use crate::types::{CreateTemplateParams, ListParams, Template, UpdateTemplateParams};

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

impl TemplateService {
    /// Creates a new template.
    ///
    /// `POST /v2/templates`
    pub async fn create(&self, params: CreateTemplateParams) -> Result<Template, Error> {
        self.client
            .request("POST", "/v2/templates", to_body(&params), None)
            .await
    }

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

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

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

    /// Deletes a template by ID.
    ///
    /// `DELETE /v2/templates/:id`
    pub async fn delete(&self, id: &str) -> Result<serde_json::Value, Error> {
        let path = format!("/v2/templates/{}", urlencoding::encode(id));
        self.client.request("DELETE", &path, None, None).await
    }

    /// Publishes a template draft, making it the active version.
    ///
    /// `POST /v2/templates/:id/publish`
    pub async fn publish(&self, id: &str) -> Result<Template, Error> {
        let path = format!("/v2/templates/{}/publish", urlencoding::encode(id));
        self.client.request("POST", &path, None, None).await
    }
}

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