diff --git a/Cargo.toml b/Cargo.toml index f7d0863..e57d93d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] members = [ - "rupring", + "rupring", "rupring_example", "rupring_macro" ] -resolver = "2" \ No newline at end of file +resolver = "2" diff --git a/README.md b/README.md index d9c7219..04ec083 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # rupring -![](https://img.shields.io/badge/language-Rust-red) ![](https://img.shields.io/badge/version-0.8.1-brightgreen) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/myyrakle/rupring/blob/master/LICENSE) +![](https://img.shields.io/badge/language-Rust-red) ![](https://img.shields.io/badge/version-0.8.2-brightgreen) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/myyrakle/rupring/blob/master/LICENSE) spring on rust diff --git a/rupring/Cargo.toml b/rupring/Cargo.toml index 6573b76..460968b 100644 --- a/rupring/Cargo.toml +++ b/rupring/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rupring" -version = "0.8.1" +version = "0.8.2" edition = "2021" license = "MIT" authors = ["myyrakle "] @@ -14,7 +14,7 @@ homepage = "https://github.com/myyrakle/rupring/blob/master/README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rupring_macro={ version="0.8.0", path="../rupring_macro" } +rupring_macro={ version="0.8.2", path="../rupring_macro" } hyper = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] } http-body-util = "0.1.0" @@ -33,7 +33,3 @@ features = [ "fast-rng", # Use a faster (but still sufficiently random) RNG "macro-diagnostics", # Enable better diagnostics for compile-time UUIDs ] - -[[bin]] -name = "example" -path = "src/example/main.rs" diff --git a/rupring/src/example/domains/users/interface.rs b/rupring/src/example/domains/users/interface.rs deleted file mode 100644 index 74e36ba..0000000 --- a/rupring/src/example/domains/users/interface.rs +++ /dev/null @@ -1,28 +0,0 @@ -use super::{ - dto::{ - CreateUserRequest, CreateUserResponse, DeleteUserRequest, DeleteUserResponse, - GetUserRequest, GetUserResponse, ListUsersRequest, ListUsersResponse, UpdateUserRequest, - UpdateUserResponse, - }, - model::{ - CountUsersParams, CreateUserParams, DeleteUserParams, GetUserParams, ListUsersParams, - UpdateUserParams, User, Users, - }, -}; - -pub trait IUserService { - fn create_user(&self, request: CreateUserRequest) -> anyhow::Result; - fn update_user(&self, request: UpdateUserRequest) -> anyhow::Result; - fn delete_user(&self, request: DeleteUserRequest) -> anyhow::Result; - fn get_user(&self, request: GetUserRequest) -> anyhow::Result; - fn list_users(&self, request: ListUsersRequest) -> anyhow::Result; -} - -pub trait IUserRepository { - fn create_user(&self, params: CreateUserParams) -> anyhow::Result; - fn update_user(&self, params: UpdateUserParams) -> anyhow::Result<()>; - fn delete_user(&self, params: DeleteUserParams) -> anyhow::Result<()>; - fn get_user(&self, params: GetUserParams) -> anyhow::Result>; - fn list_users(&self, params: ListUsersParams) -> anyhow::Result; - fn count_users(&self, params: CountUsersParams) -> anyhow::Result; -} diff --git a/rupring/src/lib.rs b/rupring/src/lib.rs index bd1d701..351b7ac 100644 --- a/rupring/src/lib.rs +++ b/rupring/src/lib.rs @@ -1,6 +1,6 @@ /*! # Get Started There is only one dependency. -```ignore +```bash cargo add rupring ``` @@ -37,7 +37,7 @@ async fn main() -> Result<(), Box> { # Request You can access any value provided in an HTTP Request through the Request parameter. -```rust,ignore +```rust #[rupring::Get(path = /:id)] pub fn hello(request: rupring::Request) -> rupring::Response { let method = request.method; @@ -53,13 +53,15 @@ pub fn hello(request: rupring::Request) -> rupring::Response { let content_type = headers.get("content-type").unwrap(); assert_eq!(content_type, "text/plain"); - let id = request.path_param("id").unwrap(); + let id = request.path_parameters["id"].clone(); assert_eq!(id, "123"); - let query = request.query_param("query").unwrap(); - assert_eq!(query, "asdf"); + let query = request.query_parameters["query"].clone(); + assert_eq!(query, vec!["asdf".to_string()]); + + //... - ... + response } ``` @@ -68,7 +70,7 @@ pub fn hello(request: rupring::Request) -> rupring::Response { For path parameters, auto binding is provided through annotation. The annotation name can be one of `Path`, `path`, or `PathVariable`. -```rust,ignore +```rust #[rupring::Get(path = /echo/:id)] pub fn echo( #[PathVariable="id"] id: i32 @@ -80,18 +82,20 @@ pub fn echo( ``` If the Path Param is optional, just wrap the type in `Option`. -```rust,ignore +```rust #[rupring::Get(path = /echo/:id)] pub fn echo( #[PathVariable="id"] id: Option ) -> rupring::Response { - ... + // ... + + rupring::Response::new().text("OK".to_string()) } ``` If you need Swagger documentation for the Path Param, you should add the `Description` annotation. `Description` can also be used as `Desc`, `desc`, etc. -```rust,ignore +```rust #[rupring::Get(path = /echo/:id)] pub fn echo( #[path="id"] #[desc="asdf"] id: i32 @@ -103,12 +107,15 @@ pub fn echo( ``` If you want to define a custom type for PathParam, you can implement the ParamStringDeserializer trait. -```rust,ignore -impl ParamStringDeserializer for ParamString { +```rust +struct SomeCustomType {} + +impl rupring::ParamStringDeserializer for rupring::ParamString { type Error = (); fn deserialize(&self) -> Result { - ... + //... + Ok(SomeCustomType {}) } } ``` @@ -117,7 +124,7 @@ impl ParamStringDeserializer for ParamString { # Response You can create a response like this: -```rust,ignore +```rust #[rupring::Get(path = /)] pub fn hello(_request: rupring::Request) -> rupring::Response { rupring::Response::new().text("Hello, World!".to_string()) @@ -125,7 +132,7 @@ pub fn hello(_request: rupring::Request) -> rupring::Response { ``` You can also return a json value like this: -```rust,ignore +```rust #[derive(serde::Serialize)] struct User { name: String, @@ -140,7 +147,7 @@ pub fn get_user(_request: rupring::Request) -> rupring::Response { ``` You can set the status code like this: -```rust,ignore +```rust #[rupring::Get(path = /asdf)] pub fn not_found(_request: rupring::Request) -> rupring::Response { rupring::Response::new().text("not found".to_string()).status(404) @@ -148,7 +155,7 @@ pub fn not_found(_request: rupring::Request) -> rupring::Response { ``` You can set the header like this: -```rust,ignore +```rust #[rupring::Get(path = /)] pub fn hello(_request: rupring::Request) -> rupring::Response { rupring::Response::new() @@ -158,7 +165,7 @@ pub fn hello(_request: rupring::Request) -> rupring::Response { ``` If you want, you can receive it as a parameter instead of creating the response directly. -```rust,ignore +```rust #[rupring::Get(path = /)] pub fn hello(_request: rupring::Request, response: rupring::Response) -> rupring::Response { response @@ -169,7 +176,7 @@ pub fn hello(_request: rupring::Request, response: rupring::Response) -> rupring This is especially useful when you need to inherit and use Response through middleware. If you want to redirect, you can use Response’s redirect method. -```rust,ignore +```rust #[rupring::Get(path = /)] pub fn hello(_request: rupring::Request) -> rupring::Response { rupring::Response::new().redirect("/hello") @@ -183,11 +190,11 @@ rupring provides middleware features for common logic processing. If you want to log requests for all APIs that exist in a module, you can apply middleware in the form below. First, define a middleware function. -```rust,ignore +```rust pub fn logger_middleware( request: rupring::Request, response: rupring::Response, - next: NextFunction, + next: rupring::NextFunction, ) -> rupring::Response { println!( "Request: {} {}", @@ -203,19 +210,45 @@ If you want to return a response immediately without forwarding, just return the And you can register the middleware function just defined in the module or controller unit. -```rust,ignore +```rust +pub fn logger_middleware( + request: rupring::Request, + response: rupring::Response, + next: rupring::NextFunction, +) -> rupring::Response { + println!( + "Request: {} {}", + request.method.to_string(), + request.path.to_string() + ); + + next(request, response) +} + #[derive(Debug, Clone, Copy)] #[rupring::Module( - controllers=[HomeController{}], + controllers=[RootController{}], modules=[UserModule{}], providers=[], middlewares=[logger_middleware] )] pub struct RootModule {} +#[derive(Debug, Clone)] +#[rupring::Controller(prefix=/, routes=[])] +pub struct RootController {} + +#[derive(Debug, Clone, Copy)] +#[rupring::Module( + controllers=[UserController{}], + providers=[], + middlewares=[] +)] +pub struct UserModule {} + // or Controller #[derive(Debug, Clone)] -#[rupring::Controller(prefix=/, routes=[get_user], middlewares=[logger_middleware])] +#[rupring::Controller(prefix=/, routes=[], middlewares=[logger_middleware])] pub struct UserController {} ``` Middleware registered in a module is recursively applied to the routes of controllers registered in that module and to child modules. @@ -234,7 +267,7 @@ rupring provides DI feature. If you want to implement and DI a Provider that contains simple functionality, you can do it like this: First, define the Provider. -```rust,ignore +```rust #[derive(Debug, Clone, Default)] pub struct HomeService {} @@ -252,14 +285,37 @@ impl rupring::IProvider for HomeService { ``` Second, add it as a dependency to the module you want to use. -```rust,ignore +```rust +use std::any::Any; + +#[derive(Debug, Clone, Default)] +pub struct HomeService {} + +impl rupring::IProvider for HomeService { + fn provide(&self, _di_context: &rupring::DIContext) -> Box { + Box::new(HomeService {}) + } +} + +#[derive(Debug, Clone, Copy)] +#[rupring::Controller(prefix=/, routes=[])] +pub struct HomeController {} + #[derive(Debug, Clone, Copy)] #[rupring::Module(controllers=[HomeController{}], modules=[], providers=[HomeService::default()])] pub struct RootModule {} ``` And, you can use it by getting it from the router through the request object. -```rust,ignore +```rust +pub struct HomeService {} + +impl HomeService { + pub fn hello(&self) -> String { + "hello!!".to_string() + } +} + #[rupring::Get(path = /)] pub fn hello(request: rupring::Request) -> rupring::Response { let home_service = request.get_provider::().unwrap(); @@ -269,7 +325,22 @@ pub fn hello(request: rupring::Request) -> rupring::Response { ``` If a provider requires another provider, you must specify the dependency cycle as follows: -```rust,ignore +```rust +use std::any::TypeId; + +#[derive(Debug, Clone, Default)] +pub struct HomeRepository {} + +pub struct HomeService { + home_repository: HomeRepository, +} + +impl HomeService { + pub fn hello(&self) -> String { + "hello!!".to_string() + } +} + impl rupring::IProvider for HomeService { fn dependencies(&self) -> Vec { vec![TypeId::of::()] @@ -277,14 +348,16 @@ impl rupring::IProvider for HomeService { fn provide(&self, di_context: &rupring::DIContext) -> Box { Box::new(HomeService { - home_repository: di_context.get::().unwrap().to_owned(), + home_repository: di_context.get::().map(|e|e.to_owned()).unwrap(), }) } } ``` If you need mutables within the provider, you must ensure thread safety through Mutex or Atomic as follows: -```rust,ignore +```rust +use std::sync::{Arc, Mutex}; + #[derive(Debug, Clone, Default)] pub struct CounterService { counter: Arc>, @@ -311,7 +384,9 @@ impl CounterService { If you need to abstract based on a trait, you need to box it twice as follows: -```rust,ignore +```rust +use std::any::TypeId; + pub trait IUserService { fn get_user(&self) -> String; } @@ -348,43 +423,73 @@ pub fn get_user(request: rupring::Request) -> rupring::Response { Additionally, shortcuts are provided for defining DI components. For example, the code below automatically creates an IProvider object "inject_counter_service" that can be passed to modules. -```rust,ignore +```rust +#[derive(Debug, Clone, Default)] +pub struct SomethingRepository {} + +#[derive(Debug, Clone, Default)] +pub struct CounterService { + something: SomethingRepository, +} + +impl CounterService { + pub fn new(something: SomethingRepository) -> Self { + CounterService { something } + } +} + #[rupring::Injectable] fn inject_counter_service(something: SomethingRepository) -> CounterService { CounterService::new(something) } -... + #[derive(Debug, Clone, Copy)] #[rupring::Module( - controllers=[HomeController{}], - modules=[UserModule{}], + controllers=[/*...*/], + modules=[/*...*/], providers=[inject_counter_service{}], middlewares=[] )] +pub struct RootModule {} ``` It automatically receives DI based on parameters. The injectable annotation can also be explicitly named. -```rust,ignore +```rust +#[derive(Debug, Clone, Default)] +pub struct SomethingRepository {} + +#[derive(Debug, Clone, Default)] +pub struct CounterService { + something: SomethingRepository, +} + +impl CounterService { + pub fn new(something: SomethingRepository) -> Self { + CounterService { something } + } +} + #[rupring::Injectable(CounterServiceFactory)] // or #[rupring::Injectable(name=CounterServiceFactory)] fn inject_counter_service(something: SomethingRepository) -> CounterService { CounterService::new(something) } -... + #[derive(Debug, Clone, Copy)] #[rupring::Module( - controllers=[HomeController{}], - modules=[UserModule{}], + controllers=[/*...*/], + modules=[/*...*/], providers=[CounterServiceFactory{}], middlewares=[] )] +pub struct RootModule {} ``` # Swagger When rupring starts the server, it automatically serves swagger documents to the `/docs` path. Additional annotations such as `summary`, `description`, and `tags` are provided for swagger documentation. -```rust,ignore +```rust #[rupring::Get(path = /echo/:id)] #[summary = "echo API"] #[description = "It's echo API"] @@ -392,11 +497,17 @@ Additional annotations such as `summary`, `description`, and `tags` are provided pub fn echo( #[path="id"] #[description="just integer id"] id: Option ) -> rupring::Response { - ... + //... + + rupring::Response::new().text("OK".to_string()) +} ``` Using the RupringDoc derive macro, you can perform document definition for Request Parameter. -```rust,ignore +```rust +use rupring::RupringDoc; +use serde::{Deserialize, Serialize}; + #[derive(Debug, Serialize, Deserialize, RupringDoc)] pub struct CreateUserRequest { #[desc = "user name"] @@ -420,32 +531,75 @@ pub struct CreateUserRequest { 7. `#[ignore]`: If you want to ignore the field, you can add this annotation. Then, you can specify request information in the API through the params attribute as follows. -```rust,ignore +```rust +use rupring::RupringDoc; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize, RupringDoc)] +pub struct CreateUserRequest { + #[desc = "user name"] + #[example = "foobar"] + pub username: String, + + pub email: String, + + #[desc = "user password"] + #[example = "q1w2e3r4"] + pub password: String, +} + #[rupring::Post(path = /users)] #[tags = [user]] #[summary = "user create"] -#[params = crate::domains::users::dto::CreateUserRequest] +#[params = CreateUserRequest] pub fn create_user(request: rupring::Request, _: rupring::Response) -> rupring::Response { -... + // ... + + rupring::Response::new().text("OK".to_string()) +} ``` Response documentation can also be defined through the RupringDoc macro and response attribute. -```rust,ignore +```rust +use rupring::RupringDoc; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize, RupringDoc)] +pub struct GetUserResponse { + pub id: i32, + pub username: String, + pub email: String, +} + #[rupring::Get(path = /users/:id)] #[tags = [user]] #[summary = "find user"] -#[response = crate::domains::users::dto::GetUserResponse] -pub fn get_user( +#[response = GetUserResponse] +pub fn get_user(request: rupring::Request, _: rupring::Response) -> rupring::Response { + return rupring::Response::new().text("OK".to_string()); +} ``` If you want to activate BearerAuth for the API, activate the auth attribute as follows. (The default is BearerAuth. -```rust,ignore +```rust +use rupring::RupringDoc; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize, RupringDoc)] +pub struct GetUserResponse { + pub id: i32, + pub username: String, + pub email: String, +} + #[rupring::Get(path = /users/:id)] #[tags = [user]] #[summary = "find user"] -#[response = crate::domains::users::dto::GetUserResponse] +#[response = GetUserResponse] #[auth = BearerAuth] -pub fn get_user( +pub fn get_user(request: rupring::Request, _: rupring::Response) -> rupring::Response { + return rupring::Response::new().text("OK".to_string()); +} ``` */ @@ -456,48 +610,82 @@ pub mod header; mod logger; /// MEME type constants pub mod meme; +/// HTTP request module pub mod request; +/// HTTP response module pub mod response; /// swagger module pub mod swagger; use std::panic::UnwindSafe; -/// Controller Annotation -/// ```rust,ignore -/// #[derive(Debug, Clone)] -/// #[rupring::Controller(prefix=/, routes=[hello, echo])] -/// pub struct HomeController {} -/// ``` +/** Controller Annotation +```rust +#[rupring::Get(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} + +#[rupring::Get(path = /echo)] +pub fn echo(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text(request.body) +} + +#[derive(Debug, Clone)] +#[rupring::Controller(prefix=/, routes=[hello, echo])] +pub struct HomeController {} +``` +*/ pub use rupring_macro::Controller; -/// Module Annotation -/// ```rust,ignore -/// #[derive(Debug, Clone, Copy)] -/// #[rupring::Module( -/// controllers=[HomeController{}], -/// modules=[], -/// providers=[HomeService::default(), HomeRepository::default(), UserService::default(), CounterService::default()] -/// )] -/// pub struct RootModule {} +/** Module Annotation +```rust +#[derive(Debug, Clone)] +#[rupring::Module( + controllers=[/*HomeController{}*/], + modules=[], + providers=[/*HomeService::default(), HomeRepository::default(), UserService::default(), CounterService::default()*/] +)] +pub struct RootModule {} +``` + */ pub use rupring_macro::Module; -/// This is a shortcut annotation for creating an IProvider object. -/// ```rust,ignore -/// #[rupring_macro::Injectable(CounterServiceFactory)] -/// fn inject_counter_service() -> CounterService { -/// CounterService::new() -/// } -/// ... -/// #[derive(Debug, Clone, Copy)] -/// #[rupring::Module( -/// controllers=[HomeController{}], -/// modules=[UserModule{}], -/// providers=[CounterServiceFactory{}], -/// middlewares=[] -/// )] -/// pub struct RootModule {} -/// ``` +/** This is a shortcut annotation for creating an IProvider object. + +```rust +use std::sync::{Arc, Mutex}; + +#[derive(Debug, Clone, Default)] +pub struct CounterService { + counter: Arc>, +} + +impl CounterService { + pub fn new() -> Self { + CounterService { + counter: Arc::new(Mutex::new(0)), + } + } +} + +#[rupring_macro::Injectable(CounterServiceFactory)] +fn inject_counter_service() -> CounterService { + CounterService::new() +} + +#[derive(Debug, Clone, Copy)] +#[rupring::Module( + controllers=[/*...*/], + modules=[/*...*/], + providers=[CounterServiceFactory{}], + middlewares=[] +)] +pub struct RootModule {} +``` +*/ pub use rupring_macro::Injectable; /// This is an alias for [Injectable]. @@ -512,63 +700,75 @@ pub use rupring_macro::Service; /// This is an alias for [Injectable]. pub use rupring_macro::Repository; -/// Get Route Annotation -/// ```rust,ignore -/// #[rupring::Get(path = /)] -/// pub fn hello(request: rupring::Request) -> rupring::Response { -/// // ... -/// } +/** Get Route Annotation +```rust +#[rupring::Get(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} +*/ pub use rupring_macro::Get; /// This is an alias for [Get]. pub use rupring_macro::GetMapping; -/// Post Route Annotation -/// ```rust,ignore -/// #[rupring::Post(path = /)] -/// pub fn hello(request: rupring::Request) -> rupring::Response { -/// // ... -/// } +/** Post Route Annotation +```rust +#[rupring::Post(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} +``` +*/ pub use rupring_macro::Post; /// This is an alias for [Post]. pub use rupring_macro::PostMapping; -/// Patch Route Annotation -/// ```rust,ignore -/// #[rupring::Patch(path = /)] -/// pub fn hello(request: rupring::Request) -> rupring::Response { -/// // ... -/// } +/** Patch Route Annotation +```rust +#[rupring::Patch(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} +``` +*/ pub use rupring_macro::Patch; /// This is an alias for [Patch]. pub use rupring_macro::PatchMapping; -/// Put Route Annotation -/// ```rust,ignore -/// #[rupring::Put(path = /)] -/// pub fn hello(request: rupring::Request) -> rupring::Response { -/// // ... -/// } +/** Put Route Annotation +```rust +#[rupring::Put(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} +``` +*/ pub use rupring_macro::Put; /// This is an alias for [Put]. pub use rupring_macro::PutMapping; -/// Delete Route Annotation -/// ```rust,ignore -/// #[rupring::Delete(path = /)] -/// pub fn hello(request: rupring::Request) -> rupring::Response { -/// // ... -/// } +/** Delete Route Annotation +```rust +#[rupring::Delete(path = /)] +pub fn hello(request: rupring::Request) -> rupring::Response { + // ... + rupring::Response::new().text("Hello, World!".to_string()) +} +``` +*/ pub use rupring_macro::Delete; /// This is an alias for [Delete]. pub use rupring_macro::DeleteMapping; -extern crate rupring_macro; - /// HTTP method (from hyper crate) pub type Method = hyper::Method; @@ -673,5 +873,11 @@ pub use rupring_macro::RupringDoc; mod test_proc_macro; pub use anyhow; -pub use serde; +pub use anyhow::anyhow as error; +pub use anyhow::Result; + +//pub use serde; +//pub use serde::{Deserialize, Serialize}; pub use serde_json; + +pub use tokio; diff --git a/rupring_example/Cargo.toml b/rupring_example/Cargo.toml new file mode 100644 index 0000000..839b81f --- /dev/null +++ b/rupring_example/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "rupring_example" +version = "0.1.0" +edition = "2021" + +[dependencies] +rupring={ version="0.8.1", path="../rupring" } +tokio = { version = "1", features = ["full"] } +serde = { version="1.0.193", features=["derive"] } \ No newline at end of file diff --git a/rupring/src/example/domains/mod.rs b/rupring_example/src/domains/mod.rs similarity index 100% rename from rupring/src/example/domains/mod.rs rename to rupring_example/src/domains/mod.rs diff --git a/rupring/src/example/domains/root/controller.rs b/rupring_example/src/domains/root/controller.rs similarity index 100% rename from rupring/src/example/domains/root/controller.rs rename to rupring_example/src/domains/root/controller.rs diff --git a/rupring/src/example/domains/root/mod.rs b/rupring_example/src/domains/root/mod.rs similarity index 100% rename from rupring/src/example/domains/root/mod.rs rename to rupring_example/src/domains/root/mod.rs diff --git a/rupring/src/example/domains/root/module.rs b/rupring_example/src/domains/root/module.rs similarity index 100% rename from rupring/src/example/domains/root/module.rs rename to rupring_example/src/domains/root/module.rs diff --git a/rupring/src/example/domains/users/controller.rs b/rupring_example/src/domains/users/controller.rs similarity index 98% rename from rupring/src/example/domains/users/controller.rs rename to rupring_example/src/domains/users/controller.rs index fabae04..5ec56c7 100644 --- a/rupring/src/example/domains/users/controller.rs +++ b/rupring_example/src/domains/users/controller.rs @@ -76,7 +76,7 @@ pub fn update_user( ) -> rupring::Response { let user_service = request.get_provider::>().unwrap(); - let request = serde_json::from_str(&request.body); + let request = rupring::serde_json::from_str(&request.body); let request: UpdateUserRequest = match request { Ok(request) => request, diff --git a/rupring/src/example/domains/users/dto.rs b/rupring_example/src/domains/users/dto.rs similarity index 96% rename from rupring/src/example/domains/users/dto.rs rename to rupring_example/src/domains/users/dto.rs index 6d79324..f29ece1 100644 --- a/rupring/src/example/domains/users/dto.rs +++ b/rupring_example/src/domains/users/dto.rs @@ -1,9 +1,8 @@ -use rupring_macro::RupringDoc; +use rupring::RupringDoc; use serde::{Deserialize, Serialize}; pub mod foo { - - use rupring_macro::RupringDoc; + use rupring::RupringDoc; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, RupringDoc)] pub struct Bar { diff --git a/rupring_example/src/domains/users/interface.rs b/rupring_example/src/domains/users/interface.rs new file mode 100644 index 0000000..6fc86c0 --- /dev/null +++ b/rupring_example/src/domains/users/interface.rs @@ -0,0 +1,28 @@ +use super::{ + dto::{ + CreateUserRequest, CreateUserResponse, DeleteUserRequest, DeleteUserResponse, + GetUserRequest, GetUserResponse, ListUsersRequest, ListUsersResponse, UpdateUserRequest, + UpdateUserResponse, + }, + model::{ + CountUsersParams, CreateUserParams, DeleteUserParams, GetUserParams, ListUsersParams, + UpdateUserParams, User, Users, + }, +}; + +pub trait IUserService { + fn create_user(&self, request: CreateUserRequest) -> rupring::Result; + fn update_user(&self, request: UpdateUserRequest) -> rupring::Result; + fn delete_user(&self, request: DeleteUserRequest) -> rupring::Result; + fn get_user(&self, request: GetUserRequest) -> rupring::Result; + fn list_users(&self, request: ListUsersRequest) -> rupring::Result; +} + +pub trait IUserRepository { + fn create_user(&self, params: CreateUserParams) -> rupring::Result; + fn update_user(&self, params: UpdateUserParams) -> rupring::Result<()>; + fn delete_user(&self, params: DeleteUserParams) -> rupring::Result<()>; + fn get_user(&self, params: GetUserParams) -> rupring::Result>; + fn list_users(&self, params: ListUsersParams) -> rupring::Result; + fn count_users(&self, params: CountUsersParams) -> rupring::Result; +} diff --git a/rupring/src/example/domains/users/mod.rs b/rupring_example/src/domains/users/mod.rs similarity index 100% rename from rupring/src/example/domains/users/mod.rs rename to rupring_example/src/domains/users/mod.rs diff --git a/rupring/src/example/domains/users/model.rs b/rupring_example/src/domains/users/model.rs similarity index 100% rename from rupring/src/example/domains/users/model.rs rename to rupring_example/src/domains/users/model.rs diff --git a/rupring/src/example/domains/users/module.rs b/rupring_example/src/domains/users/module.rs similarity index 100% rename from rupring/src/example/domains/users/module.rs rename to rupring_example/src/domains/users/module.rs diff --git a/rupring/src/example/domains/users/repository.rs b/rupring_example/src/domains/users/repository.rs similarity index 94% rename from rupring/src/example/domains/users/repository.rs rename to rupring_example/src/domains/users/repository.rs index 51baf01..198c007 100644 --- a/rupring/src/example/domains/users/repository.rs +++ b/rupring_example/src/domains/users/repository.rs @@ -15,7 +15,7 @@ impl UserInMemoryRepository { } impl IUserRepository for UserInMemoryRepository { - fn create_user(&self, params: super::model::CreateUserParams) -> anyhow::Result { + fn create_user(&self, params: super::model::CreateUserParams) -> rupring::Result { if self.users.is_poisoned() { self.users.clear_poison(); } @@ -36,7 +36,7 @@ impl IUserRepository for UserInMemoryRepository { Ok(id) } - fn update_user(&self, params: super::model::UpdateUserParams) -> anyhow::Result<()> { + fn update_user(&self, params: super::model::UpdateUserParams) -> rupring::Result<()> { if self.users.is_poisoned() { self.users.clear_poison(); } @@ -53,7 +53,7 @@ impl IUserRepository for UserInMemoryRepository { Ok(()) } - fn delete_user(&self, params: super::model::DeleteUserParams) -> anyhow::Result<()> { + fn delete_user(&self, params: super::model::DeleteUserParams) -> rupring::Result<()> { if self.users.is_poisoned() { self.users.clear_poison(); } @@ -73,7 +73,7 @@ impl IUserRepository for UserInMemoryRepository { fn get_user( &self, request: super::model::GetUserParams, - ) -> anyhow::Result> { + ) -> rupring::Result> { if self.users.is_poisoned() { self.users.clear_poison(); } @@ -85,7 +85,7 @@ impl IUserRepository for UserInMemoryRepository { Ok(user.cloned()) } - fn list_users(&self, params: super::model::ListUsersParams) -> anyhow::Result { + fn list_users(&self, params: super::model::ListUsersParams) -> rupring::Result { if self.users.is_poisoned() { self.users.clear_poison(); } @@ -110,7 +110,7 @@ impl IUserRepository for UserInMemoryRepository { Ok(users[start..end].to_vec()) } - fn count_users(&self, _: super::model::CountUsersParams) -> anyhow::Result { + fn count_users(&self, _: super::model::CountUsersParams) -> rupring::Result { if self.users.is_poisoned() { self.users.clear_poison(); } diff --git a/rupring/src/example/domains/users/service.rs b/rupring_example/src/domains/users/service.rs similarity index 82% rename from rupring/src/example/domains/users/service.rs rename to rupring_example/src/domains/users/service.rs index 1f2cd4f..5e9f3d0 100644 --- a/rupring/src/example/domains/users/service.rs +++ b/rupring_example/src/domains/users/service.rs @@ -21,7 +21,7 @@ impl UserService { } impl IUserService for UserService { - fn create_user(&self, request: CreateUserRequest) -> anyhow::Result { + fn create_user(&self, request: CreateUserRequest) -> rupring::Result { let _ = self.repository.create_user(CreateUserParams { name: request.username, email: request.email, @@ -31,7 +31,7 @@ impl IUserService for UserService { Ok(CreateUserResponse {}) } - fn update_user(&self, request: UpdateUserRequest) -> anyhow::Result { + fn update_user(&self, request: UpdateUserRequest) -> rupring::Result { let _ = self .repository .update_user(super::model::UpdateUserParams { @@ -44,14 +44,14 @@ impl IUserService for UserService { Ok(UpdateUserResponse {}) } - fn delete_user(&self, request: DeleteUserRequest) -> anyhow::Result { + fn delete_user(&self, request: DeleteUserRequest) -> rupring::Result { self.repository .delete_user(super::model::DeleteUserParams { id: request.id })?; Ok(DeleteUserResponse {}) } - fn get_user(&self, request: GetUserRequest) -> anyhow::Result { + fn get_user(&self, request: GetUserRequest) -> rupring::Result { let user = self.repository.get_user(GetUserParams { id: request.id })?; if let Some(user) = user { @@ -62,10 +62,10 @@ impl IUserService for UserService { }); } - Err(anyhow::anyhow!("user not found")) + Err(rupring::error!("user not found")) } - fn list_users(&self, request: ListUsersRequest) -> anyhow::Result { + fn list_users(&self, request: ListUsersRequest) -> rupring::Result { let count = self .repository .count_users(super::model::CountUsersParams {})?; diff --git a/rupring/src/example/main.rs b/rupring_example/src/main.rs similarity index 91% rename from rupring/src/example/main.rs rename to rupring_example/src/main.rs index 5a795a1..d79bfc1 100644 --- a/rupring/src/example/main.rs +++ b/rupring_example/src/main.rs @@ -3,7 +3,7 @@ use domains::root::module::RootModule; pub(crate) mod domains; pub(crate) mod middlewares; -#[tokio::main] +#[rupring::tokio::main] async fn main() -> Result<(), Box> { let app = rupring::RupringFactory::create(RootModule {}); diff --git a/rupring/src/example/middlewares/logger.rs b/rupring_example/src/middlewares/logger.rs similarity index 100% rename from rupring/src/example/middlewares/logger.rs rename to rupring_example/src/middlewares/logger.rs diff --git a/rupring/src/example/middlewares/mod.rs b/rupring_example/src/middlewares/mod.rs similarity index 100% rename from rupring/src/example/middlewares/mod.rs rename to rupring_example/src/middlewares/mod.rs diff --git a/rupring_macro/Cargo.toml b/rupring_macro/Cargo.toml index 29a1566..77a6732 100644 --- a/rupring_macro/Cargo.toml +++ b/rupring_macro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rupring_macro" -version = "0.8.0" +version = "0.8.2" edition = "2021" description = "rupring macro" license = "MIT" diff --git a/rupring_macro/src/lib.rs b/rupring_macro/src/lib.rs index 880e3d8..006d3e2 100644 --- a/rupring_macro/src/lib.rs +++ b/rupring_macro/src/lib.rs @@ -635,7 +635,7 @@ pub fn derive_rupring_doc(item: TokenStream) -> TokenStream { let mut define_struct_for_json = "".to_string(); define_struct_for_json += - format!(r#"#[derive(rupring::serde::Serialize, rupring::serde::Deserialize)]"#).as_str(); + format!(r#"#[derive(serde::Serialize, serde::Deserialize)]"#).as_str(); define_struct_for_json += format!(r#"pub struct {struct_name}__JSON {{"#).as_str(); let mut json_field_names = vec![];