use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::ParseError;
use crate::object::{deserialize_string_to_option_parse_date, deserialize_string_to_parse_date};
use crate::types::ParseDate;
use crate::Parse;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ParseSession {
#[serde(rename = "objectId")]
pub object_id: String,
#[serde(deserialize_with = "deserialize_string_to_parse_date")]
#[serde(rename = "createdAt")]
pub created_at: ParseDate,
#[serde(default)] #[serde(deserialize_with = "deserialize_string_to_option_parse_date")]
#[serde(rename = "updatedAt")]
pub updated_at: Option<ParseDate>,
pub user: Value,
#[serde(rename = "sessionToken")]
pub session_token: String,
#[serde(rename = "installationId")]
pub installation_id: Option<String>,
#[serde(rename = "expiresAt")]
#[serde(default)] pub expires_at: Option<ParseDate>,
pub restricted: Option<bool>,
#[serde(rename = "createdWith")]
pub created_with: Option<Value>,
#[serde(flatten)]
pub other_fields: std::collections::HashMap<String, Value>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SessionUpdateResponse {
pub updated_at: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct GetAllSessionsResponse {
pub results: Vec<ParseSession>,
}
pub struct ParseSessionHandle<'a> {
client: &'a Parse,
}
impl<'a> ParseSessionHandle<'a> {
pub fn new(client: &'a Parse) -> Self {
ParseSessionHandle { client }
}
pub async fn me(&self) -> Result<ParseSession, ParseError> {
if self.client.session_token.is_none() {
return Err(ParseError::SessionTokenMissing);
}
self.client
._request(Method::GET, "sessions/me", None::<&Value>, false, None) .await
}
pub async fn get_by_object_id(&self, object_id: &str) -> Result<ParseSession, ParseError> {
let endpoint = format!("sessions/{}", object_id);
self.client
._request(Method::GET, &endpoint, None::<&Value>, true, None) .await
}
pub async fn delete_by_object_id(&self, object_id: &str) -> Result<(), ParseError> {
let endpoint = format!("sessions/{}", object_id);
let _: Value = self
.client
._request(Method::DELETE, &endpoint, None::<&Value>, true, None) .await?;
Ok(())
}
pub async fn update_by_object_id<T: Serialize + Send + Sync>(
&self,
object_id: &str,
session_data: &T,
) -> Result<SessionUpdateResponse, ParseError> {
let endpoint = format!("sessions/{}", object_id);
self.client
._request(Method::PUT, &endpoint, Some(session_data), true, None) .await
}
pub async fn get_all_sessions(
&self,
query_string: Option<&str>,
) -> Result<Vec<ParseSession>, ParseError> {
#[derive(Deserialize, Debug)]
struct SessionsResponse<T> {
results: Vec<T>,
}
let endpoint = match query_string {
Some(qs) => format!("sessions?{}", qs),
None => "sessions".to_string(),
};
let response: SessionsResponse<ParseSession> = self
.client
._request(Method::GET, &endpoint, None::<&Value>, true, None) .await?;
Ok(response.results)
}
}