Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support references in from request from param #42

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ mod hello_handler {
use ohkami::utils::{Payload, Query};

#[Query]
pub struct HelloQuery {
name: String,
pub struct HelloQuery<'q> {
name: &'q str,
repeat: Option<usize>,
}

pub async fn hello_by_query(c: Context,
HelloQuery { name, repeat }: HelloQuery
pub async fn hello_by_query<'h>(c: Context,
HelloQuery { name, repeat }: HelloQuery<'h>
) -> Response {
tracing::info!("\
Called `hello_by_query`\
Expand All @@ -31,13 +31,13 @@ mod hello_handler {

#[Payload(JSON)]
#[derive(serde::Deserialize)]
pub struct HelloRequest {
name: String,
pub struct HelloRequest<'n> {
name: &'n str,
repeat: Option<usize>,
}

pub async fn hello_by_json(c: Context,
HelloRequest { name, repeat }: HelloRequest
pub async fn hello_by_json<'h>(c: Context,
HelloRequest { name, repeat }: HelloRequest<'h>
) -> Response {
tracing::info!("\
Called `hello_by_query`\
Expand All @@ -58,8 +58,8 @@ mod hello_handler {
mod fangs {
use ohkami::{Context, Request, Fang, IntoFang};

pub struct AppendServer;
impl IntoFang for AppendServer {
pub struct SetServer;
impl IntoFang for SetServer {
fn into_fang(self) -> Fang {
Fang(|c: &mut Context| {
c.set_headers()
Expand All @@ -77,7 +77,7 @@ mod fangs {
pub struct LogRequest;
impl IntoFang for LogRequest {
fn into_fang(self) -> Fang {
Fang(|req: &mut Request| {
Fang(|req: &Request| {
let __method__ = req.method;
let __path__ = req.path();

Expand All @@ -101,7 +101,7 @@ async fn main() {
.with_max_level(tracing::Level::INFO)
.init();

let hello_ohkami = Ohkami::with((AppendServer, LogRequest), (
let hello_ohkami = Ohkami::with((SetServer, LogRequest), (
"/query".
GET(hello_handler::hello_by_query),
"/json".
Expand Down
2 changes: 1 addition & 1 deletion examples/quick_start/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ async fn health_check(c: Context) -> Response {
c.NoContent()
}

async fn hello(c: Context, name: String) -> Response {
async fn hello(c: Context, name: &str) -> Response {
c.OK().text(format!("Hello, {name}!"))
}

Expand Down
12 changes: 6 additions & 6 deletions ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ DEBUG = [
"tokio?/macros",
"async-std?/attributes",
]
default = [
"rt_tokio",
#"rt_async-std",
"DEBUG",
# "nightly"
]
#default = [
# "rt_tokio",
# #"rt_async-std",
# "DEBUG",
# # "nightly"
#]
46 changes: 32 additions & 14 deletions ohkami/src/layer1_req_res/request/from_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,65 @@ use crate::{Request};
/// - `#[Query]`
/// - `#[Payload(JSON)]`
/// - `#[Payload(URLEncoded)]`
/// - ( `#[Payload(Form)]` )
/// - `#[Payload(Form)]`
///
/// implement this by default.
///
/// <br/>
///
/// Of course, you can manually implement for any structs that can be extracted from request:
///
/// ```ignore
/// ```
/// use ohkami::prelude::*;
///
/// struct HasPayload(bool);
///
/// impl FromRequest for HasPayload {
/// fn parse(req: &Request) -> Result<Self, Cow> {
/// impl ohkami::FromRequest<'_> for HasPayload {
/// type Error = std::convert::Infallible;
/// fn parse(req: &Request) -> Result<Self, Self::Error> {
/// Ok(Self(
/// req.payload.is_some()
/// req.payload().is_some()
/// ))
/// }
/// }
/// ```
pub trait FromRequest: Sized {
pub trait FromRequest<'req>: Sized {
type Error: std::fmt::Display + 'static;
fn parse(req: &Request) -> Result<Self, Self::Error>;
fn parse(req: &'req Request) -> Result<Self, Self::Error>;
}

pub trait FromParam: Sized {
pub trait FromParam<'p>: Sized {
type Error: std::fmt::Display;
fn from_param(param: &str) -> Result<Self, Self::Error>;
fn from_param(param: Cow<'p, str>) -> Result<Self, Self::Error>;
} const _: () = {
impl FromParam for String {
type Error = std::str::Utf8Error;
fn from_param(param: &str) -> Result<Self, Self::Error> {
impl<'p> FromParam<'p> for String {
type Error = std::convert::Infallible;
fn from_param(param: Cow<'p, str>) -> Result<Self, Self::Error> {
Ok(param.to_string())
}
}
impl<'p> FromParam<'p> for Cow<'p, str> {
type Error = std::convert::Infallible;
fn from_param(param: Cow<'p, str>) -> Result<Self, Self::Error> {
Ok(param)
}
}
impl<'p> FromParam<'p> for &'p str {
type Error = &'static str;
fn from_param(param: Cow<'p, str>) -> Result<Self, Self::Error> {
match param {
Cow::Borrowed(s) => Ok(s),
Cow::Owned(_) => Err("Found percent decoded `String`, can't convert into `&str` in `from_param`"),
}
}
}

macro_rules! unsigned_integers {
($( $unsigned_int:ty ),*) => {
$(
impl FromParam for $unsigned_int {
impl<'p> FromParam<'p> for $unsigned_int {
type Error = Cow<'static, str>;
fn from_param(param: &str) -> Result<Self, Self::Error> {
fn from_param(param: Cow<'p, str>) -> Result<Self, Self::Error> {
let digit_bytes = param.as_bytes();
if digit_bytes.is_empty() {return Err(Cow::Borrowed("Expected a number nut found an empty string"))}
match digit_bytes[0] {
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/layer1_req_res/request/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Request {
percent_decode_utf8(unsafe {self.path.as_bytes()}).unwrap()
}

#[inline] pub fn query<Value: FromParam>(&self, key: &str) -> Option<Result<Value, Value::Error>> {
#[inline] pub fn query<'req, Value: FromParam<'req>>(&'req self, key: &str) -> Option<Result<Value, Value::Error>> {
self.queries.get(key).map(Value::from_param)
}
pub fn append_query(&mut self, key: impl Into<std::borrow::Cow<'static, str>>, value: impl Into<std::borrow::Cow<'static, str>>) {
Expand Down
12 changes: 6 additions & 6 deletions ohkami/src/layer1_req_res/request/parse_payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,15 +465,15 @@ pub struct Parse<'a> {

for (k, v) in crate::__internal__::parse_urlencoded(buf) {
match &*k {
"id" => id.replace(<usize as crate::FromParam>::from_param(&v).map_err(|e| format!("{e:?}"))?)
"id" => id.replace(<usize as crate::FromParam>::from_param(v).map_err(|e| format!("{e:?}"))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `id`"))
)?,
"name" => name.replace(<String as crate::FromParam>::from_param(&v).map_err(|e| format!("{e:?}"))?)
"name" => name.replace(<String as crate::FromParam>::from_param(v).map_err(|e| format!("{e:?}"))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `name`"))
)?,
"age" => age.replace(<u8 as crate::FromParam>::from_param(&v).map_err(|e| format!("{e:?}"))?)
"age" => age.replace(<u8 as crate::FromParam>::from_param(v).map_err(|e| format!("{e:?}"))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `age`")),
)?,
Expand All @@ -500,15 +500,15 @@ pub struct Parse<'a> {

for (k, v) in crate::__internal__::parse_urlencoded(buf) {
match &*k {
"id" => id.replace(<usize as crate::FromParam>::from_param(&v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
"id" => id.replace(<usize as crate::FromParam>::from_param(v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `id`"))
)?,
"name" => name.replace(<String as crate::FromParam>::from_param(&v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
"name" => name.replace(<String as crate::FromParam>::from_param(v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `name`"))
)?,
"age" => age.replace(<u8 as crate::FromParam>::from_param(&v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
"age" => age.replace(<u8 as crate::FromParam>::from_param(v).map_err(|e| Cow::Owned(format!("{e:?}")))?)
.map_or(::std::result::Result::Ok(()), |_|
::std::result::Result::Err(::std::borrow::Cow::Borrowed("duplicated key: `age`")),
)?,
Expand Down
9 changes: 6 additions & 3 deletions ohkami/src/layer1_req_res/request/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@ pub struct QueryParams {
(std::str::from_utf8(k.as_bytes()).unwrap(), std::str::from_utf8(v.as_bytes()).unwrap())
})
}
#[inline] pub(crate) fn get(&self, key: &str) -> Option<&str> {
#[inline] pub(crate) fn get(&self, key: &str) -> Option<Cow<'_, str>> {
let key = key.as_bytes();
for kv in unsafe {self.params.get_unchecked(0..self.next)} {
unsafe {
let (k, v) = kv.assume_init_ref();
if key == k.as_bytes() {
return Some((|| std::str::from_utf8(v.as_bytes()).unwrap())())
return Some((|| match v {
CowSlice::Ref(slice) => Cow::Borrowed(std::str::from_utf8(slice.as_bytes()).unwrap()),
CowSlice::Own(vec) => Cow::Owned(String::from_utf8(vec.to_vec()).unwrap()),
})())
}
}
}
Expand Down Expand Up @@ -66,7 +69,7 @@ const _: () = {
impl PartialEq for QueryParams {
fn eq(&self, other: &Self) -> bool {
for (k, v) in self.iter() {
if other.get(k) != Some(v) {
if other.get(k) != Some(Cow::Borrowed(v)) {
return false
}
}
Expand Down
50 changes: 25 additions & 25 deletions ohkami/src/layer3_fang_handler/handler/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,23 +102,23 @@ macro_rules! Route {
pub const DB: __::Database = __::Database; mod __ {
pub struct Database;
impl Database {
pub async fn insert_returning_id(&self, Model: impl for<'de>serde::Deserialize<'de>) -> Result<usize, std::io::Error> {
pub async fn insert_returning_id(&self, Model: impl serde::Deserialize<'_>) -> Result<usize, std::io::Error> {
Ok(42)
}
pub async fn update_returning_id(&self, Model: impl for<'de>serde::Deserialize<'de>) -> Result<usize, std::io::Error> {
pub async fn update_returning_id(&self, Model: impl serde::Deserialize<'_>) -> Result<usize, std::io::Error> {
Ok(24)
}
}
}
}

#[derive(Deserialize)]
struct CreateUser {
name: String,
password: String,
} impl FromRequest for CreateUser {
struct CreateUser<'c> {
name: &'c str,
password: &'c str,
} impl<'req> FromRequest<'req> for CreateUser<'req> {
type Error = Cow<'static, str>;
fn parse(req: &crate::Request) -> Result<Self, ::std::borrow::Cow<'static, str>> {
fn parse(req: &'req crate::Request) -> Result<Self, ::std::borrow::Cow<'static, str>> {
let payload = req.payload().ok_or_else(|| Cow::Borrowed("Payload expected"))?;
match req.headers.ContentType() {
Some("application/json") => serde_json::from_slice(payload).map_err(|e| Cow::Owned(e.to_string())),
Expand All @@ -127,28 +127,31 @@ macro_rules! Route {
}
}

async fn create_user(c: Context, payload: CreateUser) -> Response {
async fn create_user<'req>(c: Context, payload: CreateUser<'req>) -> Response {
let CreateUser { name, password } = payload;

if let Err(_) = mock::authenticate().await {
return c.Unauthorized()
}

let Ok(id) = mock::DB.insert_returning_id(CreateUser{
name: name.clone(),
password: password.clone(),
}).await else {return c.InternalServerError()};
let Ok(id) = mock::DB.insert_returning_id(CreateUser{ name, password }).await else {
return c.InternalServerError();
};

c.Created().json(User { id, name, password })
c.Created().json(User {
id,
name: name.to_string(),
password: password.to_string(),
})
}

#[derive(Deserialize)]
struct UpdateUser {
name: Option<String>,
password: Option<String>,
} impl FromRequest for UpdateUser {
struct UpdateUser<'u> {
name: Option<&'u str>,
password: Option<&'u str>,
} impl<'req> FromRequest<'req> for UpdateUser<'req> {
type Error = Cow<'static, str>;
fn parse(req: &crate::Request) -> Result<Self, ::std::borrow::Cow<'static, str>> {
fn parse(req: &'req crate::Request) -> Result<Self, ::std::borrow::Cow<'static, str>> {
let payload = req.payload().ok_or_else(|| Cow::Borrowed("Payload expected"))?;
match req.headers.ContentType() {
Some("application/json") => serde_json::from_slice(payload).map_err(|e| Cow::Owned(e.to_string())),
Expand All @@ -157,17 +160,14 @@ macro_rules! Route {
}
}

async fn update_user(c: Context, req: UpdateUser) -> Response {
let UpdateUser { name, password } = req;

async fn update_user<'req>(c: Context, body: UpdateUser<'req>) -> Response {
if let Err(_) = mock::authenticate().await {
return c.Unauthorized()
}

if let Err(_) = mock::DB.update_returning_id(UpdateUser {
name: name.clone(),
password: password.clone(),
}).await {return c.InternalServerError()};
if let Err(_) = mock::DB.update_returning_id(body).await {
return c.InternalServerError();
};

c.NoContent()
}
Expand Down
Loading
Loading