df_st_api 0.3.0-development-1

Starting an API server for the DF Storyteller project.
Documentation
use crate::api_objects::ApiObject;
use crate::ServerInfo;
use df_st_core::SchemaExample;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use rocket::State;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;

/// A Wrapper for an `ApiObject` that includes additional metadata.
#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
#[schemars(example = "Self::example")]
pub struct ApiMinimalItem<D>
where
    D: ApiObject + Serialize + SchemaExample,
{
    /// A unique string identifier for this type.
    #[serde(rename = "_type")]
    pub type_: String,
    /// The included data item.
    #[serde(flatten)]
    pub data: D,
    /// Server base url.
    /// Not included in response.
    #[serde(skip)]
    pub base_url: String,
}

impl<D> SchemaExample for ApiMinimalItem<D>
where
    D: SchemaExample + Serialize + ApiObject,
{
    fn example() -> Self {
        Self {
            type_: D::get_type(),
            data: D::example(),
            base_url: "".to_owned(),
        }
    }
}

impl<D> ApiMinimalItem<D>
where
    D: ApiObject + Default + Serialize + SchemaExample,
{
    pub fn new(server_info: &State<ServerInfo>) -> Self {
        let server_info = server_info.inner().clone();
        let mut new_object = Self::default();
        new_object.base_url = server_info.base_url;
        new_object
    }

    /// Store the data in the object and construct links.
    pub fn wrap(&mut self, item: D) {
        self.data = item;
        self.type_ = D::get_type();
    }

    /// Create and wrap the item.
    /// This is the same as doing:
    /// ```ignore
    /// let api_item = ApiMinimalItem::wrap_new(result_item, &server_info.base_url);
    /// // same as:
    /// let api_item = ApiMinimalItem::new(server_info);
    /// api_item.wrap(result_item);
    /// ```
    pub fn wrap_new(item: D, base_url: &str) -> ApiMinimalItem<D> {
        let mut return_object = ApiMinimalItem::default();
        return_object.base_url = base_url.to_string();
        return_object.wrap(item);
        return_object
    }
}