├── .dockerignore ├── .env.template ├── .github ├── release-drafter.yml └── workflows │ ├── ci.yml │ ├── deploy.yml │ └── release-drafter.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── README.md ├── build.rs ├── docker-compose-test.yml ├── docker-compose.yml ├── migrations └── 20220306122339_create_tables.sql ├── rendercom └── Dockerfile ├── rust-toolchain.toml ├── src ├── bin │ └── gen_schema.rs ├── common.rs ├── common │ └── types.rs ├── dependency_injection.rs ├── domain.rs ├── domain │ ├── entity.rs │ ├── entity │ │ ├── author.rs │ │ ├── book.rs │ │ ├── common.rs │ │ └── user.rs │ ├── error.rs │ ├── repository.rs │ └── repository │ │ ├── author_repository.rs │ │ ├── book_repository.rs │ │ └── user_repository.rs ├── infrastructure.rs ├── infrastructure │ ├── author_repository.rs │ ├── book_repository.rs │ ├── error.rs │ └── user_repository.rs ├── lib.rs ├── main.rs ├── presentation.rs ├── presentation │ ├── app_state.rs │ ├── error.rs │ ├── extractor.rs │ ├── extractor │ │ └── claims.rs │ ├── graphql.rs │ ├── graphql │ │ ├── loader.rs │ │ ├── mutation.rs │ │ ├── object.rs │ │ ├── query.rs │ │ └── schema.rs │ ├── handler.rs │ └── handler │ │ └── graphql.rs ├── types.rs ├── use_case.rs └── use_case │ ├── dto.rs │ ├── dto │ ├── author.rs │ ├── book.rs │ └── user.rs │ ├── error.rs │ ├── interactor.rs │ ├── interactor │ ├── author.rs │ ├── book.rs │ ├── mutation.rs │ ├── query.rs │ └── user.rs │ ├── traits.rs │ └── traits │ ├── author.rs │ ├── book.rs │ ├── mutation.rs │ ├── query.rs │ └── user.rs └── testdata └── testdata.sql /.dockerignore: -------------------------------------------------------------------------------- 1 | /target 2 | .env.* 3 | -------------------------------------------------------------------------------- /.env.template: -------------------------------------------------------------------------------- 1 | DATABASE_URL=postgres://postgres:password@localhost:5432/postgres 2 | AUTH0_AUDIENCE= 3 | AUTH0_DOMAIN= 4 | PORT=8080 5 | RUST_LOG=debug 6 | ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001,http://localhost:8080 7 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: '$RESOLVED_VERSION' 2 | tag-template: '$RESOLVED_VERSION' 3 | categories: 4 | - title: 'Features' 5 | labels: 6 | - 'feature' 7 | - 'enhancement' 8 | - title: 'Bug Fixes' 9 | labels: 10 | - 'fix' 11 | - 'bugfix' 12 | - 'bug' 13 | - title: 'Maintenance' 14 | label: 'chore' 15 | version-resolver: 16 | major: 17 | labels: 18 | - 'major' 19 | minor: 20 | labels: 21 | - 'minor' 22 | patch: 23 | labels: 24 | - 'patch' 25 | default: patch 26 | template: | 27 | $CHANGES 28 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Continuous integration 2 | 3 | on: [push] 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: dtolnay/rust-toolchain@1.83.0 12 | - uses: Swatinem/rust-cache@v2 13 | - run: cargo check 14 | 15 | test: 16 | name: Test Suite 17 | runs-on: ubuntu-latest 18 | env: 19 | DATABASE_URL: postgres://bookshelf:password@localhost:5432/bookshelf 20 | steps: 21 | - uses: actions/checkout@v4 22 | - uses: dtolnay/rust-toolchain@1.83.0 23 | - uses: Swatinem/rust-cache@v2 24 | - run: sudo systemctl start postgresql.service 25 | - run: pg_isready 26 | - run: sudo -u postgres psql --command="CREATE USER bookshelf WITH SUPERUSER PASSWORD 'password'" --command="\du" postgres 27 | - run: sudo -u postgres createdb --owner=bookshelf bookshelf 28 | - run: cargo test --all-features 29 | 30 | test-image-building: 31 | name: Test Image Building 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: docker/setup-buildx-action@v3 36 | - name: Cache 37 | uses: actions/cache@v3 38 | id: cache 39 | with: 40 | path: | 41 | usr-local-cargo-registry 42 | app-target 43 | key: cache-${{ hashFiles('Dockerfile') }} 44 | - name: inject cache into docker 45 | uses: reproducible-containers/buildkit-cache-dance@v3.1.0 46 | with: 47 | cache-map: | 48 | { 49 | "usr-local-cargo-registry": "/usr/local/cargo/registry", 50 | "app-target": "/app/target" 51 | } 52 | skip-extraction: ${{ steps.cache.outputs.cache-hit }} 53 | - uses: docker/build-push-action@v6 54 | with: 55 | push: false 56 | cache-from: type=gha 57 | cache-to: type=gha,mode=max 58 | 59 | fmt: 60 | name: Rustfmt 61 | runs-on: ubuntu-latest 62 | steps: 63 | - uses: actions/checkout@v4 64 | - uses: dtolnay/rust-toolchain@1.83.0 65 | with: 66 | components: rustfmt 67 | - uses: Swatinem/rust-cache@v2 68 | - run: cargo fmt --all -- --check 69 | 70 | clippy: 71 | name: Clippy 72 | runs-on: ubuntu-latest 73 | steps: 74 | - uses: actions/checkout@v4 75 | - uses: dtolnay/rust-toolchain@1.83.0 76 | with: 77 | components: clippy 78 | - uses: Swatinem/rust-cache@v2 79 | - run: cargo clippy -- -D warnings 80 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to Render 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | env: 8 | REGISTRY: ghcr.io 9 | IMAGE_NAME: ${{ github.repository }} 10 | 11 | jobs: 12 | push_to_registry: 13 | name: Push Docker image 14 | runs-on: ubuntu-latest 15 | permissions: 16 | contents: read 17 | packages: write 18 | 19 | steps: 20 | - name: Check out the repo 21 | uses: actions/checkout@v4 22 | 23 | - name: Set up Docker Buildx 24 | uses: docker/setup-buildx-action@v3 25 | 26 | - name: Cache 27 | uses: actions/cache@v3 28 | id: cache 29 | with: 30 | path: | 31 | usr-local-cargo-registry 32 | app-target 33 | key: cache-${{ hashFiles('Dockerfile') }} 34 | 35 | - name: inject cache into docker 36 | uses: reproducible-containers/buildkit-cache-dance@v3.1.0 37 | with: 38 | cache-map: | 39 | { 40 | "usr-local-cargo-registry": "/usr/local/cargo/registry", 41 | "app-target": "/app/target" 42 | } 43 | skip-extraction: ${{ steps.cache.outputs.cache-hit }} 44 | 45 | - name: Log in to the Container registry 46 | uses: docker/login-action@v3 47 | with: 48 | registry: ${{ env.REGISTRY }} 49 | username: ${{ github.actor }} 50 | password: ${{ secrets.GITHUB_TOKEN }} 51 | 52 | - name: Extract metadata (tags, labels) for Docker 53 | id: meta 54 | uses: docker/metadata-action@v5 55 | with: 56 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 57 | 58 | - name: Build and push Docker image 59 | uses: docker/build-push-action@v6 60 | with: 61 | context: . 62 | push: true 63 | tags: ${{ steps.meta.outputs.tags }} 64 | labels: ${{ steps.meta.outputs.labels }} 65 | cache-from: type=gha 66 | cache-to: type=gha,mode=max 67 | deploy: 68 | name: Deploy 69 | runs-on: ubuntu-latest 70 | needs: push_to_registry 71 | steps: 72 | - env: 73 | RENDER_DEPLOY_HOOK: ${{ secrets.RENDER_DEPLOY_HOOK }} 74 | run: curl "${RENDER_DEPLOY_HOOK}" 75 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: release-drafter/release-drafter@v6 14 | id: release_drafter 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | - uses: taiki-e/install-action@v2 18 | with: 19 | tool: cargo-edit 20 | - name: Update Cargo.toml 21 | run: | 22 | cargo set-version ${{ steps.release_drafter.outputs.tag_name }} 23 | continue-on-error: true 24 | - uses: stefanzweifel/git-auto-commit-action@v5 25 | with: 26 | commit_message: Bump version 27 | 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .env* 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bookshelf-api" 3 | version = "2.1.0" 4 | edition = "2021" 5 | default-run = "bookshelf-api" 6 | 7 | [features] 8 | test-with-database = [] 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | anyhow = { version = "1.0.89", features = ["backtrace"] } 14 | async-graphql = { version = "7.0.11", features = ["dataloader"] } 15 | async-graphql-axum = "7.0.11" 16 | async-trait = "0.1.83" 17 | axum = { version = "0.7.7" } 18 | axum-extra = { version = "0.9.4", features = ["typed-header"] } 19 | axum-macros = "0.4.2" 20 | derive_more = { version = "1.0", features = ["display", "error"] } 21 | dotenv = "0.15.0" 22 | envy = "0.4.2" 23 | futures-util = "0.3.31" 24 | getset = "0.1.3" 25 | http = "1.1.0" 26 | jsonwebtoken = "9.3.0" 27 | log = "0.4.22" 28 | mockall = "0.13.0" 29 | once_cell = "1.20.2" 30 | regex = "1.11.0" 31 | reqwest = { version = "0.12", default-features = false, features = [ 32 | "json", 33 | "rustls-tls", 34 | ] } 35 | serde = { version = "1.0", features = ["derive"] } 36 | serde_json = "1.0.128" 37 | sqlx = { version = "0.8", features = [ 38 | "runtime-tokio", 39 | "tls-rustls-aws-lc-rs", 40 | "postgres", 41 | "time", 42 | "uuid", 43 | ] } 44 | thiserror = "1.0.64" 45 | time = "0.3.36" 46 | time-macros = "0.2.18" 47 | tokio = { version = "1.43.1", features = ["full"] } 48 | tower = "0.5.1" 49 | tower-http = { version = "0.6.1", features = ["cors", "trace"] } 50 | tracing = "0.1.40" 51 | tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } 52 | uuid = { version = "1.10.0", features = ["v4"] } 53 | validator = { version = "0.19.0", features = ["derive"] } 54 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # https://docs.docker.com/language/rust/develop/ 2 | 3 | FROM rust:1.83.0 AS build-stage 4 | 5 | ARG APP_NAME=bookshelf-api 6 | 7 | ARG BUILDDIR=/app 8 | WORKDIR ${BUILDDIR} 9 | 10 | # Build the application. 11 | # Leverage a cache mount to /usr/local/cargo/registry/ 12 | # for downloaded dependencies and a cache mount to /app/target/ for 13 | # compiled dependencies which will speed up subsequent builds. 14 | # Leverage a bind mount to the src directory to avoid having to copy the 15 | # source code into the container. Once built, copy the executable to an 16 | # output directory before the cache mounted /app/target is unmounted. 17 | RUN --mount=type=bind,source=src,target=src \ 18 | --mount=type=bind,source=Cargo.toml,target=Cargo.toml \ 19 | --mount=type=bind,source=Cargo.lock,target=Cargo.lock \ 20 | --mount=type=cache,target=${BUILDDIR}/target/ \ 21 | --mount=type=cache,target=/usr/local/cargo/registry/ \ 22 | --mount=type=bind,source=migrations,target=migrations \ 23 | < for BookFormat { 13 | type Error = ParseBookFormatError; 14 | 15 | fn try_from(value: &str) -> Result { 16 | match value { 17 | "eBook" => Ok(BookFormat::EBook), 18 | "Printed" => Ok(BookFormat::Printed), 19 | "Unknown" => Ok(BookFormat::Unknown), 20 | _ => Err(ParseBookFormatError(format!( 21 | "{} is not valid format", 22 | value 23 | ))), 24 | } 25 | } 26 | } 27 | 28 | #[derive(Debug, Clone, PartialEq, Eq, Display)] 29 | pub enum BookStore { 30 | Kindle, 31 | Unknown, 32 | } 33 | 34 | impl TryFrom<&str> for BookStore { 35 | type Error = ParseBookStoreError; 36 | 37 | fn try_from(value: &str) -> Result { 38 | match value { 39 | "Kindle" => Ok(BookStore::Kindle), 40 | "Unknown" => Ok(BookStore::Unknown), 41 | _ => Err(ParseBookStoreError(format!("{} is not valid store", value))), 42 | } 43 | } 44 | } 45 | 46 | #[derive(Debug, Error)] 47 | #[error("{0}")] 48 | pub struct ParseBookFormatError(String); 49 | 50 | #[derive(Debug, Error)] 51 | #[error("{0}")] 52 | pub struct ParseBookStoreError(String); 53 | 54 | #[cfg(test)] 55 | mod test { 56 | use crate::common::types::{BookFormat, BookStore}; 57 | 58 | #[test] 59 | fn book_format_ebook_to_string() { 60 | assert_eq!(BookFormat::EBook.to_string(), "eBook"); 61 | } 62 | 63 | #[test] 64 | fn book_format_printed_to_string() { 65 | assert_eq!(BookFormat::Printed.to_string(), "Printed"); 66 | } 67 | 68 | #[test] 69 | fn book_format_unknown_to_string() { 70 | assert_eq!(BookFormat::Unknown.to_string(), "Unknown"); 71 | } 72 | 73 | #[test] 74 | fn book_store_kindle_to_string() { 75 | assert_eq!(BookStore::Kindle.to_string(), "Kindle"); 76 | } 77 | 78 | #[test] 79 | fn book_store_unknown_to_string() { 80 | assert_eq!(BookStore::Unknown.to_string(), "Unknown"); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/dependency_injection.rs: -------------------------------------------------------------------------------- 1 | use async_graphql::{EmptySubscription, Schema}; 2 | use sqlx::{Pool, Postgres}; 3 | 4 | use crate::{ 5 | infrastructure::{ 6 | author_repository::PgAuthorRepository, book_repository::PgBookRepository, 7 | user_repository::PgUserRepository, 8 | }, 9 | presentation::graphql::{mutation::Mutation, query::Query, schema::build_schema}, 10 | use_case::interactor::{ 11 | author::CreateAuthorInteractor, 12 | book::{CreateBookInteractor, DeleteBookInteractor, UpdateBookInteractor}, 13 | mutation::MutationInteractor, 14 | query::QueryInteractor, 15 | user::RegisterUserInteractor, 16 | }, 17 | }; 18 | 19 | pub type QI = QueryInteractor; 20 | pub type MI = MutationInteractor< 21 | RegisterUserInteractor, 22 | CreateBookInteractor, 23 | UpdateBookInteractor, 24 | DeleteBookInteractor, 25 | CreateAuthorInteractor, 26 | >; 27 | 28 | pub fn dependency_injection( 29 | pool: Pool, 30 | ) -> (QI, Schema, Mutation, EmptySubscription>) { 31 | let user_repository = PgUserRepository::new(pool.clone()); 32 | let book_repository = PgBookRepository::new(pool.clone()); 33 | let author_repository = PgAuthorRepository::new(pool); 34 | 35 | let query_use_case = QueryInteractor { 36 | user_repository: user_repository.clone(), 37 | book_repository: book_repository.clone(), 38 | author_repository: author_repository.clone(), 39 | }; 40 | let register_user_use_case = RegisterUserInteractor::new(user_repository); 41 | let create_book_use_case = CreateBookInteractor::new(book_repository.clone()); 42 | let update_book_use_case = UpdateBookInteractor::new(book_repository.clone()); 43 | let delete_book_use_case = DeleteBookInteractor::new(book_repository); 44 | let create_author_use_case = CreateAuthorInteractor::new(author_repository); 45 | let mutation_use_case = MutationInteractor::new( 46 | register_user_use_case, 47 | create_book_use_case, 48 | update_book_use_case, 49 | delete_book_use_case, 50 | create_author_use_case, 51 | ); 52 | 53 | let query = Query::new(query_use_case.clone()); 54 | let mutation = Mutation::new(mutation_use_case); 55 | 56 | let schema = build_schema(query, mutation); 57 | 58 | (query_use_case, schema) 59 | } 60 | -------------------------------------------------------------------------------- /src/domain.rs: -------------------------------------------------------------------------------- 1 | pub mod entity; 2 | pub mod error; 3 | pub mod repository; 4 | -------------------------------------------------------------------------------- /src/domain/entity.rs: -------------------------------------------------------------------------------- 1 | pub mod author; 2 | pub mod book; 3 | pub mod common; 4 | pub mod user; 5 | -------------------------------------------------------------------------------- /src/domain/entity/author.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use getset::Getters; 4 | use uuid::Uuid; 5 | use validator::Validate; 6 | 7 | use crate::{domain::error::DomainError, impl_string_value_object}; 8 | 9 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] 10 | pub struct AuthorId { 11 | id: Uuid, 12 | } 13 | 14 | impl AuthorId { 15 | pub fn new(id: Uuid) -> Self { 16 | Self { id } 17 | } 18 | 19 | pub fn to_uuid(&self) -> Uuid { 20 | self.id 21 | } 22 | } 23 | 24 | impl Display for AuthorId { 25 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 26 | write!(f, "{}", self.id.hyphenated()) 27 | } 28 | } 29 | 30 | impl TryFrom<&str> for AuthorId { 31 | type Error = DomainError; 32 | 33 | fn try_from(value: &str) -> Result { 34 | let id = Uuid::parse_str(value).map_err(|err| { 35 | DomainError::Validation(format!( 36 | r#"Failed to parse id "{}" as uuid. Message from uuid crate: {}"#, 37 | value, err 38 | )) 39 | })?; 40 | Ok(AuthorId { id }) 41 | } 42 | } 43 | 44 | impl From for AuthorId { 45 | fn from(uuid: Uuid) -> Self { 46 | AuthorId { id: uuid } 47 | } 48 | } 49 | 50 | #[derive(Debug, Clone, PartialEq, Eq, Validate)] 51 | pub struct AuthorName { 52 | #[validate(length(min = 1))] 53 | value: String, 54 | } 55 | 56 | impl_string_value_object!(AuthorName); 57 | 58 | #[derive(Debug, Clone, PartialEq, Eq, Getters)] 59 | pub struct Author { 60 | #[getset(get = "pub")] 61 | id: AuthorId, 62 | #[getset(get = "pub")] 63 | name: AuthorName, 64 | } 65 | 66 | #[derive(Debug, Clone, PartialEq, Eq)] 67 | pub struct DestructureAuthor { 68 | pub id: AuthorId, 69 | pub name: AuthorName, 70 | } 71 | 72 | impl Author { 73 | pub fn new(id: AuthorId, name: AuthorName) -> Result { 74 | Ok(Author { id, name }) 75 | } 76 | 77 | pub fn destructure(self) -> DestructureAuthor { 78 | DestructureAuthor { 79 | id: self.id, 80 | name: self.name, 81 | } 82 | } 83 | } 84 | 85 | #[cfg(test)] 86 | mod tests { 87 | use crate::domain::{ 88 | entity::author::{AuthorId, AuthorName}, 89 | error::DomainError, 90 | }; 91 | 92 | #[test] 93 | fn author_id_to_string() { 94 | let uuid_str = "c6ea22c8-7b70-470c-a713-c7aade5693bd"; 95 | let author_id = AuthorId::try_from(uuid_str).unwrap(); 96 | assert_eq!(author_id.to_string(), uuid_str); 97 | } 98 | 99 | #[test] 100 | fn validation_success() { 101 | assert!(matches!(AuthorName::new(String::from("author1")), Ok(_))); 102 | } 103 | 104 | #[test] 105 | fn validation_failure() { 106 | assert!(matches!( 107 | AuthorName::new(String::from("")), 108 | Err(DomainError::Validation(_)) 109 | )); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/domain/entity/book.rs: -------------------------------------------------------------------------------- 1 | use getset::{Getters, Setters}; 2 | use once_cell::sync::Lazy; 3 | use regex::Regex; 4 | use time::OffsetDateTime; 5 | use uuid::Uuid; 6 | use validator::Validate; 7 | 8 | use crate::{ 9 | common::types::{BookFormat, BookStore}, 10 | domain::error::DomainError, 11 | impl_string_value_object, 12 | }; 13 | 14 | use super::author::AuthorId; 15 | 16 | #[derive(Debug, Clone, PartialEq, Eq)] 17 | pub struct BookId { 18 | id: Uuid, 19 | } 20 | 21 | impl BookId { 22 | pub fn new(id: Uuid) -> Result { 23 | Ok(BookId { id }) 24 | } 25 | 26 | pub fn to_uuid(&self) -> Uuid { 27 | self.id 28 | } 29 | } 30 | 31 | impl std::fmt::Display for BookId { 32 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 33 | write!(f, "{}", self.id.hyphenated()) 34 | } 35 | } 36 | 37 | impl TryFrom<&str> for BookId { 38 | type Error = DomainError; 39 | 40 | fn try_from(value: &str) -> Result { 41 | let id = Uuid::parse_str(value).map_err(|err| { 42 | DomainError::Validation(format!( 43 | r#"Failed to parse id "{}" as uuid. Message from uuid crate: {}"#, 44 | value, err 45 | )) 46 | })?; 47 | Ok(BookId { id }) 48 | } 49 | } 50 | 51 | #[derive(Debug, Clone, PartialEq, Eq, Validate)] 52 | pub struct BookTitle { 53 | #[validate(length(min = 1))] 54 | value: String, 55 | } 56 | 57 | impl_string_value_object!(BookTitle); 58 | 59 | static ISBN_REGEX: Lazy = Lazy::new(|| Regex::new(r"(^$|^(\d-?){12}\d$)").unwrap()); 60 | 61 | #[derive(Debug, Clone, PartialEq, Eq, Validate)] 62 | pub struct Isbn { 63 | // TODO: Validate check digit 64 | #[validate(regex(path = *ISBN_REGEX))] 65 | value: String, 66 | } 67 | 68 | impl_string_value_object!(Isbn); 69 | 70 | #[derive(Debug, Clone, PartialEq, Eq)] 71 | pub struct ReadFlag { 72 | value: bool, 73 | } 74 | 75 | impl ReadFlag { 76 | pub fn new(value: bool) -> ReadFlag { 77 | ReadFlag { value } 78 | } 79 | 80 | pub fn to_bool(&self) -> bool { 81 | self.value 82 | } 83 | } 84 | 85 | #[derive(Debug, Clone, PartialEq, Eq)] 86 | pub struct OwnedFlag { 87 | value: bool, 88 | } 89 | 90 | impl OwnedFlag { 91 | pub fn new(value: bool) -> OwnedFlag { 92 | OwnedFlag { value } 93 | } 94 | 95 | pub fn to_bool(&self) -> bool { 96 | self.value 97 | } 98 | } 99 | 100 | #[derive(Debug, Clone, PartialEq, Eq, Validate)] 101 | pub struct Priority { 102 | #[validate(range(min = 0, max = 100))] 103 | value: i32, 104 | } 105 | 106 | impl Priority { 107 | pub fn new(value: i32) -> Result { 108 | let priority = Self { value }; 109 | priority.validate()?; 110 | Ok(priority) 111 | } 112 | 113 | pub fn to_i32(&self) -> i32 { 114 | self.value 115 | } 116 | } 117 | 118 | #[derive(Debug, Clone, PartialEq, Eq, Getters, Setters)] 119 | pub struct Book { 120 | #[getset(get = "pub")] 121 | id: BookId, 122 | #[getset(get = "pub", set = "pub")] 123 | title: BookTitle, 124 | #[getset(get = "pub", set = "pub")] 125 | author_ids: Vec, 126 | #[getset(get = "pub", set = "pub")] 127 | isbn: Isbn, 128 | #[getset(get = "pub", set = "pub")] 129 | read: ReadFlag, 130 | #[getset(get = "pub", set = "pub")] 131 | owned: OwnedFlag, 132 | #[getset(get = "pub", set = "pub")] 133 | priority: Priority, 134 | #[getset(get = "pub", set = "pub")] 135 | format: BookFormat, 136 | #[getset(get = "pub", set = "pub")] 137 | store: BookStore, 138 | #[getset(get = "pub", set = "pub")] 139 | created_at: OffsetDateTime, 140 | #[getset(get = "pub", set = "pub")] 141 | updated_at: OffsetDateTime, 142 | } 143 | 144 | #[derive(Debug, Clone, PartialEq, Eq)] 145 | pub struct DestructureBook { 146 | pub id: BookId, 147 | pub title: BookTitle, 148 | pub author_ids: Vec, 149 | pub isbn: Isbn, 150 | pub read: ReadFlag, 151 | pub owned: OwnedFlag, 152 | pub priority: Priority, 153 | pub format: BookFormat, 154 | pub store: BookStore, 155 | pub created_at: OffsetDateTime, 156 | pub updated_at: OffsetDateTime, 157 | } 158 | 159 | impl Book { 160 | #[allow(clippy::too_many_arguments)] 161 | pub fn new( 162 | id: BookId, 163 | title: BookTitle, 164 | author_ids: Vec, 165 | isbn: Isbn, 166 | read: ReadFlag, 167 | owned: OwnedFlag, 168 | priority: Priority, 169 | format: BookFormat, 170 | store: BookStore, 171 | created_at: OffsetDateTime, 172 | updated_at: OffsetDateTime, 173 | ) -> Result { 174 | Ok(Self { 175 | id, 176 | title, 177 | author_ids, 178 | isbn, 179 | read, 180 | owned, 181 | priority, 182 | format, 183 | store, 184 | created_at, 185 | updated_at, 186 | }) 187 | } 188 | 189 | pub fn destructure(self) -> DestructureBook { 190 | DestructureBook { 191 | id: self.id, 192 | title: self.title, 193 | author_ids: self.author_ids, 194 | isbn: self.isbn, 195 | read: self.read, 196 | owned: self.owned, 197 | priority: self.priority, 198 | format: self.format, 199 | store: self.store, 200 | created_at: self.created_at, 201 | updated_at: self.updated_at, 202 | } 203 | } 204 | } 205 | 206 | #[cfg(test)] 207 | mod test { 208 | use super::{Isbn, Priority}; 209 | 210 | #[test] 211 | fn valid_isbn_with_hyphen() { 212 | let isbn = Isbn::new("978-4062758574".to_owned()); 213 | assert!(matches!(isbn, Ok(_))); 214 | } 215 | 216 | #[test] 217 | fn valid_isbn_without_hyphen() { 218 | let isbn = Isbn::new("9784062758574".to_owned()); 219 | assert!(matches!(isbn, Ok(_))); 220 | } 221 | 222 | #[test] 223 | fn empty_isbn_is_valid() { 224 | let isbn = Isbn::new("".to_owned()); 225 | assert!(matches!(isbn, Ok(_))); 226 | } 227 | 228 | #[test] 229 | fn isbn_too_short() { 230 | let isbn = Isbn::new("1".to_owned()); 231 | assert!(matches!(isbn, Err(_))); 232 | } 233 | 234 | #[test] 235 | fn priority_0_is_valid() { 236 | let priority = Priority::new(0); 237 | assert!(matches!(priority, Ok(_))); 238 | } 239 | 240 | #[test] 241 | fn priority_100_is_valid() { 242 | let priority = Priority::new(100); 243 | assert!(matches!(priority, Ok(_))); 244 | } 245 | 246 | #[test] 247 | fn priority_negative1_is_invalid() { 248 | let priority = Priority::new(-1); 249 | assert!(matches!(priority, Err(_))); 250 | } 251 | 252 | #[test] 253 | fn priority_101_is_invalid() { 254 | let priority = Priority::new(101); 255 | assert!(matches!(priority, Err(_))); 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /src/domain/entity/common.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! impl_string_value_object { 3 | ( $type:tt ) => { 4 | impl $type { 5 | pub fn new(id: String) -> Result { 6 | let object = Self { value: id }; 7 | object.validate()?; 8 | Ok(object) 9 | } 10 | 11 | pub fn as_str(&self) -> &str { 12 | &self.value 13 | } 14 | 15 | pub fn into_string(self) -> String { 16 | self.value 17 | } 18 | } 19 | }; 20 | } 21 | -------------------------------------------------------------------------------- /src/domain/entity/user.rs: -------------------------------------------------------------------------------- 1 | use validator::Validate; 2 | 3 | use crate::{domain::error::DomainError, impl_string_value_object}; 4 | 5 | #[derive(Debug, Clone, PartialEq, Eq, Validate)] 6 | pub struct UserId { 7 | #[validate(length(min = 1))] 8 | value: String, 9 | } 10 | 11 | impl_string_value_object!(UserId); 12 | 13 | #[derive(Debug, Clone, PartialEq, Eq)] 14 | pub struct User { 15 | pub id: UserId, 16 | } 17 | 18 | impl User { 19 | pub fn new(id: UserId) -> User { 20 | User { id } 21 | } 22 | } 23 | 24 | #[cfg(test)] 25 | mod tests { 26 | use crate::domain::error::DomainError; 27 | 28 | use super::UserId; 29 | 30 | #[test] 31 | fn validation_success() { 32 | assert!(matches!(UserId::new(String::from("user1")), Ok(_))); 33 | } 34 | 35 | #[test] 36 | fn validation_failure() { 37 | assert!(matches!( 38 | UserId::new(String::from("")), 39 | Err(DomainError::Validation(_)) 40 | )); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/domain/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | use validator::ValidationErrors; 3 | 4 | use crate::common::types::{ParseBookFormatError, ParseBookStoreError}; 5 | 6 | #[derive(Debug, Error)] 7 | pub enum DomainError { 8 | #[error("{0}")] 9 | Validation(String), 10 | #[error(r#"{entity_type} was not found for entity_id "{entity_id}" and user_id "{user_id}"."#)] 11 | NotFound { 12 | entity_type: &'static str, 13 | entity_id: String, 14 | user_id: String, 15 | }, 16 | #[error(transparent)] 17 | InfrastructureError(anyhow::Error), 18 | #[error("{0}")] 19 | Unexpected(String), 20 | } 21 | 22 | impl From for DomainError { 23 | fn from(err: ValidationErrors) -> Self { 24 | DomainError::Validation(err.to_string()) 25 | } 26 | } 27 | 28 | impl From for DomainError { 29 | fn from(err: ParseBookStoreError) -> Self { 30 | DomainError::Validation(err.to_string()) 31 | } 32 | } 33 | 34 | impl From for DomainError { 35 | fn from(err: ParseBookFormatError) -> Self { 36 | DomainError::Validation(err.to_string()) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/domain/repository.rs: -------------------------------------------------------------------------------- 1 | pub mod author_repository; 2 | pub mod book_repository; 3 | pub mod user_repository; 4 | -------------------------------------------------------------------------------- /src/domain/repository/author_repository.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use async_trait::async_trait; 4 | use mockall::automock; 5 | 6 | use crate::domain::{ 7 | entity::{ 8 | author::{Author, AuthorId}, 9 | user::UserId, 10 | }, 11 | error::DomainError, 12 | }; 13 | 14 | #[automock] 15 | #[async_trait] 16 | pub trait AuthorRepository: Send + Sync + 'static { 17 | async fn create(&self, user_id: &UserId, author: &Author) -> Result<(), DomainError>; 18 | async fn find_by_id( 19 | &self, 20 | user_id: &UserId, 21 | author_id: &AuthorId, 22 | ) -> Result, DomainError>; 23 | async fn find_all(&self, user_id: &UserId) -> Result, DomainError>; 24 | async fn find_by_ids_as_hash_map( 25 | &self, 26 | user_id: &UserId, 27 | author_ids: &[AuthorId], 28 | ) -> Result, DomainError>; 29 | } 30 | -------------------------------------------------------------------------------- /src/domain/repository/book_repository.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use mockall::automock; 3 | 4 | use crate::domain::{ 5 | entity::{ 6 | book::{Book, BookId}, 7 | user::UserId, 8 | }, 9 | error::DomainError, 10 | }; 11 | 12 | #[automock] 13 | #[async_trait] 14 | pub trait BookRepository: Send + Sync + 'static { 15 | async fn create(&self, user_id: &UserId, book: &Book) -> Result<(), DomainError>; 16 | async fn find_by_id( 17 | &self, 18 | user_id: &UserId, 19 | book_id: &BookId, 20 | ) -> Result, DomainError>; 21 | async fn find_all(&self, user_id: &UserId) -> Result, DomainError>; 22 | async fn update(&self, user_id: &UserId, book: &Book) -> Result<(), DomainError>; 23 | async fn delete(&self, user_id: &UserId, book_id: &BookId) -> Result<(), DomainError>; 24 | } 25 | -------------------------------------------------------------------------------- /src/domain/repository/user_repository.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use mockall::automock; 3 | 4 | use crate::domain::{ 5 | entity::user::{User, UserId}, 6 | error::DomainError, 7 | }; 8 | 9 | #[automock] 10 | #[async_trait] 11 | pub trait UserRepository: Send + Sync + 'static { 12 | async fn create(&self, user: &User) -> Result<(), DomainError>; 13 | async fn find_by_id(&self, id: &UserId) -> Result, DomainError>; 14 | } 15 | -------------------------------------------------------------------------------- /src/infrastructure.rs: -------------------------------------------------------------------------------- 1 | pub mod author_repository; 2 | pub mod book_repository; 3 | pub mod error; 4 | pub mod user_repository; 5 | -------------------------------------------------------------------------------- /src/infrastructure/author_repository.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use async_trait::async_trait; 4 | use futures_util::{StreamExt, TryStreamExt}; 5 | use sqlx::PgPool; 6 | use uuid::Uuid; 7 | 8 | use crate::domain::{ 9 | entity::{ 10 | author::{Author, AuthorId, AuthorName}, 11 | user::UserId, 12 | }, 13 | error::DomainError, 14 | repository::author_repository::AuthorRepository, 15 | }; 16 | 17 | #[derive(sqlx::FromRow)] 18 | struct AuthorRow { 19 | id: Uuid, 20 | name: String, 21 | } 22 | 23 | #[derive(Debug, Clone)] 24 | pub struct PgAuthorRepository { 25 | pool: PgPool, 26 | } 27 | 28 | impl PgAuthorRepository { 29 | pub fn new(pool: PgPool) -> Self { 30 | Self { pool } 31 | } 32 | } 33 | 34 | #[async_trait] 35 | impl AuthorRepository for PgAuthorRepository { 36 | async fn create(&self, user_id: &UserId, author: &Author) -> Result<(), DomainError> { 37 | sqlx::query("INSERT INTO author (id, user_id, name) VALUES ($1, $2, $3)") 38 | .bind(author.id().to_uuid()) 39 | .bind(user_id.as_str()) 40 | .bind(author.name().as_str()) 41 | .execute(&self.pool) 42 | .await?; 43 | 44 | Ok(()) 45 | } 46 | async fn find_by_id( 47 | &self, 48 | user_id: &UserId, 49 | author_id: &AuthorId, 50 | ) -> Result, DomainError> { 51 | let row: Option = 52 | sqlx::query_as("SELECT * FROM author WHERE id = $1 AND user_id = $2") 53 | .bind(author_id.to_uuid()) 54 | .bind(user_id.as_str()) 55 | .fetch_optional(&self.pool) 56 | .await?; 57 | 58 | row.map(|row| -> Result { 59 | let author_id: AuthorId = row.id.into(); 60 | let author_name = AuthorName::new(row.name)?; 61 | Author::new(author_id, author_name) 62 | }) 63 | .transpose() 64 | } 65 | 66 | async fn find_all(&self, user_id: &UserId) -> Result, DomainError> { 67 | let authors: Result, DomainError> = 68 | sqlx::query_as("SELECT * FROM author WHERE user_id = $1 ORDER BY name ASC") 69 | .bind(user_id.as_str()) 70 | .fetch(&self.pool) 71 | .map( 72 | |row: Result| -> Result { 73 | let row = row?; 74 | let author_id = AuthorId::new(row.id); 75 | let author_name = AuthorName::new(row.name)?; 76 | let author = Author::new(author_id, author_name)?; 77 | Ok(author) 78 | }, 79 | ) 80 | .try_collect() 81 | .await; 82 | 83 | authors 84 | } 85 | 86 | async fn find_by_ids_as_hash_map( 87 | &self, 88 | user_id: &UserId, 89 | author_ids: &[AuthorId], 90 | ) -> Result, DomainError> { 91 | let author_ids: Vec = author_ids 92 | .iter() 93 | .map(|author_id| author_id.to_uuid()) 94 | .collect(); 95 | 96 | let authors_map: HashMap = sqlx::query_as( 97 | "SELECT * FROM author WHERE user_id = $1 AND id = ANY($2) ORDER BY name ASC", 98 | ) 99 | .bind(user_id.as_str()) 100 | .bind(author_ids) 101 | .fetch(&self.pool) 102 | .map( 103 | |row: Result| -> Result<(AuthorId, Author), DomainError> { 104 | let row = row?; 105 | let author_id = AuthorId::new(row.id); 106 | let author_name = AuthorName::new(row.name)?; 107 | let author = Author::new(author_id.clone(), author_name)?; 108 | Ok((author_id, author)) 109 | }, 110 | ) 111 | .try_collect() 112 | .await?; 113 | 114 | Ok(authors_map) 115 | } 116 | } 117 | 118 | #[cfg(feature = "test-with-database")] 119 | #[cfg(test)] 120 | mod tests { 121 | 122 | use crate::{ 123 | domain::{entity::user::User, repository::user_repository::UserRepository}, 124 | infrastructure::user_repository::PgUserRepository, 125 | }; 126 | 127 | use super::*; 128 | 129 | #[sqlx::test] 130 | async fn create_and_find_by_id(pool: PgPool) -> anyhow::Result<()> { 131 | let user_repository = PgUserRepository::new(pool.clone()); 132 | let author_repository = PgAuthorRepository::new(pool.clone()); 133 | 134 | let user_id = prepare_user(&user_repository).await?; 135 | 136 | let author_id = AuthorId::try_from("e324be11-5b77-4ba6-8423-9f27e2d228f1")?; 137 | let author_name = AuthorName::new(String::from("author1"))?; 138 | let author = Author::new(author_id.clone(), author_name)?; 139 | 140 | author_repository.create(&user_id, &author).await?; 141 | 142 | let actual = author_repository.find_by_id(&user_id, &author_id).await?; 143 | assert_eq!(actual, Some(author.clone())); 144 | 145 | Ok(()) 146 | } 147 | 148 | #[sqlx::test] 149 | async fn create_and_find_all(pool: PgPool) -> anyhow::Result<()> { 150 | let user_repository = PgUserRepository::new(pool.clone()); 151 | let author_repository = PgAuthorRepository::new(pool.clone()); 152 | 153 | let user_id = prepare_user(&user_repository).await?; 154 | 155 | let author_id = AuthorId::try_from("e324be11-5b77-4ba6-8423-9f27e2d228f1")?; 156 | let author_name = AuthorName::new(String::from("author1"))?; 157 | let author1 = Author::new(author_id.clone(), author_name)?; 158 | 159 | let author_id = AuthorId::try_from("e9700384-6217-4152-88c0-7ba38aeee73a")?; 160 | let author_name = AuthorName::new(String::from("author2"))?; 161 | let author2 = Author::new(author_id.clone(), author_name)?; 162 | 163 | author_repository.create(&user_id, &author1).await?; 164 | author_repository.create(&user_id, &author2).await?; 165 | 166 | let all_authors = author_repository.find_all(&user_id).await?; 167 | assert_eq!(all_authors.len(), 2); 168 | assert_eq!(all_authors, vec![author1, author2]); 169 | 170 | Ok(()) 171 | } 172 | 173 | #[sqlx::test] 174 | async fn create_and_find_by_ids_as_hash_map(pool: PgPool) -> anyhow::Result<()> { 175 | let user_repository = PgUserRepository::new(pool.clone()); 176 | let author_repository = PgAuthorRepository::new(pool.clone()); 177 | 178 | let user_id = prepare_user(&user_repository).await?; 179 | 180 | let author_id1 = AuthorId::try_from("e324be11-5b77-4ba6-8423-9f27e2d228f1")?; 181 | let author_name = AuthorName::new(String::from("author1"))?; 182 | let author1 = Author::new(author_id1.clone(), author_name)?; 183 | 184 | let author_id2 = AuthorId::try_from("e9700384-6217-4152-88c0-7ba38aeee73a")?; 185 | let author_name = AuthorName::new(String::from("author2"))?; 186 | let author2 = Author::new(author_id2.clone(), author_name)?; 187 | 188 | author_repository.create(&user_id, &author1).await?; 189 | author_repository.create(&user_id, &author2).await?; 190 | 191 | let all_authors = author_repository 192 | .find_by_ids_as_hash_map(&user_id, &[author_id1.clone(), author_id2.clone()]) 193 | .await?; 194 | let mut expected = HashMap::new(); 195 | expected.insert(author_id1, author1); 196 | expected.insert(author_id2, author2); 197 | 198 | assert_eq!(all_authors.len(), 2); 199 | assert_eq!(all_authors, expected); 200 | 201 | Ok(()) 202 | } 203 | 204 | async fn prepare_user(repository: &PgUserRepository) -> Result { 205 | let user_id = UserId::new(String::from("user1"))?; 206 | let user = User::new(user_id.clone()); 207 | repository.create(&user).await?; 208 | 209 | Ok(user_id) 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /src/infrastructure/book_repository.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use futures_util::{StreamExt, TryStreamExt}; 3 | use sqlx::PgPool; 4 | use time::OffsetDateTime; 5 | use uuid::Uuid; 6 | 7 | use crate::{ 8 | common::types::{BookFormat, BookStore}, 9 | domain::{ 10 | entity::{ 11 | author::AuthorId, 12 | book::{Book, BookId, BookTitle, Isbn, OwnedFlag, Priority, ReadFlag}, 13 | user::UserId, 14 | }, 15 | error::DomainError, 16 | repository::book_repository::BookRepository, 17 | }, 18 | }; 19 | 20 | #[derive(sqlx::FromRow)] 21 | struct BookRow { 22 | id: Uuid, 23 | title: String, 24 | author_ids: Option>, 25 | isbn: String, 26 | read: bool, 27 | owned: bool, 28 | priority: i32, 29 | format: String, 30 | store: String, 31 | created_at: OffsetDateTime, 32 | updated_at: OffsetDateTime, 33 | } 34 | 35 | #[derive(Debug, Clone)] 36 | pub struct PgBookRepository { 37 | pool: PgPool, 38 | } 39 | 40 | impl PgBookRepository { 41 | pub fn new(pool: PgPool) -> Self { 42 | Self { pool } 43 | } 44 | } 45 | 46 | #[async_trait] 47 | impl BookRepository for PgBookRepository { 48 | async fn create(&self, user_id: &UserId, book: &Book) -> Result<(), DomainError> { 49 | sqlx::query( 50 | "INSERT INTO book ( 51 | id, 52 | user_id, 53 | title, 54 | isbn, 55 | read, 56 | owned, 57 | priority, 58 | format, 59 | store, 60 | created_at, 61 | updated_at 62 | ) 63 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);", 64 | ) 65 | .bind(book.id().to_uuid()) 66 | .bind(user_id.as_str()) 67 | .bind(book.title().as_str()) 68 | .bind(book.isbn().as_str()) 69 | .bind(book.read().to_bool()) 70 | .bind(book.owned().to_bool()) 71 | .bind(book.priority().to_i32()) 72 | .bind(book.format().to_string()) 73 | .bind(book.store().to_string()) 74 | .bind(book.created_at()) 75 | .bind(book.updated_at()) 76 | .execute(&self.pool) 77 | .await?; 78 | 79 | let author_ids: Vec = book 80 | .author_ids() 81 | .iter() 82 | .map(|author_id| author_id.to_uuid()) 83 | .collect(); 84 | 85 | // https://github.com/launchbadge/sqlx/blob/fa5c436918664de112677519d73cf6939c938cb0/FAQ.md#how-can-i-bind-an-array-to-a-values-clause-how-can-i-do-bulk-inserts 86 | sqlx::query( 87 | "INSERT INTO book_author (user_id, book_id, author_id) 88 | SELECT $1, $2::uuid, * FROM UNNEST($3::uuid[])", 89 | ) 90 | .bind(user_id.as_str()) 91 | .bind(book.id().to_uuid()) 92 | .bind(&author_ids) 93 | .execute(&self.pool) 94 | .await?; 95 | 96 | Ok(()) 97 | } 98 | 99 | async fn find_by_id( 100 | &self, 101 | user_id: &UserId, 102 | book_id: &BookId, 103 | ) -> Result, DomainError> { 104 | let book_row: Option = sqlx::query_as( 105 | "WITH book_of_user AS( 106 | SELECT 107 | * 108 | FROM 109 | book 110 | WHERE 111 | book.user_id = $1 112 | ), 113 | authors_of_book_and_user AS( 114 | SELECT 115 | book_id, 116 | array_agg(author_id) AS author_ids 117 | FROM 118 | book_author 119 | WHERE 120 | book_author.user_id = $1 121 | GROUP BY 122 | book_author.book_id 123 | ) 124 | SELECT 125 | * 126 | FROM 127 | book_of_user 128 | LEFT OUTER JOIN 129 | authors_of_book_and_user 130 | ON book_of_user.id = authors_of_book_and_user.book_id 131 | WHERE book_of_user.id = $2", 132 | ) 133 | .bind(user_id.as_str()) 134 | .bind(book_id.to_uuid()) 135 | .fetch_optional(&self.pool) 136 | .await?; 137 | 138 | let book = book_row.map(|row| { 139 | let book_id = BookId::new(row.id)?; 140 | let title = BookTitle::new(row.title)?; 141 | let author_ids: Vec = row 142 | .author_ids 143 | .map(|author_ids| author_ids.into_iter().map(AuthorId::new).collect()) 144 | .unwrap_or_default(); 145 | let isbn = Isbn::new(row.isbn)?; 146 | let read = ReadFlag::new(row.read); 147 | let owned = OwnedFlag::new(row.owned); 148 | let priority = Priority::new(row.priority)?; 149 | let format = BookFormat::try_from(row.format.as_str())?; 150 | let store = BookStore::try_from(row.store.as_str())?; 151 | 152 | Book::new( 153 | book_id, 154 | title, 155 | author_ids, 156 | isbn, 157 | read, 158 | owned, 159 | priority, 160 | format, 161 | store, 162 | row.created_at, 163 | row.updated_at, 164 | ) 165 | }); 166 | let book = book.transpose()?; 167 | 168 | Ok(book) 169 | } 170 | 171 | async fn find_all(&self, user_id: &UserId) -> Result, DomainError> { 172 | let books: Result, DomainError> = sqlx::query_as( 173 | "WITH book_of_user AS( 174 | SELECT 175 | * 176 | FROM 177 | book 178 | WHERE 179 | book.user_id = $1 180 | ), 181 | authors_of_book_and_user AS( 182 | SELECT 183 | book_id, 184 | array_agg(author_id) AS author_ids 185 | FROM 186 | book_author 187 | WHERE 188 | book_author.user_id = $1 189 | GROUP BY 190 | book_author.book_id 191 | ) 192 | SELECT 193 | * 194 | FROM 195 | book_of_user 196 | LEFT OUTER JOIN 197 | authors_of_book_and_user 198 | ON book_of_user.id = authors_of_book_and_user.book_id", 199 | ) 200 | .bind(user_id.as_str()) 201 | .fetch(&self.pool) 202 | .map( 203 | |row: Result| -> Result { 204 | let row = row?; 205 | let book_id = BookId::new(row.id)?; 206 | let title = BookTitle::new(row.title)?; 207 | let author_ids: Vec = row 208 | .author_ids 209 | .map(|author_ids| author_ids.into_iter().map(AuthorId::new).collect()) 210 | .unwrap_or_else(std::vec::Vec::new); 211 | let isbn = Isbn::new(row.isbn)?; 212 | let read = ReadFlag::new(row.read); 213 | let owned = OwnedFlag::new(row.owned); 214 | let priority = Priority::new(row.priority)?; 215 | let format = BookFormat::try_from(row.format.as_str())?; 216 | let store = BookStore::try_from(row.store.as_str())?; 217 | 218 | Book::new( 219 | book_id, 220 | title, 221 | author_ids, 222 | isbn, 223 | read, 224 | owned, 225 | priority, 226 | format, 227 | store, 228 | row.created_at, 229 | row.updated_at, 230 | ) 231 | }, 232 | ) 233 | .try_collect() 234 | .await; 235 | 236 | books 237 | } 238 | 239 | async fn update(&self, user_id: &UserId, book: &Book) -> Result<(), DomainError> { 240 | let result = sqlx::query( 241 | "UPDATE book SET 242 | user_id = $1, 243 | title = $2, 244 | isbn = $3, 245 | read = $4, 246 | owned = $5, 247 | priority = $6, 248 | format = $7, 249 | store = $8, 250 | created_at = $9, 251 | updated_at = $10 252 | WHERE id = $11", 253 | ) 254 | .bind(user_id.as_str()) 255 | .bind(book.title().as_str()) 256 | .bind(book.isbn().as_str()) 257 | .bind(book.read().to_bool()) 258 | .bind(book.owned().to_bool()) 259 | .bind(book.priority().to_i32()) 260 | .bind(book.format().to_string()) 261 | .bind(book.store().to_string()) 262 | .bind(book.created_at()) 263 | .bind(book.updated_at()) 264 | .bind(book.id().to_uuid()) 265 | .execute(&self.pool) 266 | .await?; 267 | 268 | let rows_affected = result.rows_affected(); 269 | match rows_affected { 270 | 0 => { 271 | return Err(DomainError::NotFound { 272 | entity_type: "book", 273 | entity_id: book.id().to_string(), 274 | user_id: user_id.to_owned().into_string(), 275 | }); 276 | } 277 | 1 => {} 278 | _ => { 279 | return Err(DomainError::Unexpected(String::from( 280 | "rows_affected is greater than 1.", 281 | ))) 282 | } 283 | } 284 | 285 | let author_ids: Vec = book 286 | .author_ids() 287 | .iter() 288 | .map(|author_id| author_id.to_uuid()) 289 | .collect(); 290 | 291 | // https://github.com/launchbadge/sqlx/blob/fa5c436918664de112677519d73cf6939c938cb0/FAQ.md#how-can-i-do-a-select--where-foo-in--query 292 | sqlx::query("DELETE FROM book_author WHERE book_id = $1 AND author_id != ALL($2)") 293 | .bind(book.id().to_uuid()) 294 | .bind(&author_ids) 295 | .execute(&self.pool) 296 | .await?; 297 | 298 | // https://github.com/launchbadge/sqlx/blob/fa5c436918664de112677519d73cf6939c938cb0/FAQ.md#how-can-i-bind-an-array-to-a-values-clause-how-can-i-do-bulk-inserts 299 | sqlx::query( 300 | "INSERT INTO book_author (user_id, book_id, author_id) 301 | SELECT $1, $2::uuid, * FROM UNNEST($3::uuid[]) 302 | ON CONFLICT DO NOTHING", 303 | ) 304 | .bind(user_id.as_str()) 305 | .bind(book.id().to_uuid()) 306 | .bind(&author_ids) 307 | .execute(&self.pool) 308 | .await?; 309 | 310 | Ok(()) 311 | } 312 | 313 | async fn delete(&self, user_id: &UserId, book_id: &BookId) -> Result<(), DomainError> { 314 | sqlx::query("DELETE FROM book_author WHERE user_id = $1 AND book_id = $2") 315 | .bind(user_id.as_str()) 316 | .bind(book_id.to_uuid()) 317 | .execute(&self.pool) 318 | .await?; 319 | 320 | let result = sqlx::query("DELETE FROM book WHERE user_id = $1 AND id = $2") 321 | .bind(user_id.as_str()) 322 | .bind(book_id.to_uuid()) 323 | .execute(&self.pool) 324 | .await?; 325 | 326 | let rows_affected = result.rows_affected(); 327 | match rows_affected { 328 | 0 => { 329 | return Err(DomainError::NotFound { 330 | entity_type: "book", 331 | entity_id: book_id.to_string(), 332 | user_id: user_id.to_owned().into_string(), 333 | }); 334 | } 335 | 1 => {} 336 | _ => { 337 | return Err(DomainError::Unexpected(String::from( 338 | "rows_affected is greater than 1.", 339 | ))) 340 | } 341 | } 342 | 343 | Ok(()) 344 | } 345 | } 346 | 347 | #[cfg(feature = "test-with-database")] 348 | #[cfg(test)] 349 | mod tests { 350 | 351 | use crate::{ 352 | domain::{ 353 | entity::{ 354 | author::{Author, AuthorName}, 355 | user::User, 356 | }, 357 | repository::{author_repository::AuthorRepository, user_repository::UserRepository}, 358 | }, 359 | infrastructure::{ 360 | author_repository::PgAuthorRepository, user_repository::PgUserRepository, 361 | }, 362 | }; 363 | 364 | use super::*; 365 | use time::{ 366 | macros::{date, time}, 367 | PrimitiveDateTime, 368 | }; 369 | 370 | #[sqlx::test] 371 | async fn test_create_and_find_by_id(pool: PgPool) -> anyhow::Result<()> { 372 | let user_repository = PgUserRepository::new(pool.clone()); 373 | let author_repository = PgAuthorRepository::new(pool.clone()); 374 | let book_repository = PgBookRepository::new(pool.clone()); 375 | 376 | let user_id = prepare_user(&user_repository).await?; 377 | let author_ids = prepare_authors1(&user_id, &author_repository).await?; 378 | 379 | let all_books = book_repository.find_all(&user_id).await?; 380 | assert_eq!(all_books.len(), 0); 381 | 382 | let book = book_entity1(&author_ids)?; 383 | book_repository.create(&user_id, &book).await?; 384 | 385 | let actual = book_repository.find_by_id(&user_id, book.id()).await?; 386 | assert_eq!(actual, Some(book)); 387 | 388 | Ok(()) 389 | } 390 | 391 | #[sqlx::test] 392 | async fn test_create_and_find_all(pool: PgPool) -> anyhow::Result<()> { 393 | let user_repository = PgUserRepository::new(pool.clone()); 394 | let author_repository = PgAuthorRepository::new(pool.clone()); 395 | let book_repository = PgBookRepository::new(pool.clone()); 396 | 397 | let user_id = prepare_user(&user_repository).await?; 398 | 399 | let author_ids1 = prepare_authors1(&user_id, &author_repository).await?; 400 | let author_ids2 = prepare_authors2(&user_id, &author_repository).await?; 401 | 402 | let all_books = book_repository.find_all(&user_id).await?; 403 | assert_eq!(all_books.len(), 0); 404 | 405 | let book1 = book_entity1(&author_ids1)?; 406 | let book2 = book_entity2(&author_ids2)?; 407 | book_repository.create(&user_id, &book1).await?; 408 | book_repository.create(&user_id, &book2).await?; 409 | 410 | let all_books = book_repository.find_all(&user_id).await?; 411 | assert_eq!(all_books.len(), 2); 412 | if all_books[0] == book1 { 413 | assert_eq!(all_books[0], book1); 414 | assert_eq!(all_books[1], book2); 415 | } else { 416 | assert_eq!(all_books[0], book2); 417 | assert_eq!(all_books[1], book1); 418 | } 419 | 420 | Ok(()) 421 | } 422 | 423 | #[sqlx::test] 424 | async fn test_update(pool: PgPool) -> anyhow::Result<()> { 425 | // setup 426 | let user_repository = PgUserRepository::new(pool.clone()); 427 | let author_repository = PgAuthorRepository::new(pool.clone()); 428 | let book_repository = PgBookRepository::new(pool.clone()); 429 | 430 | let user_id = prepare_user(&user_repository).await?; 431 | let mut author_ids = prepare_authors1(&user_id, &author_repository).await?; 432 | let mut book = book_entity1(&author_ids)?; 433 | book_repository.create(&user_id, &book).await?; 434 | let actual = book_repository.find_by_id(&user_id, book.id()).await?; 435 | assert_eq!(actual, Some(book.clone())); 436 | 437 | // update 438 | book.set_title(BookTitle::new("another_title".to_owned())?); 439 | author_ids.pop(); 440 | let another_author_id = AuthorId::try_from("e30ce456-d34a-4c42-831c-b08d5f9ed81f")?; 441 | let another_author = Author::new( 442 | another_author_id.clone(), 443 | AuthorName::new("another_author1".to_owned())?, 444 | )?; 445 | author_repository.create(&user_id, &another_author).await?; 446 | author_ids.push(another_author_id); 447 | book.set_author_ids(author_ids); 448 | book_repository.update(&user_id, &book).await?; 449 | 450 | let actual = book_repository.find_by_id(&user_id, book.id()).await?; 451 | assert_eq!(actual, Some(book.clone())); 452 | 453 | Ok(()) 454 | } 455 | 456 | #[sqlx::test] 457 | async fn test_delete(pool: PgPool) -> anyhow::Result<()> { 458 | let user_repository = PgUserRepository::new(pool.clone()); 459 | let author_repository = PgAuthorRepository::new(pool.clone()); 460 | let book_repository = PgBookRepository::new(pool.clone()); 461 | 462 | let user_id = prepare_user(&user_repository).await?; 463 | let author_ids = prepare_authors1(&user_id, &author_repository).await?; 464 | let book = book_entity1(&author_ids)?; 465 | book_repository.create(&user_id, &book).await?; 466 | let actual = book_repository.find_by_id(&user_id, book.id()).await?; 467 | assert_eq!(actual, Some(book.clone())); 468 | 469 | book_repository.delete(&user_id, book.id()).await?; 470 | let actual = book_repository.find_by_id(&user_id, book.id()).await?; 471 | assert_eq!(actual, None); 472 | 473 | Ok(()) 474 | } 475 | 476 | async fn prepare_user(repository: &PgUserRepository) -> Result { 477 | let user_id = UserId::new(String::from("user1"))?; 478 | let user = User::new(user_id.clone()); 479 | repository.create(&user).await?; 480 | 481 | Ok(user_id) 482 | } 483 | 484 | async fn prepare_authors1( 485 | user_id: &UserId, 486 | repository: &PgAuthorRepository, 487 | ) -> Result, DomainError> { 488 | let author_id1 = AuthorId::try_from("278935cf-ed83-4346-9b35-b84bbdb630c0")?; 489 | let author_id2 = AuthorId::try_from("925aaf96-64c7-44be-85f8-767a20b2c20c")?; 490 | let author_ids = vec![author_id1.clone(), author_id2.clone()]; 491 | let author1 = Author::new(author_id1, AuthorName::new("author1".to_owned())?)?; 492 | let author2 = Author::new(author_id2, AuthorName::new("author2".to_owned())?)?; 493 | repository.create(user_id, &author1).await?; 494 | repository.create(user_id, &author2).await?; 495 | 496 | Ok(author_ids) 497 | } 498 | 499 | async fn prepare_authors2( 500 | user_id: &UserId, 501 | repository: &PgAuthorRepository, 502 | ) -> Result, DomainError> { 503 | let author_id1 = AuthorId::try_from("93090e87-b7a1-403c-974c-d74d881e83b9")?; 504 | let author_ids = vec![author_id1.clone()]; 505 | let author1 = Author::new(author_id1, AuthorName::new("author1".to_owned())?)?; 506 | repository.create(user_id, &author1).await?; 507 | 508 | Ok(author_ids) 509 | } 510 | 511 | fn book_entity1(author_ids: &[AuthorId]) -> Result { 512 | let book_id = BookId::try_from("675bc8d9-3155-42fb-87b0-0a82cb162848")?; 513 | let title = BookTitle::new("title1".to_owned())?; 514 | let isbn = Isbn::new("1111111111116".to_owned())?; 515 | let read = ReadFlag::new(false); 516 | let owned = OwnedFlag::new(false); 517 | let priority = Priority::new(50)?; 518 | let format = BookFormat::EBook; 519 | let store = BookStore::Kindle; 520 | let created_at = PrimitiveDateTime::new(date!(2022 - 05 - 05), time!(0:00)).assume_utc(); 521 | let updated_at = PrimitiveDateTime::new(date!(2022 - 05 - 05), time!(0:00)).assume_utc(); 522 | 523 | let book = Book::new( 524 | book_id, 525 | title, 526 | author_ids.to_owned(), 527 | isbn, 528 | read, 529 | owned, 530 | priority, 531 | format, 532 | store, 533 | created_at, 534 | updated_at, 535 | )?; 536 | 537 | Ok(book) 538 | } 539 | 540 | fn book_entity2(author_ids: &[AuthorId]) -> Result { 541 | let book_id = BookId::try_from("c5a81e57-bc91-40ff-8b57-18cfa7cc7ae8")?; 542 | let title = BookTitle::new("title2".to_owned())?; 543 | let isbn = Isbn::new("2222222222222".to_owned())?; 544 | let read = ReadFlag::new(false); 545 | let owned = OwnedFlag::new(false); 546 | let priority = Priority::new(50)?; 547 | let format = BookFormat::EBook; 548 | let store = BookStore::Kindle; 549 | let created_at = PrimitiveDateTime::new(date!(2022 - 05 - 05), time!(0:00)).assume_utc(); 550 | let updated_at = PrimitiveDateTime::new(date!(2022 - 05 - 05), time!(0:00)).assume_utc(); 551 | 552 | let book = Book::new( 553 | book_id, 554 | title, 555 | author_ids.to_owned(), 556 | isbn, 557 | read, 558 | owned, 559 | priority, 560 | format, 561 | store, 562 | created_at, 563 | updated_at, 564 | )?; 565 | 566 | Ok(book) 567 | } 568 | } 569 | -------------------------------------------------------------------------------- /src/infrastructure/error.rs: -------------------------------------------------------------------------------- 1 | use crate::domain::error::DomainError; 2 | 3 | impl From for DomainError { 4 | fn from(error: sqlx::Error) -> Self { 5 | DomainError::InfrastructureError(anyhow::Error::new(error)) 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/infrastructure/user_repository.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use sqlx::PgPool; 3 | 4 | use crate::domain::{ 5 | entity::user::{User, UserId}, 6 | error::DomainError, 7 | repository::user_repository::UserRepository, 8 | }; 9 | 10 | #[derive(sqlx::FromRow)] 11 | struct UserRow { 12 | id: String, 13 | } 14 | 15 | #[derive(Debug, Clone)] 16 | pub struct PgUserRepository { 17 | pool: PgPool, 18 | } 19 | 20 | impl PgUserRepository { 21 | pub fn new(pool: PgPool) -> Self { 22 | Self { pool } 23 | } 24 | } 25 | 26 | #[async_trait] 27 | impl UserRepository for PgUserRepository { 28 | async fn create(&self, user: &User) -> Result<(), DomainError> { 29 | sqlx::query("INSERT INTO bookshelf_user (id) VALUES ($1)") 30 | .bind(user.id.as_str()) 31 | .execute(&self.pool) 32 | .await?; 33 | Ok(()) 34 | } 35 | 36 | async fn find_by_id(&self, id: &UserId) -> Result, DomainError> { 37 | let row: Option = sqlx::query_as("SELECT * FROM bookshelf_user WHERE id = $1") 38 | .bind(id.as_str()) 39 | .fetch_optional(&self.pool) 40 | .await?; 41 | 42 | let id = row.map(|row| UserId::new(row.id)).transpose()?; 43 | Ok(id.map(User::new)) 44 | } 45 | } 46 | 47 | #[cfg(feature = "test-with-database")] 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | 52 | #[sqlx::test] 53 | async fn test_user_repository(pool: PgPool) -> anyhow::Result<()> { 54 | dotenv::dotenv().ok(); 55 | 56 | let repository = PgUserRepository::new(pool); 57 | 58 | let id = UserId::new(String::from("foo"))?; 59 | let user = User::new(id.clone()); 60 | 61 | let fetched_user = repository.find_by_id(&id).await?; 62 | assert!(fetched_user.is_none()); 63 | 64 | repository.create(&user).await?; 65 | 66 | let fetched_user = repository.find_by_id(&id).await?; 67 | assert_eq!(fetched_user, Some(user)); 68 | 69 | Ok(()) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod common; 2 | pub mod dependency_injection; 3 | pub mod domain; 4 | pub mod infrastructure; 5 | pub mod presentation; 6 | pub mod types; 7 | pub mod use_case; 8 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use std::{net::SocketAddr, sync::Arc}; 2 | 3 | use axum::{ 4 | routing::{get, post}, 5 | Extension, Router, 6 | }; 7 | use bookshelf_api::{ 8 | dependency_injection::{dependency_injection, MI, QI}, 9 | presentation::handler::graphql::{graphql_handler, graphql_playground_handler}, 10 | presentation::{app_state::AppState, extractor::claims::Auth0Config}, 11 | }; 12 | use http::{ 13 | header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}, 14 | HeaderValue, Method, 15 | }; 16 | use sqlx::postgres::PgPoolOptions; 17 | use tower::ServiceBuilder; 18 | use tower_http::trace::{DefaultOnResponse, TraceLayer}; 19 | use tower_http::{cors::CorsLayer, trace::DefaultOnRequest}; 20 | use tracing::Level; 21 | 22 | #[tokio::main] 23 | async fn main() { 24 | dotenv::dotenv().ok(); 25 | 26 | tracing_subscriber::fmt::init(); 27 | 28 | let db_url = fetch_database_url(); 29 | 30 | let pool = PgPoolOptions::new() 31 | .max_connections(5) 32 | .connect(&db_url) 33 | .await 34 | .unwrap(); 35 | 36 | sqlx::migrate!() 37 | .run(&pool) 38 | .await 39 | .expect("Migration failed."); 40 | 41 | let (query_use_case, schema) = dependency_injection(pool); 42 | 43 | let auth0_config = Auth0Config::default(); 44 | let state = Arc::new(AppState { auth0_config }); 45 | 46 | let allowed_origins: Vec<_> = fetch_allowed_origins() 47 | .into_iter() 48 | .map(|origin| origin.parse::().unwrap()) 49 | .collect(); 50 | let cors_layer = CorsLayer::new() 51 | .allow_origin(allowed_origins) 52 | .allow_methods([Method::POST]) 53 | .allow_headers(vec![AUTHORIZATION, ACCEPT, CONTENT_TYPE]); 54 | 55 | // build our application with a single route 56 | let app = Router::new() 57 | .route("/", get(|| async { "OK" })) 58 | .route("/graphql", post(graphql_handler::)) 59 | .route("/graphql/playground", get(graphql_playground_handler)) 60 | .route("/health", get(|| async { "OK" })) 61 | .with_state(state) 62 | .layer( 63 | ServiceBuilder::new() 64 | .layer(Extension(query_use_case)) 65 | .layer(Extension(schema)) 66 | .layer( 67 | TraceLayer::new_for_http() 68 | .on_request(DefaultOnRequest::new().level(Level::INFO)) 69 | .on_response(DefaultOnResponse::new().level(Level::INFO)), 70 | ) 71 | .layer(cors_layer), 72 | ); 73 | 74 | let addr = SocketAddr::from(([0, 0, 0, 0], fetch_port())); 75 | let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); 76 | axum::serve(listener, app).await.unwrap(); 77 | } 78 | 79 | fn fetch_port() -> u16 { 80 | use std::env::VarError; 81 | 82 | match std::env::var("PORT") { 83 | Ok(s) => s 84 | .parse() 85 | .expect("Failed to parse environment variable PORT."), 86 | Err(VarError::NotPresent) => panic!("Environment variable PORT is required."), 87 | Err(VarError::NotUnicode(_)) => panic!("Environment variable PORT is not unicode."), 88 | } 89 | } 90 | 91 | fn fetch_database_url() -> String { 92 | use std::env::VarError; 93 | 94 | match std::env::var("DATABASE_URL") { 95 | Ok(s) => s, 96 | Err(VarError::NotPresent) => panic!("Environment variable DATABASE_URL is required."), 97 | Err(VarError::NotUnicode(_)) => panic!("Environment variable DATABASE_URL is not unicode."), 98 | } 99 | } 100 | 101 | fn fetch_allowed_origins() -> Vec { 102 | use std::env::VarError; 103 | 104 | match std::env::var("ALLOWED_ORIGINS") { 105 | Ok(s) => s.split(',').map(|s| s.to_owned()).collect(), 106 | Err(VarError::NotPresent) => panic!("Environment variable ALLOWED_ORIGINS is required."), 107 | Err(VarError::NotUnicode(_)) => { 108 | panic!("Environment variable ALLOWED_ORIGINS is not unicode.") 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/presentation.rs: -------------------------------------------------------------------------------- 1 | pub mod app_state; 2 | pub mod error; 3 | pub mod extractor; 4 | pub mod graphql; 5 | pub mod handler; 6 | -------------------------------------------------------------------------------- /src/presentation/app_state.rs: -------------------------------------------------------------------------------- 1 | use super::extractor::claims::Auth0Config; 2 | 3 | #[derive(Debug, Clone)] 4 | pub struct AppState { 5 | pub auth0_config: Auth0Config, 6 | } 7 | -------------------------------------------------------------------------------- /src/presentation/error.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use thiserror::Error; 4 | 5 | use crate::use_case::error::UseCaseError; 6 | 7 | #[derive(Debug, Clone, Error)] 8 | pub enum PresentationalError { 9 | #[error("{0}")] 10 | NotFound(String), 11 | #[error("{0}")] 12 | Validation(String), 13 | #[error(transparent)] 14 | OtherError(Arc), 15 | #[error("{0}")] 16 | Unexpected(String), 17 | } 18 | 19 | impl From for PresentationalError { 20 | fn from(err: UseCaseError) -> Self { 21 | match err { 22 | UseCaseError::NotFound { .. } => PresentationalError::NotFound(err.to_string()), 23 | UseCaseError::Validation(_) => PresentationalError::Validation(err.to_string()), 24 | UseCaseError::Other(_) => { 25 | PresentationalError::OtherError(Arc::new(anyhow::Error::new(err))) 26 | } 27 | UseCaseError::Unexpected(message) => PresentationalError::Unexpected(message), 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/presentation/extractor.rs: -------------------------------------------------------------------------------- 1 | pub mod claims; 2 | -------------------------------------------------------------------------------- /src/presentation/extractor/claims.rs: -------------------------------------------------------------------------------- 1 | use crate::presentation::app_state::AppState; 2 | use async_trait::async_trait; 3 | use axum::extract::FromRequestParts; 4 | use axum::http::request::Parts; 5 | use axum::response::{IntoResponse, Response}; 6 | use axum::{Json, RequestPartsExt}; 7 | use axum_extra::headers::authorization::Bearer; 8 | use axum_extra::headers::Authorization; 9 | use axum_extra::TypedHeader; 10 | use derive_more::Display; 11 | use http::{StatusCode, Uri}; 12 | use jsonwebtoken::{ 13 | decode, decode_header, 14 | jwk::{AlgorithmParameters, JwkSet}, 15 | Algorithm, DecodingKey, Validation, 16 | }; 17 | use serde::Deserialize; 18 | use serde_json::json; 19 | use std::{collections::HashSet, sync::Arc}; 20 | 21 | #[derive(Debug, Clone, Deserialize)] 22 | pub struct Auth0Config { 23 | audience: String, 24 | domain: String, 25 | } 26 | 27 | impl Default for Auth0Config { 28 | fn default() -> Self { 29 | envy::prefixed("AUTH0_") 30 | .from_env() 31 | .expect("Provide missing environment variables for Auth0Client") 32 | } 33 | } 34 | 35 | #[derive(Debug, Display)] 36 | pub enum ClientError { 37 | #[display("authentication")] 38 | Authentication, 39 | #[display("decode")] 40 | Decode(jsonwebtoken::errors::Error), 41 | #[display("not_found")] 42 | NotFound(String), 43 | #[display("unsupported_algorithm")] 44 | UnsupportedAlgortithm(AlgorithmParameters), 45 | } 46 | 47 | impl IntoResponse for ClientError { 48 | fn into_response(self) -> Response { 49 | let (error, error_description, message) = match self { 50 | Self::Authentication => (None, None, "Requires authentication".to_string()), 51 | Self::Decode(_) => ( 52 | Some("invalid_token".to_string()), 53 | Some( 54 | "Authorization header value must follow this format: Bearer access-token" 55 | .to_string(), 56 | ), 57 | "Bad credentials".to_string(), 58 | ), 59 | Self::NotFound(msg) => ( 60 | Some("invalid_token".to_string()), 61 | Some(msg), 62 | "Bad credentials".to_string(), 63 | ), 64 | Self::UnsupportedAlgortithm(alg) => ( 65 | Some("invalid_token".to_string()), 66 | Some(format!( 67 | "Unsupported encryption algortithm expected RSA got {:?}", 68 | alg 69 | )), 70 | "Bad credentials".to_string(), 71 | ), 72 | }; 73 | let body = Json(json!({ 74 | "error": error, 75 | "error_description": error_description, 76 | "message": message 77 | })); 78 | (StatusCode::UNAUTHORIZED, body).into_response() 79 | } 80 | } 81 | 82 | #[derive(Debug, Clone, Deserialize)] 83 | pub struct Claims { 84 | pub sub: String, 85 | pub _permissions: Option>, 86 | } 87 | 88 | #[async_trait] 89 | impl FromRequestParts> for Claims { 90 | type Rejection = ClientError; 91 | 92 | async fn from_request_parts( 93 | parts: &mut Parts, 94 | state: &Arc, 95 | ) -> Result { 96 | let config = state.auth0_config.clone(); 97 | let TypedHeader(Authorization(bearer)) = parts 98 | .extract::>>() 99 | .await 100 | .map_err(|_| ClientError::Authentication)?; 101 | let token = bearer.token(); 102 | 103 | let header = decode_header(token).map_err(ClientError::Decode)?; 104 | let kid = header 105 | .kid 106 | .ok_or_else(|| ClientError::NotFound("kid not found in token header".to_string()))?; 107 | let domain = config.domain.as_str(); 108 | // TODO: サンプル実装の通りに戻せそうなら戻す 109 | // https://github.com/auth0-developer-hub/api_actix-web_rust_hello-world/blob/c86861763a4a4f2ad5f0e39bb3c15a7216d3fdba/src/extractors/claims.rs#L107-L119 110 | let jwks = fetch_jwks(domain).await.unwrap(); // TODO 111 | let jwk = jwks 112 | .find(&kid) 113 | .ok_or_else(|| ClientError::NotFound("No JWK found for kid".to_string()))?; 114 | match jwk.clone().algorithm { 115 | AlgorithmParameters::RSA(ref rsa) => { 116 | let mut validation = Validation::new(Algorithm::RS256); 117 | validation.set_audience(&[config.audience]); 118 | validation.set_issuer(&[Uri::builder() 119 | .scheme("https") 120 | .authority(domain) 121 | .path_and_query("/") 122 | .build() 123 | .unwrap()]); 124 | let key = DecodingKey::from_rsa_components(&rsa.n, &rsa.e) 125 | .map_err(ClientError::Decode)?; 126 | let token = 127 | decode::(token, &key, &validation).map_err(ClientError::Decode)?; 128 | Ok(token.claims) 129 | } 130 | algorithm => Err(ClientError::UnsupportedAlgortithm(algorithm)), 131 | } 132 | } 133 | } 134 | 135 | #[derive(Debug, Display, derive_more::Error)] 136 | #[display("my error: {message}")] 137 | struct MyError { 138 | message: String, 139 | } 140 | 141 | async fn fetch_jwks(domain: &str) -> Result { 142 | let uri = Uri::builder() 143 | .scheme("https") 144 | .authority(domain) 145 | .path_and_query("/.well-known/jwks.json") 146 | .build() 147 | .unwrap(); 148 | let client = reqwest::ClientBuilder::new() 149 | .use_rustls_tls() 150 | .build() 151 | .unwrap(); 152 | let response = client.get(uri.to_string()).send().await; 153 | let response = match response { 154 | Ok(response) => response, 155 | Err(e) => { 156 | return Err(MyError { 157 | message: format!("TODO1: {}", e), 158 | }) 159 | } 160 | }; 161 | match response.json().await { 162 | Ok(jwks) => Ok(jwks), 163 | Err(_) => Err(MyError { 164 | message: "TODO2".to_string(), 165 | }), 166 | } 167 | } 168 | 169 | #[derive(Debug)] 170 | pub enum AuthError { 171 | WrongCredentials, 172 | MissingCredentials, 173 | TokenCreation, 174 | InvalidToken, 175 | } 176 | 177 | impl IntoResponse for AuthError { 178 | fn into_response(self) -> Response { 179 | let (status, error_message) = match self { 180 | AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, "Wrong credentials"), 181 | AuthError::MissingCredentials => (StatusCode::BAD_REQUEST, "Missing credentials"), 182 | AuthError::TokenCreation => (StatusCode::INTERNAL_SERVER_ERROR, "Token creation error"), 183 | AuthError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token"), 184 | }; 185 | let body = Json(json!({ 186 | "error": error_message, 187 | })); 188 | (status, body).into_response() 189 | } 190 | } 191 | 192 | #[cfg(test)] 193 | mod test { 194 | use crate::presentation::extractor::claims::MyError; 195 | 196 | #[test] 197 | fn my_error_to_string() { 198 | assert_eq!( 199 | MyError { 200 | message: "test".to_string() 201 | } 202 | .to_string(), 203 | "my error: test" 204 | ); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/presentation/graphql.rs: -------------------------------------------------------------------------------- 1 | pub mod loader; 2 | pub mod mutation; 3 | pub mod object; 4 | pub mod query; 5 | pub mod schema; 6 | -------------------------------------------------------------------------------- /src/presentation/graphql/loader.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use async_graphql::dataloader::Loader; 4 | 5 | use crate::{ 6 | presentation::{error::PresentationalError, extractor::claims::Claims}, 7 | use_case::traits::query::QueryUseCase, 8 | }; 9 | 10 | use super::object::Author; 11 | 12 | pub struct AuthorLoader { 13 | claims: Claims, 14 | query_use_case: QUC, 15 | } 16 | 17 | impl AuthorLoader { 18 | pub fn new(claims: Claims, query_use_case: QUC) -> Self { 19 | Self { 20 | claims, 21 | query_use_case, 22 | } 23 | } 24 | } 25 | 26 | impl Loader for AuthorLoader 27 | where 28 | QUC: QueryUseCase, 29 | { 30 | type Value = Author; 31 | type Error = PresentationalError; 32 | 33 | async fn load(&self, keys: &[String]) -> Result, Self::Error> { 34 | let authors_map = self 35 | .query_use_case 36 | .find_author_by_ids_as_hash_map(&self.claims.sub, keys) 37 | .await?; 38 | let authors_map: HashMap = authors_map 39 | .into_iter() 40 | .map(|(author_id, author)| (author_id, Author::from(author))) 41 | .collect(); 42 | 43 | Ok(authors_map) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/presentation/graphql/mutation.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use async_graphql::{Context, Object, ID}; 4 | 5 | use crate::{ 6 | presentation::{error::PresentationalError, extractor::claims::Claims}, 7 | use_case::traits::mutation::MutationUseCase, 8 | }; 9 | 10 | use super::object::{Author, Book, CreateAuthorInput, CreateBookInput, UpdateBookInput, User}; 11 | 12 | pub struct Mutation { 13 | mutation_use_case: MUC, 14 | } 15 | 16 | impl Mutation { 17 | pub fn new(mutation_use_case: MUC) -> Self { 18 | Self { mutation_use_case } 19 | } 20 | } 21 | 22 | #[Object] 23 | impl Mutation 24 | where 25 | MUC: MutationUseCase, 26 | { 27 | async fn register_user(&self, ctx: &Context<'_>) -> Result { 28 | let claims = get_claims(ctx)?; 29 | let user = self.mutation_use_case.register_user(&claims.sub).await?; 30 | Ok(User::new(ID(user.id))) 31 | } 32 | 33 | async fn create_book( 34 | &self, 35 | ctx: &Context<'_>, 36 | book_data: CreateBookInput, 37 | ) -> Result { 38 | let claims = get_claims(ctx)?; 39 | let book = self 40 | .mutation_use_case 41 | .create_book(&claims.sub, book_data.into()) 42 | .await?; 43 | 44 | Ok(book.into()) 45 | } 46 | 47 | async fn update_book( 48 | &self, 49 | ctx: &Context<'_>, 50 | book_data: UpdateBookInput, 51 | ) -> Result { 52 | let claims = get_claims(ctx)?; 53 | let book = self 54 | .mutation_use_case 55 | .update_book(&claims.sub, book_data.into()) 56 | .await?; 57 | 58 | Ok(book.into()) 59 | } 60 | 61 | async fn delete_book( 62 | &self, 63 | ctx: &Context<'_>, 64 | book_id: ID, 65 | ) -> Result { 66 | let claims = get_claims(ctx)?; 67 | self.mutation_use_case 68 | .delete_book(&claims.sub, book_id.as_str()) 69 | .await?; 70 | 71 | Ok(book_id.to_string()) 72 | } 73 | 74 | async fn create_author( 75 | &self, 76 | ctx: &Context<'_>, 77 | author_data: CreateAuthorInput, 78 | ) -> Result { 79 | let claims = get_claims(ctx)?; 80 | let author = self 81 | .mutation_use_case 82 | .create_author(&claims.sub, author_data.into()) 83 | .await?; 84 | Ok(author.into()) 85 | } 86 | } 87 | 88 | fn get_claims<'a>(ctx: &Context<'a>) -> Result<&'a Claims, PresentationalError> { 89 | ctx.data::() 90 | .map_err(|err| PresentationalError::OtherError(Arc::new(anyhow::anyhow!(err.message)))) 91 | } 92 | -------------------------------------------------------------------------------- /src/presentation/graphql/object.rs: -------------------------------------------------------------------------------- 1 | use async_graphql::dataloader::DataLoader; 2 | use async_graphql::{ComplexObject, Context, Enum, Result}; 3 | use async_graphql::{InputObject, SimpleObject, ID}; 4 | 5 | use crate::common::types::{BookFormat as CommonBookFormat, BookStore as CommonBookStore}; 6 | use crate::dependency_injection::QI; 7 | use crate::use_case::dto::author::AuthorDto; 8 | use crate::use_case::dto::author::CreateAuthorDto; 9 | use crate::use_case::dto::book::{BookDto, CreateBookDto, UpdateBookDto}; 10 | 11 | use super::loader::AuthorLoader; 12 | 13 | #[derive(SimpleObject)] 14 | pub struct User { 15 | id: ID, 16 | } 17 | 18 | impl User { 19 | pub fn new(id: ID) -> Self { 20 | Self { id } 21 | } 22 | } 23 | 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)] 25 | pub enum BookFormat { 26 | EBook, 27 | Printed, 28 | Unknown, 29 | } 30 | 31 | impl From for BookFormat { 32 | fn from(book_format: CommonBookFormat) -> Self { 33 | match book_format { 34 | CommonBookFormat::EBook => BookFormat::EBook, 35 | CommonBookFormat::Printed => BookFormat::Printed, 36 | CommonBookFormat::Unknown => BookFormat::Unknown, 37 | } 38 | } 39 | } 40 | 41 | impl From for CommonBookFormat { 42 | fn from(book_format: BookFormat) -> Self { 43 | match book_format { 44 | BookFormat::EBook => CommonBookFormat::EBook, 45 | BookFormat::Printed => CommonBookFormat::Printed, 46 | BookFormat::Unknown => CommonBookFormat::Unknown, 47 | } 48 | } 49 | } 50 | 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)] 52 | pub enum BookStore { 53 | Kindle, 54 | Unknown, 55 | } 56 | 57 | impl From for BookStore { 58 | fn from(book_format: CommonBookStore) -> Self { 59 | match book_format { 60 | CommonBookStore::Kindle => BookStore::Kindle, 61 | CommonBookStore::Unknown => BookStore::Unknown, 62 | } 63 | } 64 | } 65 | 66 | impl From for CommonBookStore { 67 | fn from(book_format: BookStore) -> Self { 68 | match book_format { 69 | BookStore::Kindle => CommonBookStore::Kindle, 70 | BookStore::Unknown => CommonBookStore::Unknown, 71 | } 72 | } 73 | } 74 | 75 | #[derive(SimpleObject)] 76 | #[graphql(complex)] 77 | pub struct Book { 78 | pub id: String, 79 | pub title: String, 80 | #[graphql(skip)] 81 | pub author_ids: Vec, 82 | pub isbn: String, 83 | pub read: bool, 84 | pub owned: bool, 85 | pub priority: i32, 86 | pub format: BookFormat, 87 | pub store: BookStore, 88 | pub created_at: i64, 89 | pub updated_at: i64, 90 | } 91 | 92 | impl Book { 93 | #[allow(clippy::too_many_arguments)] 94 | pub fn new( 95 | id: String, 96 | title: String, 97 | author_ids: Vec, 98 | isbn: String, 99 | read: bool, 100 | owned: bool, 101 | priority: i32, 102 | format: BookFormat, 103 | store: BookStore, 104 | created_at: i64, 105 | updated_at: i64, 106 | ) -> Self { 107 | Self { 108 | id, 109 | title, 110 | author_ids, 111 | isbn, 112 | read, 113 | owned, 114 | priority, 115 | format, 116 | store, 117 | created_at, 118 | updated_at, 119 | } 120 | } 121 | } 122 | 123 | #[ComplexObject] 124 | impl Book { 125 | async fn authors(&self, ctx: &Context<'_>) -> Result> { 126 | // QIの型はGenericにできないか 127 | let loader = ctx.data_unchecked::>>(); 128 | let authors: Vec = loader 129 | .load_many(self.author_ids.clone()) // TODO cloneやめる 130 | .await? 131 | .into_values() 132 | .collect(); 133 | 134 | Ok(authors) 135 | } 136 | } 137 | 138 | impl From for Book { 139 | fn from(book_dto: BookDto) -> Self { 140 | Self { 141 | id: book_dto.id, 142 | title: book_dto.title, 143 | author_ids: book_dto.author_ids, 144 | isbn: book_dto.isbn, 145 | read: book_dto.read, 146 | owned: book_dto.owned, 147 | priority: book_dto.priority, 148 | format: book_dto.format.into(), 149 | store: book_dto.store.into(), 150 | created_at: book_dto.created_at.unix_timestamp(), 151 | updated_at: book_dto.updated_at.unix_timestamp(), 152 | } 153 | } 154 | } 155 | 156 | #[derive(InputObject)] 157 | pub struct CreateBookInput { 158 | pub title: String, 159 | pub author_ids: Vec, 160 | pub isbn: String, 161 | pub read: bool, 162 | pub owned: bool, 163 | pub priority: i32, 164 | pub format: BookFormat, 165 | pub store: BookStore, 166 | } 167 | 168 | impl From for CreateBookDto { 169 | fn from(book_input: CreateBookInput) -> Self { 170 | let CreateBookInput { 171 | title, 172 | author_ids, 173 | isbn, 174 | read, 175 | owned, 176 | priority, 177 | format, 178 | store, 179 | } = book_input; 180 | 181 | CreateBookDto::new( 182 | title, 183 | author_ids, 184 | isbn, 185 | read, 186 | owned, 187 | priority, 188 | format.into(), 189 | store.into(), 190 | ) 191 | } 192 | } 193 | 194 | #[derive(InputObject)] 195 | pub struct UpdateBookInput { 196 | pub id: String, 197 | pub title: String, 198 | pub author_ids: Vec, 199 | pub isbn: String, 200 | pub read: bool, 201 | pub owned: bool, 202 | pub priority: i32, 203 | pub format: BookFormat, 204 | pub store: BookStore, 205 | } 206 | 207 | impl From for UpdateBookDto { 208 | fn from(book_input: UpdateBookInput) -> Self { 209 | let UpdateBookInput { 210 | id, 211 | title, 212 | author_ids, 213 | isbn, 214 | read, 215 | owned, 216 | priority, 217 | format, 218 | store, 219 | } = book_input; 220 | 221 | UpdateBookDto::new( 222 | id, 223 | title, 224 | author_ids, 225 | isbn, 226 | read, 227 | owned, 228 | priority, 229 | format.into(), 230 | store.into(), 231 | ) 232 | } 233 | } 234 | 235 | #[derive(Debug, Clone, SimpleObject)] 236 | pub struct Author { 237 | pub id: ID, 238 | pub name: String, 239 | } 240 | 241 | impl Author { 242 | pub fn new(id: String, name: String) -> Self { 243 | Self { id: ID(id), name } 244 | } 245 | } 246 | 247 | impl From for Author { 248 | fn from(author: AuthorDto) -> Self { 249 | let AuthorDto { id, name } = author; 250 | Author::new(id, name) 251 | } 252 | } 253 | 254 | #[derive(InputObject)] 255 | pub struct CreateAuthorInput { 256 | pub name: String, 257 | } 258 | 259 | impl CreateAuthorInput { 260 | pub fn new(name: String) -> Self { 261 | Self { name } 262 | } 263 | } 264 | 265 | impl From for CreateAuthorDto { 266 | fn from(val: CreateAuthorInput) -> Self { 267 | CreateAuthorDto::new(val.name) 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /src/presentation/graphql/query.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use async_graphql::{Context, Object, ID}; 4 | 5 | use crate::{ 6 | presentation::{error::PresentationalError, extractor::claims::Claims}, 7 | use_case::traits::query::QueryUseCase, 8 | }; 9 | 10 | use super::object::{Author, Book, User}; 11 | 12 | pub struct Query { 13 | query_use_case: QUC, 14 | } 15 | 16 | impl Query { 17 | pub fn new(query_use_case: QUC) -> Self { 18 | Query { query_use_case } 19 | } 20 | } 21 | 22 | #[Object] 23 | impl Query 24 | where 25 | QUC: QueryUseCase, 26 | { 27 | async fn logged_in_user(&self, ctx: &Context<'_>) -> Result, PresentationalError> { 28 | let claims = get_claims(ctx)?; 29 | let user = self.query_use_case.find_user_by_id(&claims.sub).await?; 30 | Ok(user.map(|user| User::new(ID(user.id)))) 31 | } 32 | 33 | async fn book(&self, ctx: &Context<'_>, id: ID) -> Result, PresentationalError> { 34 | let claims = get_claims(ctx)?; 35 | let book = self 36 | .query_use_case 37 | .find_book_by_id(&claims.sub, id.as_str()) 38 | .await?; 39 | 40 | Ok(book.map(Book::from)) 41 | } 42 | 43 | async fn books(&self, ctx: &Context<'_>) -> Result, PresentationalError> { 44 | let claims = get_claims(ctx)?; 45 | let books = self.query_use_case.find_all_books(&claims.sub).await?; 46 | let books: Vec = books.into_iter().map(Book::from).collect(); 47 | 48 | Ok(books) 49 | } 50 | 51 | async fn author( 52 | &self, 53 | ctx: &Context<'_>, 54 | id: ID, 55 | ) -> Result, PresentationalError> { 56 | let claims = get_claims(ctx)?; 57 | let author = self 58 | .query_use_case 59 | .find_author_by_id(&claims.sub, id.as_str()) 60 | .await?; 61 | Ok(author.map(|author| Author::new(author.id, author.name))) 62 | } 63 | 64 | async fn authors(&self, ctx: &Context<'_>) -> Result, PresentationalError> { 65 | let claims = get_claims(ctx)?; 66 | let authors = self.query_use_case.find_all_authors(&claims.sub).await?; 67 | let authors: Vec = authors.into_iter().map(Author::from).collect(); 68 | Ok(authors) 69 | } 70 | } 71 | 72 | fn get_claims<'a>(ctx: &Context<'a>) -> Result<&'a Claims, PresentationalError> { 73 | ctx.data::() 74 | .map_err(|err| PresentationalError::OtherError(Arc::new(anyhow::anyhow!(err.message)))) 75 | } 76 | -------------------------------------------------------------------------------- /src/presentation/graphql/schema.rs: -------------------------------------------------------------------------------- 1 | use crate::use_case::traits::{mutation::MutationUseCase, query::QueryUseCase}; 2 | 3 | use super::{mutation::Mutation, query::Query}; 4 | use async_graphql::{EmptySubscription, Schema}; 5 | 6 | pub fn build_schema( 7 | query: Query, 8 | mutation: Mutation, 9 | ) -> Schema, Mutation, EmptySubscription> 10 | where 11 | QUC: QueryUseCase, 12 | MUC: MutationUseCase, 13 | { 14 | Schema::build(query, mutation, EmptySubscription).finish() 15 | } 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use mockall::predicate; 20 | 21 | use crate::{ 22 | presentation::{ 23 | extractor::claims::Claims, 24 | graphql::{mutation::Mutation, query::Query}, 25 | }, 26 | use_case::{ 27 | dto::author::AuthorDto, 28 | traits::{mutation::MockMutationUseCase, query::MockQueryUseCase}, 29 | }, 30 | }; 31 | 32 | use super::build_schema; 33 | 34 | #[tokio::test] 35 | async fn execute_query() { 36 | let user_id = "user1"; 37 | let author_id = "d065a358-4fa7-4236-ae19-f6f2f9467c35"; 38 | let author_name = "author1"; 39 | 40 | let mut mock_query_use_case = MockQueryUseCase::new(); 41 | mock_query_use_case 42 | .expect_find_author_by_id() 43 | .with(predicate::eq(user_id), predicate::eq(author_id)) 44 | .times(1) 45 | .returning(|_user_id, author_id| { 46 | Ok(Some(AuthorDto { 47 | id: author_id.to_string(), 48 | name: author_name.to_string(), 49 | })) 50 | }); 51 | let query = Query::new(mock_query_use_case); 52 | let mutation_use_case = MockMutationUseCase::new(); 53 | let mutation = Mutation::new(mutation_use_case); 54 | let schema = build_schema(query, mutation); 55 | let claims = Claims { 56 | sub: user_id.to_string(), 57 | _permissions: None, 58 | }; 59 | let res = schema 60 | .execute( 61 | async_graphql::Request::from( 62 | r#"query { author(id: "d065a358-4fa7-4236-ae19-f6f2f9467c35") {id, name} }"#, 63 | ) 64 | .data(claims), 65 | ) 66 | .await; 67 | let json = serde_json::to_value(&res).unwrap(); 68 | assert_eq!(json["data"]["author"]["name"], author_name); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/presentation/handler.rs: -------------------------------------------------------------------------------- 1 | pub mod graphql; 2 | -------------------------------------------------------------------------------- /src/presentation/handler/graphql.rs: -------------------------------------------------------------------------------- 1 | use async_graphql::{ 2 | dataloader::DataLoader, 3 | http::{playground_source, GraphQLPlaygroundConfig}, 4 | EmptySubscription, Schema, 5 | }; 6 | use async_graphql_axum::{GraphQLRequest, GraphQLResponse}; 7 | use axum::{ 8 | response::{Html, IntoResponse}, 9 | Extension, 10 | }; 11 | 12 | use crate::{ 13 | presentation::{ 14 | extractor::claims::Claims, 15 | graphql::{loader::AuthorLoader, mutation::Mutation, query::Query}, 16 | }, 17 | use_case::traits::{mutation::MutationUseCase, query::QueryUseCase}, 18 | }; 19 | 20 | pub async fn graphql_handler( 21 | claims: Claims, 22 | schema: Extension, Mutation, EmptySubscription>>, 23 | Extension(query_use_case): Extension, 24 | req: GraphQLRequest, 25 | ) -> GraphQLResponse 26 | where 27 | QUC: QueryUseCase + Clone, 28 | MUC: MutationUseCase, 29 | { 30 | let query_use_case: QUC = query_use_case.clone(); 31 | let author_loader = DataLoader::new( 32 | AuthorLoader::new(claims.clone(), query_use_case), 33 | tokio::spawn, 34 | ); 35 | 36 | schema 37 | .execute(req.into_inner().data(claims).data(author_loader)) 38 | .await 39 | .into() 40 | } 41 | 42 | pub async fn graphql_playground_handler() -> impl IntoResponse { 43 | Html(playground_source(GraphQLPlaygroundConfig::new("/graphql"))) 44 | } 45 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Deserialize)] 4 | pub struct Config { 5 | #[serde(default = "default_host")] 6 | pub host: String, 7 | pub port: u16, 8 | pub client_origin_url: String, 9 | } 10 | 11 | fn default_host() -> String { 12 | "127.0.0.1".to_string() 13 | } 14 | 15 | impl Default for Config { 16 | fn default() -> Self { 17 | envy::from_env::().expect("Provide missing environment variables for Config") 18 | } 19 | } 20 | 21 | #[derive(Serialize)] 22 | pub struct ErrorMessage { 23 | #[serde(skip_serializing_if = "Option::is_none")] 24 | pub error: Option, 25 | #[serde(skip_serializing_if = "Option::is_none")] 26 | pub error_description: Option, 27 | pub message: String, 28 | } 29 | -------------------------------------------------------------------------------- /src/use_case.rs: -------------------------------------------------------------------------------- 1 | pub mod dto; 2 | pub mod error; 3 | pub mod interactor; 4 | pub mod traits; 5 | -------------------------------------------------------------------------------- /src/use_case/dto.rs: -------------------------------------------------------------------------------- 1 | pub mod author; 2 | pub mod book; 3 | pub mod user; 4 | -------------------------------------------------------------------------------- /src/use_case/dto/author.rs: -------------------------------------------------------------------------------- 1 | use crate::domain::entity::author::{Author, DestructureAuthor}; 2 | 3 | #[derive(Debug, PartialEq, Eq)] 4 | pub struct AuthorDto { 5 | pub id: String, 6 | pub name: String, 7 | } 8 | 9 | impl From for AuthorDto { 10 | fn from(author: Author) -> Self { 11 | let DestructureAuthor { id, name } = author.destructure(); 12 | AuthorDto { 13 | id: id.to_string(), 14 | name: name.into_string(), 15 | } 16 | } 17 | } 18 | 19 | pub struct CreateAuthorDto { 20 | pub name: String, 21 | } 22 | 23 | impl CreateAuthorDto { 24 | pub fn new(name: String) -> Self { 25 | Self { name } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/use_case/dto/book.rs: -------------------------------------------------------------------------------- 1 | use time::OffsetDateTime; 2 | use uuid::Uuid; 3 | 4 | use crate::{ 5 | common::types::{BookFormat, BookStore}, 6 | domain::{ 7 | entity::{ 8 | author::AuthorId, 9 | book::{Book, BookId, BookTitle, DestructureBook, Isbn, OwnedFlag, Priority, ReadFlag}, 10 | }, 11 | error::DomainError, 12 | }, 13 | use_case::error::UseCaseError, 14 | }; 15 | 16 | #[derive(Debug, Clone)] 17 | pub struct BookDto { 18 | pub id: String, 19 | pub title: String, 20 | pub author_ids: Vec, 21 | pub isbn: String, 22 | pub read: bool, 23 | pub owned: bool, 24 | pub priority: i32, 25 | pub format: BookFormat, 26 | pub store: BookStore, 27 | pub created_at: OffsetDateTime, 28 | pub updated_at: OffsetDateTime, 29 | } 30 | 31 | impl From for BookDto { 32 | fn from(book: Book) -> Self { 33 | let DestructureBook { 34 | id, 35 | title, 36 | author_ids, 37 | isbn, 38 | read, 39 | owned, 40 | priority, 41 | format, 42 | store, 43 | created_at, 44 | updated_at, 45 | } = book.destructure(); 46 | 47 | Self { 48 | id: id.to_string(), 49 | title: title.into_string(), 50 | author_ids: author_ids 51 | .into_iter() 52 | .map(|author_id| author_id.to_string()) 53 | .collect(), 54 | isbn: isbn.into_string(), 55 | read: read.to_bool(), 56 | owned: owned.to_bool(), 57 | priority: priority.to_i32(), 58 | format, 59 | store, 60 | created_at, 61 | updated_at, 62 | } 63 | } 64 | } 65 | 66 | pub struct TimeInfo { 67 | pub created_at: OffsetDateTime, 68 | pub updated_at: OffsetDateTime, 69 | } 70 | 71 | impl TimeInfo { 72 | pub fn new(created_at: OffsetDateTime, updated_at: OffsetDateTime) -> Self { 73 | Self { 74 | created_at, 75 | updated_at, 76 | } 77 | } 78 | } 79 | 80 | #[derive(Debug, Clone)] 81 | pub struct CreateBookDto { 82 | pub title: String, 83 | pub author_ids: Vec, 84 | pub isbn: String, 85 | pub read: bool, 86 | pub owned: bool, 87 | pub priority: i32, 88 | pub format: BookFormat, 89 | pub store: BookStore, 90 | } 91 | 92 | impl CreateBookDto { 93 | #[allow(clippy::too_many_arguments)] 94 | pub fn new( 95 | title: String, 96 | author_ids: Vec, 97 | isbn: String, 98 | read: bool, 99 | owned: bool, 100 | priority: i32, 101 | format: BookFormat, 102 | store: BookStore, 103 | ) -> Self { 104 | Self { 105 | title, 106 | author_ids, 107 | isbn, 108 | read, 109 | owned, 110 | priority, 111 | format, 112 | store, 113 | } 114 | } 115 | } 116 | 117 | impl TryFrom<(Uuid, CreateBookDto, TimeInfo)> for Book { 118 | type Error = UseCaseError; 119 | 120 | fn try_from( 121 | (uuid, book_data, time_info): (Uuid, CreateBookDto, TimeInfo), 122 | ) -> Result { 123 | let author_ids: Result, DomainError> = book_data 124 | .author_ids 125 | .into_iter() 126 | .map(|author_id| AuthorId::try_from(author_id.as_str())) 127 | .collect(); 128 | let author_ids = author_ids?; 129 | 130 | let book = Book::new( 131 | BookId::new(uuid)?, 132 | BookTitle::new(book_data.title)?, 133 | author_ids, 134 | Isbn::new(book_data.isbn)?, 135 | ReadFlag::new(book_data.read), 136 | OwnedFlag::new(book_data.owned), 137 | Priority::new(book_data.priority)?, 138 | book_data.format, 139 | book_data.store, 140 | time_info.created_at, 141 | time_info.updated_at, 142 | )?; 143 | 144 | Ok(book) 145 | } 146 | } 147 | 148 | #[derive(Debug, Clone)] 149 | pub struct UpdateBookDto { 150 | pub id: String, 151 | pub title: String, 152 | pub author_ids: Vec, 153 | pub isbn: String, 154 | pub read: bool, 155 | pub owned: bool, 156 | pub priority: i32, 157 | pub format: BookFormat, 158 | pub store: BookStore, 159 | } 160 | 161 | impl UpdateBookDto { 162 | #[allow(clippy::too_many_arguments)] 163 | pub fn new( 164 | id: String, 165 | title: String, 166 | author_ids: Vec, 167 | isbn: String, 168 | read: bool, 169 | owned: bool, 170 | priority: i32, 171 | format: BookFormat, 172 | store: BookStore, 173 | ) -> Self { 174 | Self { 175 | id, 176 | title, 177 | author_ids, 178 | isbn, 179 | read, 180 | owned, 181 | priority, 182 | format, 183 | store, 184 | } 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/use_case/dto/user.rs: -------------------------------------------------------------------------------- 1 | use crate::domain::entity::user::User as DomainUser; 2 | 3 | pub struct UserDto { 4 | pub id: String, 5 | } 6 | 7 | impl UserDto { 8 | pub fn new(id: String) -> Self { 9 | Self { id } 10 | } 11 | } 12 | 13 | impl From for UserDto { 14 | fn from(user: DomainUser) -> Self { 15 | UserDto::new(user.id.into_string()) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/use_case/error.rs: -------------------------------------------------------------------------------- 1 | use thiserror::Error; 2 | 3 | use crate::domain::error::DomainError; 4 | 5 | #[derive(Debug, Error)] 6 | pub enum UseCaseError { 7 | #[error("{0}")] 8 | Validation(String), 9 | #[error(r#"{entity_type} was not found for entity_id "{entity_id}" and user_id "{user_id}"."#)] 10 | NotFound { 11 | entity_type: &'static str, 12 | entity_id: String, 13 | user_id: String, 14 | }, 15 | #[error(transparent)] 16 | Other(anyhow::Error), 17 | #[error("{0}")] 18 | Unexpected(String), 19 | } 20 | 21 | impl From for UseCaseError { 22 | fn from(err: DomainError) -> Self { 23 | match err { 24 | DomainError::Validation(message) => UseCaseError::Validation(message), 25 | DomainError::NotFound { 26 | entity_type, 27 | entity_id, 28 | user_id, 29 | } => UseCaseError::NotFound { 30 | entity_type, 31 | entity_id, 32 | user_id, 33 | }, 34 | DomainError::InfrastructureError(_) => UseCaseError::Other(anyhow::Error::new(err)), 35 | DomainError::Unexpected(message) => UseCaseError::Unexpected(message), 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/use_case/interactor.rs: -------------------------------------------------------------------------------- 1 | pub mod author; 2 | pub mod book; 3 | pub mod mutation; 4 | pub mod query; 5 | pub mod user; 6 | -------------------------------------------------------------------------------- /src/use_case/interactor/author.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use uuid::Uuid; 3 | 4 | use crate::{ 5 | domain::{ 6 | entity::{ 7 | author::{Author, AuthorId, AuthorName}, 8 | user::UserId, 9 | }, 10 | repository::author_repository::AuthorRepository, 11 | }, 12 | use_case::{ 13 | dto::author::{AuthorDto, CreateAuthorDto}, 14 | error::UseCaseError, 15 | traits::author::CreateAuthorUseCase, 16 | }, 17 | }; 18 | 19 | pub struct CreateAuthorInteractor { 20 | author_repository: AR, 21 | } 22 | 23 | impl CreateAuthorInteractor { 24 | pub fn new(author_repository: AR) -> Self { 25 | Self { author_repository } 26 | } 27 | } 28 | 29 | #[async_trait] 30 | impl CreateAuthorUseCase for CreateAuthorInteractor 31 | where 32 | AR: AuthorRepository, 33 | { 34 | async fn create( 35 | &self, 36 | user_id: &str, 37 | author_data: CreateAuthorDto, 38 | ) -> Result { 39 | let user_id = UserId::new(user_id.to_string())?; 40 | let uuid = Uuid::new_v4(); 41 | let author_id = AuthorId::new(uuid); 42 | let author_name = AuthorName::new(author_data.name)?; 43 | let author = Author::new(author_id, author_name)?; 44 | self.author_repository.create(&user_id, &author).await?; 45 | 46 | Ok(author.into()) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/use_case/interactor/book.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use time::OffsetDateTime; 3 | use uuid::Uuid; 4 | 5 | use crate::{ 6 | domain::{ 7 | entity::{ 8 | author::AuthorId, 9 | book::{Book, BookId, BookTitle, Isbn, OwnedFlag, Priority, ReadFlag}, 10 | user::UserId, 11 | }, 12 | error::DomainError, 13 | repository::book_repository::BookRepository, 14 | }, 15 | use_case::{ 16 | dto::book::{BookDto, CreateBookDto, TimeInfo, UpdateBookDto}, 17 | error::UseCaseError, 18 | traits::book::{CreateBookUseCase, DeleteBookUseCase, UpdateBookUseCase}, 19 | }, 20 | }; 21 | 22 | pub struct CreateBookInteractor
{ 23 | book_repository: BR, 24 | } 25 | 26 | impl
CreateBookInteractor
{ 27 | pub fn new(book_repository: BR) -> Self { 28 | Self { book_repository } 29 | } 30 | } 31 | 32 | #[async_trait] 33 | impl
CreateBookUseCase for CreateBookInteractor
34 | where 35 | BR: BookRepository, 36 | { 37 | async fn create( 38 | &self, 39 | user_id: &str, 40 | book_data: CreateBookDto, 41 | ) -> Result { 42 | let user_id = UserId::new(user_id.to_string())?; 43 | let uuid = Uuid::new_v4(); 44 | let time_info = TimeInfo::new(OffsetDateTime::now_utc(), OffsetDateTime::now_utc()); 45 | let book = Book::try_from((uuid, book_data, time_info))?; 46 | 47 | self.book_repository.create(&user_id, &book).await?; 48 | 49 | Ok(book.into()) 50 | } 51 | } 52 | 53 | pub struct UpdateBookInteractor
{ 54 | book_repository: BR, 55 | } 56 | 57 | impl
UpdateBookInteractor
{ 58 | pub fn new(book_repository: BR) -> Self { 59 | Self { book_repository } 60 | } 61 | } 62 | 63 | #[async_trait] 64 | impl
UpdateBookUseCase for UpdateBookInteractor
65 | where 66 | BR: BookRepository, 67 | { 68 | async fn update( 69 | &self, 70 | user_id: &str, 71 | book_data: UpdateBookDto, 72 | ) -> Result { 73 | let user_id = UserId::new(user_id.to_string())?; 74 | let book_id = BookId::try_from(book_data.id.as_str())?; 75 | let book = self.book_repository.find_by_id(&user_id, &book_id).await?; 76 | let mut book = match book { 77 | Some(book) => book, 78 | None => { 79 | return Err(UseCaseError::NotFound { 80 | entity_type: "book", 81 | entity_id: book_data.id, 82 | user_id: user_id.into_string(), 83 | }) 84 | } 85 | }; 86 | 87 | let title = BookTitle::new(book_data.title)?; 88 | let author_ids: Result, DomainError> = book_data 89 | .author_ids 90 | .into_iter() 91 | .map(|author_id| AuthorId::try_from(author_id.as_str())) 92 | .collect(); 93 | let author_ids = author_ids?; 94 | let isbn = Isbn::new(book_data.isbn)?; 95 | let read = ReadFlag::new(book_data.read); 96 | let owned = OwnedFlag::new(book_data.owned); 97 | let priority = Priority::new(book_data.priority)?; 98 | let format = book_data.format; 99 | let store = book_data.store; 100 | 101 | book.set_title(title); 102 | book.set_author_ids(author_ids); 103 | book.set_isbn(isbn); 104 | book.set_read(read); 105 | book.set_owned(owned); 106 | book.set_priority(priority); 107 | book.set_format(format); 108 | book.set_store(store); 109 | book.set_updated_at(OffsetDateTime::now_utc()); 110 | 111 | self.book_repository.update(&user_id, &book).await?; 112 | 113 | Ok(book.into()) 114 | } 115 | } 116 | 117 | pub struct DeleteBookInteractor
{ 118 | book_repository: BR, 119 | } 120 | 121 | impl
DeleteBookInteractor
{ 122 | pub fn new(book_repository: BR) -> Self { 123 | Self { book_repository } 124 | } 125 | } 126 | 127 | #[async_trait] 128 | impl
DeleteBookUseCase for DeleteBookInteractor
129 | where 130 | BR: BookRepository, 131 | { 132 | async fn delete(&self, user_id: &str, book_id: &str) -> Result<(), UseCaseError> { 133 | let user_id = UserId::new(user_id.to_string())?; 134 | let book_id = BookId::try_from(book_id)?; 135 | 136 | self.book_repository.delete(&user_id, &book_id).await?; 137 | 138 | Ok(()) 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/use_case/interactor/mutation.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | 3 | use crate::use_case::{ 4 | dto::{ 5 | author::{AuthorDto, CreateAuthorDto}, 6 | book::{BookDto, CreateBookDto, UpdateBookDto}, 7 | user::UserDto, 8 | }, 9 | error::UseCaseError, 10 | traits::{ 11 | author::CreateAuthorUseCase, 12 | book::{CreateBookUseCase, DeleteBookUseCase, UpdateBookUseCase}, 13 | mutation::MutationUseCase, 14 | user::RegisterUserUseCase, 15 | }, 16 | }; 17 | 18 | pub struct MutationInteractor { 19 | register_user_use_case: RUUC, 20 | create_book_use_case: CBUC, 21 | update_book_use_case: UBUC, 22 | delete_book_use_case: DBUC, 23 | create_author_use_case: CAUC, 24 | } 25 | 26 | impl MutationInteractor { 27 | pub fn new( 28 | register_user_use_case: RUUC, 29 | create_book_use_case: CBUC, 30 | update_book_use_case: UBUC, 31 | delete_book_use_case: DBUC, 32 | create_author_use_case: CAUC, 33 | ) -> Self { 34 | Self { 35 | register_user_use_case, 36 | create_book_use_case, 37 | update_book_use_case, 38 | delete_book_use_case, 39 | create_author_use_case, 40 | } 41 | } 42 | } 43 | 44 | #[async_trait] 45 | impl MutationUseCase 46 | for MutationInteractor 47 | where 48 | RUUC: RegisterUserUseCase, 49 | CBUC: CreateBookUseCase, 50 | UBUC: UpdateBookUseCase, 51 | DBUC: DeleteBookUseCase, 52 | CAUC: CreateAuthorUseCase, 53 | { 54 | async fn register_user(&self, user_id: &str) -> Result { 55 | let user = self.register_user_use_case.register_user(user_id).await?; 56 | Ok(user) 57 | } 58 | 59 | async fn create_book( 60 | &self, 61 | user_id: &str, 62 | book_data: CreateBookDto, 63 | ) -> Result { 64 | let book = self.create_book_use_case.create(user_id, book_data).await?; 65 | Ok(book) 66 | } 67 | 68 | async fn update_book( 69 | &self, 70 | user_id: &str, 71 | book_data: UpdateBookDto, 72 | ) -> Result { 73 | let book = self.update_book_use_case.update(user_id, book_data).await?; 74 | Ok(book) 75 | } 76 | 77 | async fn delete_book(&self, user_id: &str, book_id: &str) -> Result<(), UseCaseError> { 78 | self.delete_book_use_case.delete(user_id, book_id).await?; 79 | Ok(()) 80 | } 81 | 82 | async fn create_author( 83 | &self, 84 | user_id: &str, 85 | author_data: CreateAuthorDto, 86 | ) -> Result { 87 | let author = self 88 | .create_author_use_case 89 | .create(user_id, author_data) 90 | .await?; 91 | Ok(author) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/use_case/interactor/query.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use async_trait::async_trait; 4 | 5 | use crate::{ 6 | domain::{ 7 | entity::{author::AuthorId, book::BookId, user::UserId}, 8 | error::DomainError, 9 | repository::{ 10 | author_repository::AuthorRepository, book_repository::BookRepository, 11 | user_repository::UserRepository, 12 | }, 13 | }, 14 | use_case::{ 15 | dto::{author::AuthorDto, book::BookDto, user::UserDto}, 16 | error::UseCaseError, 17 | traits::query::QueryUseCase, 18 | }, 19 | }; 20 | 21 | #[derive(Debug, Clone)] 22 | pub struct QueryInteractor { 23 | pub user_repository: UR, 24 | pub book_repository: BR, 25 | pub author_repository: AR, 26 | } 27 | 28 | #[async_trait] 29 | impl QueryUseCase for QueryInteractor 30 | where 31 | UR: UserRepository, 32 | BR: BookRepository, 33 | AR: AuthorRepository, 34 | { 35 | async fn find_user_by_id(&self, raw_user_id: &str) -> Result, UseCaseError> { 36 | let user_id = UserId::new(raw_user_id.to_string())?; 37 | let user = self.user_repository.find_by_id(&user_id).await?; 38 | 39 | Ok(user.map(|user| UserDto::new(user.id.into_string()))) 40 | } 41 | 42 | async fn find_book_by_id( 43 | &self, 44 | user_id: &str, 45 | book_id: &str, 46 | ) -> Result, UseCaseError> { 47 | let user_id = UserId::new(user_id.to_string())?; 48 | let book_id = BookId::try_from(book_id)?; 49 | let book = self.book_repository.find_by_id(&user_id, &book_id).await?; 50 | let book = book.map(BookDto::from); 51 | Ok(book) 52 | } 53 | 54 | async fn find_all_books(&self, user_id: &str) -> Result, UseCaseError> { 55 | let user_id = UserId::new(user_id.to_string())?; 56 | let books = self.book_repository.find_all(&user_id).await?; 57 | let books: Vec = books.into_iter().map(BookDto::from).collect(); 58 | Ok(books) 59 | } 60 | 61 | async fn find_author_by_id( 62 | &self, 63 | user_id: &str, 64 | author_id: &str, 65 | ) -> Result, UseCaseError> { 66 | let raw_user_id = user_id; 67 | let raw_author_id = author_id; 68 | let user_id = UserId::new(raw_user_id.to_string())?; 69 | let author_id = AuthorId::try_from(raw_author_id)?; 70 | let author = self 71 | .author_repository 72 | .find_by_id(&user_id, &author_id) 73 | .await?; 74 | 75 | Ok(author.map(AuthorDto::from)) 76 | } 77 | 78 | async fn find_all_authors(&self, user_id: &str) -> Result, UseCaseError> { 79 | let user_id = UserId::new(user_id.to_string())?; 80 | let authors = self.author_repository.find_all(&user_id).await?; 81 | let authors: Vec = authors.into_iter().map(AuthorDto::from).collect(); 82 | Ok(authors) 83 | } 84 | 85 | async fn find_author_by_ids_as_hash_map( 86 | &self, 87 | user_id: &str, 88 | author_ids: &[String], 89 | ) -> Result, UseCaseError> { 90 | let user_id = UserId::new(user_id.to_string())?; 91 | let author_ids: Vec = author_ids 92 | .iter() 93 | .map(|author_id| AuthorId::try_from(author_id.as_str())) 94 | .collect::, DomainError>>()?; 95 | let authors_map = self 96 | .author_repository 97 | .find_by_ids_as_hash_map(&user_id, &author_ids) 98 | .await?; 99 | let authors_map = authors_map 100 | .into_iter() 101 | .map(|(author_id, author)| (author_id.to_string(), author.into())) 102 | .collect(); 103 | 104 | Ok(authors_map) 105 | } 106 | } 107 | 108 | #[cfg(test)] 109 | mod tests { 110 | 111 | use mockall::predicate::always; 112 | 113 | use crate::{ 114 | domain::{ 115 | self, 116 | entity::author::{AuthorId, AuthorName}, 117 | repository::{ 118 | author_repository::MockAuthorRepository, book_repository::MockBookRepository, 119 | user_repository::MockUserRepository, 120 | }, 121 | }, 122 | use_case::{ 123 | dto::author::AuthorDto, interactor::query::QueryInteractor, traits::query::QueryUseCase, 124 | }, 125 | }; 126 | 127 | #[tokio::test] 128 | async fn find_author_by_id() { 129 | let user_repository = MockUserRepository::new(); 130 | let book_repository = MockBookRepository::new(); 131 | let mut author_repository = MockAuthorRepository::new(); 132 | 133 | let user_id = "user1"; 134 | let author_id = "006099b4-6c42-4ec4-8645-f6bd5b63eddc"; 135 | let author_name = "author1"; 136 | 137 | author_repository 138 | .expect_find_by_id() 139 | .with(always(), always()) 140 | .returning(move |_, _| { 141 | Ok(Some(domain::entity::author::Author::new( 142 | AuthorId::try_from(author_id).unwrap(), 143 | AuthorName::new(author_name.to_string()).unwrap(), 144 | )?)) 145 | }); 146 | 147 | let query_interactor = QueryInteractor { 148 | user_repository, 149 | book_repository, 150 | author_repository, 151 | }; 152 | 153 | let actual = query_interactor 154 | .find_author_by_id(user_id, author_id) 155 | .await 156 | .unwrap(); 157 | 158 | let expected = Some(AuthorDto { 159 | id: author_id.to_owned(), 160 | name: author_name.to_owned(), 161 | }); 162 | 163 | assert_eq!(actual, expected); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/use_case/interactor/user.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | 3 | use crate::{ 4 | domain::{ 5 | entity::user::{User as DomainUser, UserId}, 6 | repository::user_repository::UserRepository, 7 | }, 8 | use_case::{dto::user::UserDto, error::UseCaseError, traits::user::RegisterUserUseCase}, 9 | }; 10 | 11 | pub struct RegisterUserInteractor { 12 | user_repository: UR, 13 | } 14 | 15 | impl RegisterUserInteractor { 16 | pub fn new(user_repository: UR) -> Self { 17 | Self { user_repository } 18 | } 19 | } 20 | 21 | #[async_trait] 22 | impl RegisterUserUseCase for RegisterUserInteractor 23 | where 24 | UR: UserRepository, 25 | { 26 | async fn register_user(&self, user_id: &str) -> Result { 27 | let user_id = UserId::new(user_id.to_string())?; 28 | let user = DomainUser::new(user_id); 29 | self.user_repository.create(&user).await?; 30 | Ok(UserDto::new(user.id.into_string())) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/use_case/traits.rs: -------------------------------------------------------------------------------- 1 | pub mod author; 2 | pub mod book; 3 | pub mod mutation; 4 | pub mod query; 5 | pub mod user; 6 | -------------------------------------------------------------------------------- /src/use_case/traits/author.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use mockall::automock; 3 | 4 | use crate::use_case::{ 5 | dto::author::{AuthorDto, CreateAuthorDto}, 6 | error::UseCaseError, 7 | }; 8 | 9 | #[automock] 10 | #[async_trait] 11 | pub trait CreateAuthorUseCase: Send + Sync + 'static { 12 | async fn create( 13 | &self, 14 | user_id: &str, 15 | author_data: CreateAuthorDto, 16 | ) -> Result; 17 | } 18 | -------------------------------------------------------------------------------- /src/use_case/traits/book.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use mockall::automock; 3 | 4 | use crate::use_case::{ 5 | dto::book::{BookDto, CreateBookDto, UpdateBookDto}, 6 | error::UseCaseError, 7 | }; 8 | 9 | #[automock] 10 | #[async_trait] 11 | pub trait CreateBookUseCase: Send + Sync + 'static { 12 | async fn create( 13 | &self, 14 | user_id: &str, 15 | book_data: CreateBookDto, 16 | ) -> Result; 17 | } 18 | 19 | #[automock] 20 | #[async_trait] 21 | pub trait UpdateBookUseCase: Send + Sync + 'static { 22 | async fn update( 23 | &self, 24 | user_id: &str, 25 | book_data: UpdateBookDto, 26 | ) -> Result; 27 | } 28 | 29 | #[automock] 30 | #[async_trait] 31 | pub trait DeleteBookUseCase: Send + Sync + 'static { 32 | async fn delete(&self, user_id: &str, book_id: &str) -> Result<(), UseCaseError>; 33 | } 34 | -------------------------------------------------------------------------------- /src/use_case/traits/mutation.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use mockall::automock; 3 | 4 | use crate::use_case::{ 5 | dto::{ 6 | author::{AuthorDto, CreateAuthorDto}, 7 | book::{BookDto, CreateBookDto, UpdateBookDto}, 8 | user::UserDto, 9 | }, 10 | error::UseCaseError, 11 | }; 12 | 13 | #[automock] 14 | #[async_trait] 15 | pub trait MutationUseCase: Send + Sync + 'static { 16 | async fn register_user(&self, user_id: &str) -> Result; 17 | async fn create_book( 18 | &self, 19 | user_id: &str, 20 | book_data: CreateBookDto, 21 | ) -> Result; 22 | async fn update_book( 23 | &self, 24 | user_id: &str, 25 | book_data: UpdateBookDto, 26 | ) -> Result; 27 | async fn delete_book(&self, user_id: &str, book_id: &str) -> Result<(), UseCaseError>; 28 | async fn create_author( 29 | &self, 30 | user_id: &str, 31 | author_data: CreateAuthorDto, 32 | ) -> Result; 33 | } 34 | -------------------------------------------------------------------------------- /src/use_case/traits/query.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use async_trait::async_trait; 4 | use mockall::automock; 5 | 6 | use crate::use_case::{ 7 | dto::{author::AuthorDto, book::BookDto, user::UserDto}, 8 | error::UseCaseError, 9 | }; 10 | 11 | #[automock] 12 | #[async_trait] 13 | pub trait QueryUseCase: Send + Sync + 'static { 14 | async fn find_user_by_id(&self, user_id: &str) -> Result, UseCaseError>; 15 | async fn find_book_by_id( 16 | &self, 17 | user_id: &str, 18 | book_id: &str, 19 | ) -> Result, UseCaseError>; 20 | async fn find_all_books(&self, user_id: &str) -> Result, UseCaseError>; 21 | async fn find_author_by_id( 22 | &self, 23 | user_id: &str, 24 | author_id: &str, 25 | ) -> Result, UseCaseError>; 26 | async fn find_all_authors(&self, user_id: &str) -> Result, UseCaseError>; 27 | async fn find_author_by_ids_as_hash_map( 28 | &self, 29 | user_id: &str, 30 | author_ids: &[String], 31 | ) -> Result, UseCaseError>; 32 | } 33 | -------------------------------------------------------------------------------- /src/use_case/traits/user.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | 3 | use crate::use_case::{dto::user::UserDto, error::UseCaseError}; 4 | 5 | #[async_trait] 6 | pub trait RegisterUserUseCase: Send + Sync + 'static { 7 | async fn register_user(&self, user_id: &str) -> Result; 8 | } 9 | -------------------------------------------------------------------------------- /testdata/testdata.sql: -------------------------------------------------------------------------------- 1 | BEGIN; 2 | 3 | INSERT INTO bookshelf_user (id) VALUES ('testuser1'); 4 | 5 | INSERT INTO author 6 | (id, user_id, name) 7 | VALUES 8 | ('9d548ede-f636-4890-8418-ad3b7336d8e3', 'testuser1', 'author1'); 9 | INSERT INTO author 10 | (id, user_id, name) 11 | VALUES 12 | ('54bbfcd2-e937-4da5-84fc-5984fa7b5979', 'testuser1', 'author2'); 13 | 14 | INSERT INTO book ( 15 | id, 16 | user_id, 17 | title, 18 | isbn, 19 | read, 20 | owned, 21 | priority, 22 | format, 23 | store 24 | ) 25 | VALUES ( 26 | 'd85f0e56-f632-4d50-b057-bab5af3d0159', 27 | 'testuser1', 28 | 'title1', 29 | '2222222222222', 30 | false, 31 | false, 32 | 50, 33 | 'eBook', 34 | 'Kindle' 35 | ); 36 | 37 | INSERT INTO book_author (user_id, book_id, author_id) VALUES 38 | ('testuser1', 'd85f0e56-f632-4d50-b057-bab5af3d0159', '9d548ede-f636-4890-8418-ad3b7336d8e3'), 39 | ('testuser1', 'd85f0e56-f632-4d50-b057-bab5af3d0159', '54bbfcd2-e937-4da5-84fc-5984fa7b5979'); 40 | 41 | COMMIT; 42 | --------------------------------------------------------------------------------