use super::{Encoding, FromReq, IntoReq};
use crate::{
error::ServerFnError,
request::{ClientReq, Req},
};
use http::Method;
use serde::{de::DeserializeOwned, Serialize};
pub struct GetUrl;
pub struct PostUrl;
impl Encoding for GetUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
const METHOD: Method = Method::GET;
}
impl<CustErr, T, Request> IntoReq<GetUrl, Request, CustErr> for T
where
Request: ClientReq<CustErr>,
T: Serialize + Send,
{
fn into_req(
self,
path: &str,
accepts: &str,
) -> Result<Request, ServerFnError<CustErr>> {
let data = serde_qs::to_string(&self)
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
Request::try_new_get(path, accepts, GetUrl::CONTENT_TYPE, &data)
}
}
impl<CustErr, T, Request> FromReq<GetUrl, Request, CustErr> for T
where
Request: Req<CustErr> + Send + 'static,
T: DeserializeOwned,
{
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
let string_data = req.as_query().unwrap_or_default();
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(string_data)
.map_err(|e| ServerFnError::Args(e.to_string()))?;
Ok(args)
}
}
impl Encoding for PostUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
const METHOD: Method = Method::POST;
}
impl<CustErr, T, Request> IntoReq<PostUrl, Request, CustErr> for T
where
Request: ClientReq<CustErr>,
T: Serialize + Send,
{
fn into_req(
self,
path: &str,
accepts: &str,
) -> Result<Request, ServerFnError<CustErr>> {
let qs = serde_qs::to_string(&self)
.map_err(|e| ServerFnError::Serialization(e.to_string()))?;
Request::try_new_post(path, accepts, PostUrl::CONTENT_TYPE, qs)
}
}
impl<CustErr, T, Request> FromReq<PostUrl, Request, CustErr> for T
where
Request: Req<CustErr> + Send + 'static,
T: DeserializeOwned,
{
async fn from_req(req: Request) -> Result<Self, ServerFnError<CustErr>> {
let string_data = req.try_into_string().await?;
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(&string_data)
.map_err(|e| ServerFnError::Args(e.to_string()))?;
Ok(args)
}
}