pub async fn insert<T>(&self, item: Item<T>) -> Result<String>
    where
        T: Serialize,
    {
        let url = format!(
            "{}/{}/items",
            self.url,
            self.base_name.as_ref().ok_or(Error::BaseNameNotPresent)?,
        );

        let Item { key, value } = item;
        let mut value = serde_json::to_value(value).map_err(|_| Error::JSONSerializingFailed)?;

        if !value.is_object() {
            value = serde_json::json!({ "value": value });
        }

        if let Some(x) = key {
            value["key"] = serde_json::json!(x);
        }

        let req_body = serde_json::json!({ "item": value });

        let json: serde_json::Value = self
            .client
            .post(&url)
            .json(&req_body)
            .send()
            .await
            .map_err(|_| Error::RequestSendError)?
            .error_for_status()
            .map_err(|e| {
                if let Some(x) = e.status() {
                    if x == reqwest::StatusCode::CONFLICT {
                        return Error::KeyConflict;
                    } else if x == reqwest::StatusCode::BAD_REQUEST {
                        return Error::BadRequest;
                    }
                }
                Error::ServerError
            })?
            .json()
            .await
            .map_err(|_| Error::JSONDeserializingFailed)?;

        Ok(json["key"].as_str().ok_or(Error::ServerError)?.to_string())
    }
/// Creates a new item only if no item with the same `key` exists.
///
/// Returns the key, if successful. If the same key exists returns an Error.
///
/// # Arguments
///
/// * `item`: An `Item`.
///
/// # Errors
///
/// * [`Error::BaseNameNotPresent`](crate::Error::BaseNameNotPresent)
/// * [`Error::JSONSerializingFailed`](crate::Error::JSONSerializingFailed)
/// * [`Error::RequestSendError`](crate::Error::RequestSendError)
/// * [`Error::KeyConflict`](crate::Error::KeyConflict)
/// * [`Error::BadRequest`](crate::Error::BadRequest)
/// * [`Error::ServerError`](crate::Error::ServerError)
/// * [`Error::JSONDeserializingFailed`](crate::Error::JSONDeserializingFailed)
///
/// # Examples
///
/// ```
/// use deta::{Deta, Item};
/// # #[tokio::main]
/// # async fn main() -> deta::Result<()> {
/// let deta = Deta::new()?;
///
/// let base = deta.base("main");
/// # base.delete("insert_id").await?;
/// let item = Item::new_with_key("insert_id", 60);
/// base.insert(item).await?;
/// # Ok(())
/// # }
/// ```
Creates a new item only if no item with the same `key` exists.
Returns the key, if successful. If the same key exists returns an Error.
Creates a new item only if no item with the same ` key ` exists . Returns the key if successful . If the same key exists returns an Error .
pub async fn insert<T>(&self, item: Item<T>) -> Result<String>
    where
        T: Serialize,
    {
        let url = format!(
            "{}/{}/items",
            self.url,
            self.base_name.as_ref().ok_or(Error::BaseNameNotPresent)?,
        );
        let Item { key, value } = item;
        let mut value = serde_json::to_value(value).map_err(|_| Error::JSONSerializingFailed)?;
        if !value.is_object() {
            value = serde_json::json!({ "value": value });
        }
        if let Some(x) = key {
            value["key"] = serde_json::json!(x);
        }
        let req_body = serde_json::json!({ "item": value });
        let json: serde_json::Value = self
            .client
            .post(&url)
            .json(&req_body)
            .send()
            .await
            .map_err(|_| Error::RequestSendError)?
            .error_for_status()
            .map_err(|e| {
                if let Some(x) = e.status() {
                    if x == reqwest::StatusCode::CONFLICT {
                        return Error::KeyConflict;
                    } else if x == reqwest::StatusCode::BAD_REQUEST {
                        return Error::BadRequest;
                    }
                }
                Error::ServerError
            })?
            .json()
            .await
            .map_err(|_| Error::JSONDeserializingFailed)?;
        Ok(json["key"].as_str().ok_or(Error::ServerError)?.to_string())
    }
pub async fn insert < T > ( & self , item : Item < T > ) -> Result < String > where T : Serialize , { let url = format ! ( " " self url self base_name as_ref ( ) ok_or ( Error BaseNameNotPresent ) ) ; let Item { key , value } = item ; let mut value = serde_json :: to_value ( value ) . map_err ( | _ | Error :: JSONSerializingFailed ) ? ; if ! value . is_object ( ) { value = serde_json :: json ! ( { " " value } ) ; } if let Some ( x ) = key { value [ " " ] = serde_json :: json ! ( x ) ; } let req_body = serde_json :: json ! ( { " " value } ) ; let json : serde_json :: Value = self . client . post ( & url ) . json ( & req_body ) . send ( ) . await . map_err ( | _ | Error :: RequestSendError ) ? . error_for_status ( ) . map_err ( | e | { if let Some ( x ) = e . status ( ) { if x == reqwest :: StatusCode :: CONFLICT { return Error :: KeyConflict ; } else if x == reqwest :: StatusCode :: BAD_REQUEST { return Error :: BadRequest ; } } Error :: ServerError } ) ? . json ( ) . await . map_err ( | _ | Error :: JSONDeserializingFailed ) ? ; Ok ( json [ " " ] . as_str ( ) . ok_or ( Error :: ServerError ) ? . to_string ( ) ) }
Creates a new item only if no item with the same `key` exists.
Creates a new item only if no item with the same ` key ` exists .
&self
item
Item<T>
&self
item
Item<T>
errors
None
examples
None
#[tokio::main]
None
async fn main() -> deta::result<()> {
let deta = Deta::new()?.

let base = deta.base("main").
let deta = Deta :: new () ? . let base = deta . base ( " main " ) .
base.delete("insert_id").await?;
let item = Item::new_with_key("insert_id", 60);
base.insert(item).await?.
let item = Item :: new_with_key ( " insert_id " 60 ) ; base . insert ( item ) . await? .
ok(())
None
}
None