Initial commit: Project setup with frontend and backend

This commit is contained in:
continuist 2025-06-16 00:40:45 -04:00
commit eb1e9c27ed
67 changed files with 11550 additions and 0 deletions

54
.gitignore vendored Normal file
View file

@ -0,0 +1,54 @@
# Rust
**/*/target/
**/*.rs.bk
Cargo.lock
# Node.js
**/*/node_modules/
**/*/.next/
**/*/.pnp
**/*/.pnp.*
**/*/.yarn/*
!**/*/.yarn/patches
!**/*/.yarn/plugins
!**/*/.yarn/releases
!**/*/.yarn/versions
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# Testing
**/*/coverage/
# Next.js
**/*/out/
# Production
**/*/build/
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
*.pem
# Build outputs
dist/
build/
*.log
# Environment files
**/*/.env*
# Vercel
**/*/.vercel
# TypeScript
**/*/*.tsbuildinfo
**/*/next-env.d.ts

170
LICENSE.md Normal file
View file

@ -0,0 +1,170 @@
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. Additional offer from the Licensor Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

37
backend/Cargo.toml Normal file
View file

@ -0,0 +1,37 @@
[workspace]
members = [
"crates/*",
]
resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
authors = ["Continuist <continuist02@gmail.com>"]
license = "CC-BY-NC-4.0"
[workspace.dependencies]
tokio = { version = "1.36", features = ["full"] }
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "1.7", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
thiserror = "1.0"
clap = { version = "4.5", features = ["derive"] }
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono"] }
axum = "0.7"
tower = "0.4"
tower-http = { version = "0.5", features = ["trace", "cors"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
dotenvy = "0.15"
ratatui = "0.24"
crossterm = "0.27"
textwrap = "0.16"
[profile.release]
lto = true
opt-level = 3
codegen-units = 1
strip = true

101
backend/README.md Normal file
View file

@ -0,0 +1,101 @@
# Sharenet
A Rust backend for performing CRUD operations on various struct types (e.g., products, users) that uses a clean architecture with configurable storage and interface layers.
## Features
- Clean architecture with separate domain, application, and infrastructure layers
- Support for both HTTP REST API and CLI interfaces
- Configurable storage backends (in-memory or PostgreSQL)
- Generic implementations for easy extension
- Static dispatch with generic traits
- Axum-based HTTP API
- Clap-based CLI
## Project Structure
```
.
├── domain/ # Domain entities and traits
├── application/ # Application services and use cases
├── api/ # HTTP API implementation (Axum)
├── cli/ # CLI implementation (Clap)
├── memory/ # In-memory storage implementation
├── postgres/ # PostgreSQL storage implementation
└── src/ # Binary crate
```
## Building
```bash
cargo build
```
## Running
### HTTP API with in-memory storage
```bash
cargo run -- --api --addr 127.0.0.1:3000
```
### HTTP API with PostgreSQL
```bash
cargo run -- --api --postgres --database-url postgres://user:password@localhost/dbname --addr 127.0.0.1:3000
```
### CLI with in-memory storage
```bash
cargo run -- user create --username john --email john@example.com
cargo run -- user list
cargo run -- product create --name "Product 1" --description "Description" --price 99.99
cargo run -- product list
```
### CLI with PostgreSQL
```bash
cargo run -- --postgres --database-url postgres://user:password@localhost/dbname user create --username john --email john@example.com
```
## API Endpoints
### Users
- `POST /users` - Create a new user
- `GET /users/:id` - Get a user by ID
- `GET /users` - List all users
- `PUT /users/:id` - Update a user
- `DELETE /users/:id` - Delete a user
### Products
- `POST /products` - Create a new product
- `GET /products/:id` - Get a product by ID
- `GET /products` - List all products
- `PUT /products/:id` - Update a product
- `DELETE /products/:id` - Delete a product
## CLI Commands
### Users
- `user create --username <username> --email <email>` - Create a new user
- `user get --id <id>` - Get a user by ID
- `user list` - List all users
- `user update --id <id> [--username <username>] [--email <email>]` - Update a user
- `user delete --id <id>` - Delete a user
### Products
- `product create --name <name> --description <description> --price <price>` - Create a new product
- `product get --id <id>` - Get a product by ID
- `product list` - List all products
- `product update --id <id> [--name <name>] [--description <description>] [--price <price>]` - Update a product
- `product delete --id <id>` - Delete a product
## License
MIT

View file

@ -0,0 +1,5 @@
# Server Configuration
SERVER_ADDR=127.0.0.1:3000
# Optional: Logging Configuration
RUST_LOG=info

View file

@ -0,0 +1,8 @@
# Server Configuration
SERVER_ADDR=127.0.0.1:3000
# Database Configuration
DATABASE_URL=postgres://postgres:password@localhost:5432/pylon
# Optional: Logging Configuration
RUST_LOG=info

View file

@ -0,0 +1,2 @@
# Optional: Logging Configuration
RUST_LOG=info

View file

@ -0,0 +1,5 @@
# Database Configuration
DATABASE_URL=postgres://postgres:password@localhost:5432/pylon
# Optional: Logging Configuration
RUST_LOG=info

View file

@ -0,0 +1,2 @@
# Memory TUI Configuration
RUST_LOG=info

View file

@ -0,0 +1,3 @@
# Postgres TUI Configuration
RUST_LOG=info
DATABASE_URL=postgres://postgres:password@localhost:5432/pylon

View file

@ -0,0 +1,19 @@
[package]
name = "api"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
application = { path = "../application" }
axum = { workspace = true }
tokio = { workspace = true }
tower = "0.4"
tower-http = { version = "0.5", features = ["trace", "cors"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
serde = { workspace = true }
serde_json = "1.0"
uuid = { workspace = true }

View file

@ -0,0 +1,207 @@
use std::net::SocketAddr;
use std::sync::Arc;
use application::UseCase;
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, post, put},
Json, Router,
};
use domain::{CreateProduct, CreateUser, Product, UpdateProduct, UpdateUser, User};
use tower_http::trace::TraceLayer;
use tower_http::cors::{CorsLayer, Any};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, filter::EnvFilter};
use uuid::Uuid;
pub struct AppState<U, P> {
user_service: Arc<U>,
product_service: Arc<P>,
}
impl<U, P> Clone for AppState<U, P>
where
U: Clone,
P: Clone,
{
fn clone(&self) -> Self {
Self {
user_service: self.user_service.clone(),
product_service: self.product_service.clone(),
}
}
}
pub async fn run<U, P>(addr: SocketAddr, user_service: U, product_service: P)
where
U: UseCase<User> + Clone + Send + Sync + 'static,
P: UseCase<Product> + Clone + Send + Sync + 'static,
{
tracing_subscriber::registry()
.with(EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
let state = AppState {
user_service: Arc::new(user_service),
product_service: Arc::new(product_service),
};
// Configure CORS
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/users", post(create_user::<U>))
.route("/users/:id", get(get_user::<U>))
.route("/users", get(list_users::<U>))
.route("/users/:id", put(update_user::<U>))
.route("/users/:id", delete(delete_user::<U>))
.route("/products", post(create_product::<P>))
.route("/products/:id", get(get_product::<P>))
.route("/products", get(list_products::<P>))
.route("/products/:id", put(update_product::<P>))
.route("/products/:id", delete(delete_product::<P>))
.layer(cors)
.layer(TraceLayer::new_for_http())
.with_state(state);
tracing::info!("listening on {}", addr);
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn create_user<U>(
State(state): State<AppState<U, impl UseCase<Product>>>,
Json(data): Json<CreateUser>,
) -> impl IntoResponse
where
U: UseCase<User>,
{
match state.user_service.create(data).await {
Ok(user) => (StatusCode::CREATED, Json(user)).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn get_user<U>(
State(state): State<AppState<U, impl UseCase<Product>>>,
Path(id): Path<Uuid>,
) -> impl IntoResponse
where
U: UseCase<User>,
{
match state.user_service.get(id).await {
Ok(user) => (StatusCode::OK, Json(user)).into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
async fn list_users<U>(
State(state): State<AppState<U, impl UseCase<Product>>>,
) -> impl IntoResponse
where
U: UseCase<User>,
{
match state.user_service.list().await {
Ok(users) => (StatusCode::OK, Json(users)).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn update_user<U>(
State(state): State<AppState<U, impl UseCase<Product>>>,
Path(id): Path<Uuid>,
Json(data): Json<UpdateUser>,
) -> impl IntoResponse
where
U: UseCase<User>,
{
match state.user_service.update(id, data).await {
Ok(user) => (StatusCode::OK, Json(user)).into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
async fn delete_user<U>(
State(state): State<AppState<U, impl UseCase<Product>>>,
Path(id): Path<Uuid>,
) -> impl IntoResponse
where
U: UseCase<User>,
{
match state.user_service.delete(id).await {
Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
async fn create_product<P>(
State(state): State<AppState<impl UseCase<User>, P>>,
Json(data): Json<CreateProduct>,
) -> impl IntoResponse
where
P: UseCase<Product>,
{
match state.product_service.create(data).await {
Ok(product) => (StatusCode::CREATED, Json(product)).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn get_product<P>(
State(state): State<AppState<impl UseCase<User>, P>>,
Path(id): Path<Uuid>,
) -> impl IntoResponse
where
P: UseCase<Product>,
{
match state.product_service.get(id).await {
Ok(product) => (StatusCode::OK, Json(product)).into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
async fn list_products<P>(
State(state): State<AppState<impl UseCase<User>, P>>,
) -> impl IntoResponse
where
P: UseCase<Product>,
{
match state.product_service.list().await {
Ok(products) => (StatusCode::OK, Json(products)).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
async fn update_product<P>(
State(state): State<AppState<impl UseCase<User>, P>>,
Path(id): Path<Uuid>,
Json(data): Json<UpdateProduct>,
) -> impl IntoResponse
where
P: UseCase<Product>,
{
match state.product_service.update(id, data).await {
Ok(product) => (StatusCode::OK, Json(product)).into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
async fn delete_product<P>(
State(state): State<AppState<impl UseCase<User>, P>>,
Path(id): Path<Uuid>,
) -> impl IntoResponse
where
P: UseCase<Product>,
{
match state.product_service.delete(id).await {
Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(e) => (StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}

View file

@ -0,0 +1,11 @@
[package]
name = "application"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
thiserror = { workspace = true }
uuid = { workspace = true }

View file

@ -0,0 +1,78 @@
use domain::{Result, Entity};
use thiserror::Error;
use uuid::Uuid;
use std::marker::PhantomData;
use std::future::Future;
#[derive(Debug, Error)]
pub enum ApplicationError {
#[error("Domain error: {0}")]
Domain(#[from] domain::DomainError),
#[error("Repository error: {0}")]
Repository(String),
}
pub type AppResult<T> = std::result::Result<T, ApplicationError>;
pub trait Repository<T: Entity>: Send + Sync {
fn create(&self, data: T::Create) -> impl Future<Output = Result<T>> + Send;
fn find_by_id(&self, id: Uuid) -> impl Future<Output = Result<T>> + Send;
fn find_all(&self) -> impl Future<Output = Result<Vec<T>>> + Send;
fn update(&self, id: Uuid, data: T::Update) -> impl Future<Output = Result<T>> + Send;
fn delete(&self, id: Uuid) -> impl Future<Output = Result<()>> + Send;
}
pub trait UseCase<T: Entity> {
fn create(&self, data: T::Create) -> impl Future<Output = AppResult<T>> + Send;
fn get(&self, id: Uuid) -> impl Future<Output = AppResult<T>> + Send;
fn list(&self) -> impl Future<Output = AppResult<Vec<T>>> + Send;
fn update(&self, id: Uuid, data: T::Update) -> impl Future<Output = AppResult<T>> + Send;
fn delete(&self, id: Uuid) -> impl Future<Output = AppResult<()>> + Send;
}
#[derive(Clone)]
pub struct Service<T: Entity, R: Repository<T> + Clone> {
repository: R,
_phantom: PhantomData<T>,
}
impl<T: Entity, R: Repository<T> + Clone> Service<T, R> {
pub fn new(repository: R) -> Self {
Self {
repository,
_phantom: PhantomData,
}
}
}
impl<T: Entity, R: Repository<T> + Clone> UseCase<T> for Service<T, R> {
fn create(&self, data: T::Create) -> impl Future<Output = AppResult<T>> + Send {
async move {
self.repository.create(data).await.map_err(ApplicationError::Domain)
}
}
fn get(&self, id: Uuid) -> impl Future<Output = AppResult<T>> + Send {
async move {
self.repository.find_by_id(id).await.map_err(ApplicationError::Domain)
}
}
fn list(&self) -> impl Future<Output = AppResult<Vec<T>>> + Send {
async move {
self.repository.find_all().await.map_err(ApplicationError::Domain)
}
}
fn update(&self, id: Uuid, data: T::Update) -> impl Future<Output = AppResult<T>> + Send {
async move {
self.repository.update(id, data).await.map_err(ApplicationError::Domain)
}
}
fn delete(&self, id: Uuid) -> impl Future<Output = AppResult<()>> + Send {
async move {
self.repository.delete(id).await.map_err(ApplicationError::Domain)
}
}
}

View file

@ -0,0 +1,19 @@
[package]
name = "cli"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
uuid = { workspace = true }
ratatui = { workspace = true }
crossterm = { workspace = true }
textwrap = "0.16"

View file

@ -0,0 +1,165 @@
use anyhow::Result;
use clap::Parser;
use domain::{CreateProduct, CreateUser, Product, User, UpdateProduct, UpdateUser};
use application::UseCase;
use uuid::Uuid;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Parser)]
pub enum Commands {
/// User management commands
User {
#[command(subcommand)]
command: UserCommands,
},
/// Product management commands
Product {
#[command(subcommand)]
command: ProductCommands,
},
}
#[derive(Parser)]
pub enum UserCommands {
/// Create a new user
Create {
/// Username
#[arg(short, long)]
username: String,
/// Email
#[arg(short, long)]
email: String,
},
/// List all users
List,
/// Get a user by ID
Get {
/// User ID
#[arg(short, long)]
id: Uuid,
},
/// Update a user
Update {
/// User ID
#[arg(short, long)]
id: Uuid,
/// New username
#[arg(short, long)]
username: Option<String>,
/// New email
#[arg(short, long)]
email: Option<String>,
},
/// Delete a user
Delete {
/// User ID
#[arg(short, long)]
id: Uuid,
},
}
#[derive(Parser)]
pub enum ProductCommands {
/// Create a new product
Create {
/// Product name
#[arg(short, long)]
name: String,
/// Product description
#[arg(short, long)]
description: String,
},
/// List all products
List,
/// Get a product by ID
Get {
/// Product ID
#[arg(short, long)]
id: Uuid,
},
/// Update a product
Update {
/// Product ID
#[arg(short, long)]
id: Uuid,
/// New name
#[arg(short, long)]
name: Option<String>,
/// New description
#[arg(short, long)]
description: Option<String>,
},
/// Delete a product
Delete {
/// Product ID
#[arg(short, long)]
id: Uuid,
},
}
impl Cli {
pub async fn run<U, P>(self, user_service: U, product_service: P) -> Result<()>
where
U: UseCase<User>,
P: UseCase<Product>,
{
match self.command {
Some(Commands::User { command }) => match command {
UserCommands::Create { username, email } => {
let user = user_service.create(CreateUser { username, email }).await?;
println!("Created user: {:?}", user);
}
UserCommands::List => {
let users = user_service.list().await?;
println!("Users: {:?}", users);
}
UserCommands::Get { id } => {
let user = user_service.get(id).await?;
println!("User: {:?}", user);
}
UserCommands::Update { id, username, email } => {
let update = UpdateUser { username, email };
let user = user_service.update(id, update).await?;
println!("Updated user: {:?}", user);
}
UserCommands::Delete { id } => {
user_service.delete(id).await?;
println!("Deleted user {}", id);
}
},
Some(Commands::Product { command }) => match command {
ProductCommands::Create { name, description } => {
let product = product_service.create(CreateProduct { name, description }).await?;
println!("Created product: {:?}", product);
}
ProductCommands::List => {
let products = product_service.list().await?;
println!("Products: {:?}", products);
}
ProductCommands::Get { id } => {
let product = product_service.get(id).await?;
println!("Product: {:?}", product);
}
ProductCommands::Update { id, name, description } => {
let update = UpdateProduct { name, description };
let product = product_service.update(id, update).await?;
println!("Updated product: {:?}", product);
}
ProductCommands::Delete { id } => {
product_service.delete(id).await?;
println!("Deleted product {}", id);
}
},
None => {
println!("No command provided. Use --help for usage information.");
}
}
Ok(())
}
}

View file

@ -0,0 +1,12 @@
[package]
name = "domain"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
serde = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }

View file

@ -0,0 +1,105 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
use std::future::Future;
#[derive(Debug, Error)]
pub enum DomainError {
#[error("Entity not found: {0}")]
NotFound(String),
#[error("Invalid input: {0}")]
InvalidInput(String),
#[error("Internal error: {0}")]
Internal(String),
}
unsafe impl Send for DomainError {}
unsafe impl Sync for DomainError {}
pub type Result<T> = std::result::Result<T, DomainError>;
pub trait Entity: Send + Sync {
type Create: Send;
type Update: Send;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub username: String,
pub email: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Entity for User {
type Create = CreateUser;
type Update = UpdateUser;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Product {
pub id: Uuid,
pub name: String,
pub description: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Entity for Product {
type Create = CreateProduct;
type Update = UpdateProduct;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUser {
pub username: String,
pub email: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateUser {
pub username: Option<String>,
pub email: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateProduct {
pub name: String,
pub description: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateProduct {
pub name: Option<String>,
pub description: Option<String>,
}
pub trait Repository<T, Create, Update>: Send + Sync
where
T: Send,
Create: Send,
Update: Send,
{
fn create(&self, data: Create) -> impl Future<Output = Result<T>> + Send;
fn find_by_id(&self, id: Uuid) -> impl Future<Output = Result<T>> + Send;
fn find_all(&self) -> impl Future<Output = Result<Vec<T>>> + Send;
fn update(&self, id: Uuid, data: Update) -> impl Future<Output = Result<T>> + Send;
fn delete(&self, id: Uuid) -> impl Future<Output = Result<()>> + Send;
}
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}

View file

@ -0,0 +1,13 @@
[package]
name = "memory"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
application = { path = "../application" }
tokio = { workspace = true, features = ["sync"] }
uuid = { workspace = true }
chrono = { workspace = true }

View file

@ -0,0 +1,161 @@
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;
use domain::{
CreateProduct, CreateUser, Product, Result, UpdateProduct, UpdateUser, User,
};
use application::{Repository, Service};
#[derive(Default, Clone)]
pub struct InMemoryUserRepository {
users: Arc<RwLock<HashMap<Uuid, User>>>,
}
impl InMemoryUserRepository {
pub fn new() -> Self {
Self {
users: Arc::new(RwLock::new(HashMap::new())),
}
}
}
impl Repository<User> for InMemoryUserRepository {
async fn create(&self, data: CreateUser) -> Result<User> {
let user = User {
id: Uuid::new_v4(),
username: data.username,
email: data.email,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
self.users.write().await.insert(user.id, user.clone());
Ok(user)
}
async fn find_by_id(&self, id: Uuid) -> Result<User> {
self.users
.read()
.await
.get(&id)
.cloned()
.ok_or_else(|| domain::DomainError::NotFound(format!("User not found: {}", id)))
}
async fn find_all(&self) -> Result<Vec<User>> {
Ok(self.users.read().await.values().cloned().collect())
}
async fn update(&self, id: Uuid, data: UpdateUser) -> Result<User> {
let mut users = self.users.write().await;
let user = users
.get_mut(&id)
.ok_or_else(|| domain::DomainError::NotFound(format!("User not found: {}", id)))?;
if let Some(username) = data.username {
user.username = username;
}
if let Some(email) = data.email {
user.email = email;
}
user.updated_at = chrono::Utc::now();
Ok(user.clone())
}
async fn delete(&self, id: Uuid) -> Result<()> {
self.users
.write()
.await
.remove(&id)
.map(|_| ())
.ok_or_else(|| domain::DomainError::NotFound(format!("User not found: {}", id)))
}
}
#[derive(Default, Clone)]
pub struct InMemoryProductRepository {
products: Arc<RwLock<HashMap<Uuid, Product>>>,
}
impl InMemoryProductRepository {
pub fn new() -> Self {
Self {
products: Arc::new(RwLock::new(HashMap::new())),
}
}
}
impl Repository<Product> for InMemoryProductRepository {
async fn create(&self, data: CreateProduct) -> Result<Product> {
let product = Product {
id: Uuid::new_v4(),
name: data.name,
description: data.description,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
self.products.write().await.insert(product.id, product.clone());
Ok(product)
}
async fn find_by_id(&self, id: Uuid) -> Result<Product> {
self.products
.read()
.await
.get(&id)
.cloned()
.ok_or_else(|| domain::DomainError::NotFound(format!("Product not found: {}", id)))
}
async fn find_all(&self) -> Result<Vec<Product>> {
Ok(self.products.read().await.values().cloned().collect())
}
async fn update(&self, id: Uuid, data: UpdateProduct) -> Result<Product> {
let mut products = self.products.write().await;
let product = products
.get_mut(&id)
.ok_or_else(|| domain::DomainError::NotFound(format!("Product not found: {}", id)))?;
if let Some(name) = data.name {
product.name = name;
}
if let Some(description) = data.description {
product.description = description;
}
product.updated_at = chrono::Utc::now();
Ok(product.clone())
}
async fn delete(&self, id: Uuid) -> Result<()> {
self.products
.write()
.await
.remove(&id)
.map(|_| ())
.ok_or_else(|| domain::DomainError::NotFound(format!("Product not found: {}", id)))
}
}
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
pub type MemoryUserService = Service<User, InMemoryUserRepository>;
pub type MemoryProductService = Service<Product, InMemoryProductRepository>;

View file

@ -0,0 +1,14 @@
[package]
name = "postgres"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
application = { path = "../application" }
sqlx = { workspace = true }
tokio = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }

View file

@ -0,0 +1,224 @@
use sqlx::PgPool;
use uuid::Uuid;
use domain::{
CreateProduct, CreateUser, Product, Result, UpdateProduct, UpdateUser, User,
};
use application::{Repository, Service};
#[derive(Clone)]
pub struct PostgresUserRepository {
pool: PgPool,
}
impl PostgresUserRepository {
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
}
impl Repository<User> for PostgresUserRepository {
async fn create(&self, data: CreateUser) -> Result<User> {
let user = sqlx::query_as!(
User,
r#"
INSERT INTO users (username, email)
VALUES ($1, $2)
RETURNING id, username, email, created_at, updated_at
"#,
data.username,
data.email
)
.fetch_one(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
Ok(user)
}
async fn find_by_id(&self, id: Uuid) -> Result<User> {
let user = sqlx::query_as!(
User,
r#"
SELECT id, username, email, created_at, updated_at
FROM users
WHERE id = $1
"#,
id
)
.fetch_optional(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?
.ok_or_else(|| domain::DomainError::NotFound(format!("User not found: {}", id)))?;
Ok(user)
}
async fn find_all(&self) -> Result<Vec<User>> {
let users = sqlx::query_as!(
User,
r#"
SELECT id, username, email, created_at, updated_at
FROM users
"#
)
.fetch_all(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
Ok(users)
}
async fn update(&self, id: Uuid, data: UpdateUser) -> Result<User> {
let user = sqlx::query_as!(
User,
r#"
UPDATE users
SET
username = COALESCE($1, username),
email = COALESCE($2, email),
updated_at = CURRENT_TIMESTAMP
WHERE id = $3
RETURNING id, username, email, created_at, updated_at
"#,
data.username,
data.email,
id
)
.fetch_optional(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?
.ok_or_else(|| domain::DomainError::NotFound(format!("User not found: {}", id)))?;
Ok(user)
}
async fn delete(&self, id: Uuid) -> Result<()> {
let result = sqlx::query!(
r#"
DELETE FROM users
WHERE id = $1
"#,
id
)
.execute(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
if result.rows_affected() == 0 {
return Err(domain::DomainError::NotFound(format!("User not found: {}", id)));
}
Ok(())
}
}
#[derive(Clone)]
pub struct PostgresProductRepository {
pool: PgPool,
}
impl PostgresProductRepository {
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
}
impl Repository<Product> for PostgresProductRepository {
async fn create(&self, data: CreateProduct) -> Result<Product> {
let product = sqlx::query_as!(
Product,
r#"
INSERT INTO products (name, description)
VALUES ($1, $2)
RETURNING id, name, description, created_at, updated_at
"#,
data.name,
data.description
)
.fetch_one(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
Ok(product)
}
async fn find_by_id(&self, id: Uuid) -> Result<Product> {
let product = sqlx::query_as!(
Product,
r#"
SELECT id, name, description, created_at, updated_at
FROM products
WHERE id = $1
"#,
id
)
.fetch_optional(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?
.ok_or_else(|| domain::DomainError::NotFound(format!("Product not found: {}", id)))?;
Ok(product)
}
async fn find_all(&self) -> Result<Vec<Product>> {
let products = sqlx::query_as!(
Product,
r#"
SELECT id, name, description, created_at, updated_at
FROM products
"#
)
.fetch_all(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
Ok(products)
}
async fn update(&self, id: Uuid, data: UpdateProduct) -> Result<Product> {
let product = sqlx::query_as!(
Product,
r#"
UPDATE products
SET
name = COALESCE($1, name),
description = COALESCE($2, description),
updated_at = CURRENT_TIMESTAMP
WHERE id = $3
RETURNING id, name, description, created_at, updated_at
"#,
data.name,
data.description,
id
)
.fetch_optional(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?
.ok_or_else(|| domain::DomainError::NotFound(format!("Product not found: {}", id)))?;
Ok(product)
}
async fn delete(&self, id: Uuid) -> Result<()> {
let result = sqlx::query!(
r#"
DELETE FROM products
WHERE id = $1
"#,
id
)
.execute(&self.pool)
.await
.map_err(|e| domain::DomainError::Internal(e.to_string()))?;
if result.rows_affected() == 0 {
return Err(domain::DomainError::NotFound(format!("Product not found: {}", id)));
}
Ok(())
}
}
pub type PostgresUserService = Service<User, PostgresUserRepository>;
pub type PostgresProductService = Service<Product, PostgresProductRepository>;

View file

@ -0,0 +1,17 @@
[package]
name = "sharenet-api-memory"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
api = { path = "../api" }
application = { path = "../application" }
cli = { path = "../cli" }
memory = { path = "../memory" }
clap = { workspace = true, features = ["derive"] }
tokio = { workspace = true, features = ["full", "macros", "rt-multi-thread"] }
anyhow = { workspace = true }
dotenvy = { workspace = true }

View file

@ -0,0 +1,32 @@
use std::net::SocketAddr;
use std::str::FromStr;
use api::run as run_api;
use application::Service;
use domain::{User, Product};
use memory::{InMemoryProductRepository, InMemoryUserRepository};
use dotenvy::dotenv;
use std::env;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load environment variables from .env file
dotenv().ok();
// Get configuration from environment variables
let server_addr = env::var("SERVER_ADDR").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
// Create repositories
let user_repo = InMemoryUserRepository::new();
let product_repo = InMemoryProductRepository::new();
// Create services
let user_service = Service::<User, _>::new(user_repo);
let product_service = Service::<Product, _>::new(product_repo);
// Run API server
let addr = SocketAddr::from_str(&server_addr)?;
run_api(addr, user_service, product_service).await;
Ok(())
}

View file

@ -0,0 +1,17 @@
[package]
name = "sharenet-api-postgres"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
domain = { path = "../domain" }
api = { path = "../api" }
application = { path = "../application" }
postgres = { path = "../postgres" }
clap = { workspace = true, features = ["derive"] }
tokio = { workspace = true, features = ["full", "macros", "rt-multi-thread"] }
anyhow = { workspace = true }
sqlx = { workspace = true }
dotenvy = { workspace = true }

View file

@ -0,0 +1,40 @@
use std::net::SocketAddr;
use std::str::FromStr;
use api::run as run_api;
use application::Service;
use domain::{User, Product};
use postgres::{PostgresProductRepository, PostgresUserRepository};
use sqlx::postgres::PgPoolOptions;
use dotenvy::dotenv;
use std::env;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load environment variables from .env file
dotenv().ok();
// Get configuration from environment variables
let server_addr = env::var("SERVER_ADDR").unwrap_or_else(|_| "127.0.0.1:3000".to_string());
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
// Create database pool
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
// Create repositories
let user_repo = PostgresUserRepository::new(pool.clone());
let product_repo = PostgresProductRepository::new(pool);
// Create services
let user_service = Service::<User, _>::new(user_repo);
let product_service = Service::<Product, _>::new(product_repo);
// Run API server
let addr = SocketAddr::from_str(&server_addr)?;
run_api(addr, user_service, product_service).await;
Ok(())
}

View file

@ -0,0 +1,15 @@
[package]
name = "sharenet-cli-memory"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
cli = { path = "../cli" }
memory = { path = "../memory" }
tokio = { workspace = true }
clap = { workspace = true }

View file

@ -0,0 +1,13 @@
use anyhow::Result;
use clap::Parser;
use memory::{MemoryUserService, MemoryProductService};
use cli::Cli;
#[tokio::main]
async fn main() -> Result<()> {
let user_service = MemoryUserService::new(memory::InMemoryUserRepository::new());
let product_service = MemoryProductService::new(memory::InMemoryProductRepository::new());
let cli = Cli::try_parse()?;
cli.run(user_service, product_service).await
}

View file

@ -0,0 +1,17 @@
[package]
name = "sharenet-cli-postgres"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
cli = { path = "../cli" }
postgres = { path = "../postgres" }
tokio = { workspace = true }
clap = { workspace = true }
dotenvy = { workspace = true }
sqlx = { workspace = true }

View file

@ -0,0 +1,15 @@
use anyhow::Result;
use clap::Parser;
use postgres::{PostgresUserService, PostgresProductService};
use cli::Cli;
#[tokio::main]
async fn main() -> Result<()> {
dotenvy::dotenv().ok();
let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
let user_service = PostgresUserService::new(postgres::PostgresUserRepository::new(pool.clone()));
let product_service = PostgresProductService::new(postgres::PostgresProductRepository::new(pool));
let cli = Cli::try_parse()?;
cli.run(user_service, product_service).await
}

View file

@ -0,0 +1,14 @@
[package]
name = "sharenet-tui-memory"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
tui = { path = "../tui" }
memory = { path = "../memory" }
tokio = { workspace = true }

View file

@ -0,0 +1,11 @@
use anyhow::Result;
use memory::{MemoryUserService, MemoryProductService};
use tui::run_tui;
#[tokio::main]
async fn main() -> Result<()> {
let user_service = MemoryUserService::new(memory::InMemoryUserRepository::new());
let product_service = MemoryProductService::new(memory::InMemoryProductRepository::new());
run_tui(user_service, product_service).await
}

View file

@ -0,0 +1,464 @@
use std::io;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::collections::VecDeque;
use application::UseCase;
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use domain::{CreateProduct, CreateUser, Product, User};
use ratatui::{
backend::{Backend, CrosstermBackend},
layout::{Constraint, Direction, Layout},
style::{Color, Style},
widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
Frame, Terminal,
};
use textwrap;
const MAX_HISTORY: usize = 100;
pub struct App {
input: String,
messages: Vec<String>,
should_quit: bool,
command_history: VecDeque<String>,
history_index: Option<usize>,
cursor_position: usize,
}
impl App {
pub fn new() -> Self {
Self {
input: String::new(),
messages: vec!["Welcome to Sharenet CLI!".to_string()],
should_quit: false,
command_history: VecDeque::with_capacity(MAX_HISTORY),
history_index: None,
cursor_position: 0,
}
}
pub fn add_message(&mut self, message: String) {
self.messages.push(message);
}
pub fn clear_input(&mut self) {
self.input.clear();
self.cursor_position = 0;
}
pub fn add_to_history(&mut self, command: String) {
if !command.trim().is_empty() {
self.command_history.push_front(command);
if self.command_history.len() > MAX_HISTORY {
self.command_history.pop_back();
}
}
}
pub fn move_cursor(&mut self, delta: isize) {
let new_pos = self.cursor_position as isize + delta;
if new_pos >= 0 && new_pos <= self.input.len() as isize {
self.cursor_position = new_pos as usize;
}
}
pub fn insert_char(&mut self, c: char) {
self.input.insert(self.cursor_position, c);
self.cursor_position += 1;
}
pub fn delete_char(&mut self) {
if self.cursor_position > 0 {
self.input.remove(self.cursor_position - 1);
self.cursor_position -= 1;
}
}
}
pub async fn run_tui<U, P>(user_service: U, product_service: P) -> anyhow::Result<()>
where
U: UseCase<User> + Clone + Send + 'static,
P: UseCase<Product> + Clone + Send + 'static,
{
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and run it
let app = App::new();
let res = run_app(&mut terminal, app, user_service, product_service).await;
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
if let Err(err) = res {
println!("{:?}", err);
}
Ok(())
}
async fn run_app<B: Backend, U, P>(
terminal: &mut Terminal<B>,
mut app: App,
user_service: U,
product_service: P,
) -> anyhow::Result<()>
where
U: UseCase<User> + Clone + Send + 'static,
P: UseCase<Product> + Clone + Send + 'static,
{
let (tx, rx) = mpsc::channel();
let user_service_clone = user_service.clone();
let product_service_clone = product_service.clone();
// Spawn a thread to handle user input
thread::spawn(move || {
loop {
if event::poll(Duration::from_millis(50)).unwrap() {
if let Event::Key(key) = event::read().unwrap() {
tx.send(key).unwrap();
}
}
}
});
loop {
terminal.draw(|f| ui(f, &app))?;
if let Ok(key) = rx.try_recv() {
match key.code {
KeyCode::Char(c) => {
app.insert_char(c);
}
KeyCode::Backspace => {
app.delete_char();
}
KeyCode::Left => {
app.move_cursor(-1);
}
KeyCode::Right => {
app.move_cursor(1);
}
KeyCode::Up => {
if let Some(index) = app.history_index {
if index + 1 < app.command_history.len() {
app.history_index = Some(index + 1);
app.input = app.command_history[index + 1].clone();
app.cursor_position = app.input.len();
}
} else if !app.command_history.is_empty() {
app.history_index = Some(0);
app.input = app.command_history[0].clone();
app.cursor_position = app.input.len();
}
}
KeyCode::Down => {
if let Some(index) = app.history_index {
if index > 0 {
app.history_index = Some(index - 1);
app.input = app.command_history[index - 1].clone();
app.cursor_position = app.input.len();
} else {
app.history_index = None;
app.clear_input();
}
}
}
KeyCode::Enter => {
let input = app.input.clone();
app.add_to_history(input.clone());
app.clear_input();
app.history_index = None;
// Display the command in a distinct color
app.add_message(format!("> {}", input));
// Handle commands
match input.trim() {
"exit" => {
app.add_message("Goodbye!".to_string());
app.should_quit = true;
}
"help" => {
print_help(&mut app);
}
cmd if cmd.starts_with("user create") => {
match parse_user_create(cmd) {
Ok((username, email)) => {
match user_service_clone
.create(CreateUser { username, email })
.await
{
Ok(user) => app.add_message(format!("Created user: {:?}", user)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"user list" => {
match user_service_clone.list().await {
Ok(users) => app.add_message(format!("Users: {:?}", users)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
cmd if cmd.starts_with("product create") => {
match parse_product_create(cmd) {
Ok((name, description)) => {
match product_service_clone
.create(CreateProduct { name, description })
.await
{
Ok(product) => app.add_message(format!("Created product: {:?}", product)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"product list" => {
match product_service_clone.list().await {
Ok(products) => app.add_message(format!("Products: {:?}", products)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"" => {}
_ => {
app.add_message("Unknown command. Type 'help' for available commands.".to_string());
}
}
}
KeyCode::Esc => {
app.should_quit = true;
}
_ => {}
}
}
if app.should_quit {
return Ok(());
}
}
}
fn print_help(app: &mut App) {
app.add_message("\nAvailable commands:".to_string());
app.add_message(" user create -u <username> -e <email>".to_string());
app.add_message(" Example: user create -u \"john doe\" -e \"john@example.com\"".to_string());
app.add_message(" user list".to_string());
app.add_message(" product create -n <name> -d <description>".to_string());
app.add_message(" Example: product create -n \"My Product\" -d \"A great product description\"".to_string());
app.add_message(" product list".to_string());
app.add_message("\nTips:".to_string());
app.add_message(" - Use quotes for values with spaces".to_string());
app.add_message(" - Use Up/Down arrows to navigate command history".to_string());
app.add_message(" - Press Esc to exit".to_string());
app.add_message(" - Type 'help' to show this message".to_string());
}
fn ui(f: &mut Frame, app: &App) {
// Create the layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([
Constraint::Min(1),
Constraint::Length(3),
])
.split(f.size());
// Create the messages list with styling and wrapping
let messages: Vec<ListItem> = app
.messages
.iter()
.flat_map(|msg| {
let style = if msg.starts_with("Error:") {
Style::default().fg(Color::Red)
} else if msg.starts_with("Created") {
Style::default().fg(Color::Green)
} else if msg.starts_with(">") {
Style::default().fg(Color::Cyan)
} else {
Style::default()
};
// Calculate available width for text (accounting for borders and margins)
let available_width = chunks[0].width.saturating_sub(2) as usize;
// Split message into wrapped lines
let wrapped_lines = textwrap::wrap(msg, available_width);
// Convert each wrapped line into a ListItem
wrapped_lines.into_iter().map(move |line| {
ListItem::new(line.to_string()).style(style)
})
})
.collect();
let messages = List::new(messages)
.block(Block::default().title("Messages").borders(Borders::ALL));
f.render_widget(messages, chunks[0]);
// Create the input box with cursor and wrapping
let input = Paragraph::new(app.input.as_str())
.style(Style::default().fg(Color::Yellow))
.block(Block::default().title("Input (Press 'Esc' to exit)").borders(Borders::ALL))
.wrap(Wrap { trim: true });
f.render_widget(input, chunks[1]);
// Show cursor
f.set_cursor(
chunks[1].x + app.cursor_position as u16 + 1,
chunks[1].y + 1,
);
}
fn parse_user_create(cmd: &str) -> anyhow::Result<(String, String)> {
let parts: Vec<&str> = cmd.split_whitespace().collect();
if parts.len() < 6 {
return Err(anyhow::anyhow!(
"Invalid command format. Use: user create -u <username> -e <email>\nExample: user create -u \"john doe\" -e \"john@example.com\""
));
}
let mut username = None;
let mut email = None;
let mut current_arg = None;
let mut current_value = Vec::new();
// Skip "user create" command
let mut i = 2;
while i < parts.len() {
match parts[i] {
"-u" => {
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("username");
current_value.clear();
i += 1;
}
"-e" => {
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("email");
current_value.clear();
i += 1;
}
_ => {
if current_arg.is_some() {
current_value.push(parts[i].trim_matches('"'));
}
i += 1;
}
}
}
// Handle the last argument
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
match (username, email) {
(Some(u), Some(e)) if !u.is_empty() && !e.is_empty() => Ok((u, e)),
_ => Err(anyhow::anyhow!(
"Invalid command format. Use: user create -u <username> -e <email>\nExample: user create -u \"john doe\" -e \"john@example.com\""
)),
}
}
fn parse_product_create(cmd: &str) -> anyhow::Result<(String, String)> {
let parts: Vec<&str> = cmd.split_whitespace().collect();
if parts.len() < 6 {
return Err(anyhow::anyhow!(
"Invalid command format. Use: product create -n <name> -d <description>\nExample: product create -n \"My Product\" -d \"A great product description\""
));
}
let mut name = None;
let mut description = None;
let mut current_arg = None;
let mut current_value = Vec::new();
// Skip "product create" command
let mut i = 2;
while i < parts.len() {
match parts[i] {
"-n" => {
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("name");
current_value.clear();
i += 1;
}
"-d" => {
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("description");
current_value.clear();
i += 1;
}
_ => {
if current_arg.is_some() {
current_value.push(parts[i].trim_matches('"'));
}
i += 1;
}
}
}
// Handle the last argument
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
match (name, description) {
(Some(n), Some(d)) if !n.is_empty() && !d.is_empty() => Ok((n, d)),
_ => Err(anyhow::anyhow!(
"Invalid command format. Use: product create -n <name> -d <description>\nExample: product create -n \"My Product\" -d \"A great product description\""
)),
}
}

View file

@ -0,0 +1,16 @@
[package]
name = "sharenet-tui-postgres"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
tui = { path = "../tui" }
postgres = { path = "../postgres" }
tokio = { workspace = true }
dotenvy = { workspace = true }
sqlx = { workspace = true }

View file

@ -0,0 +1,12 @@
use anyhow::Result;
use postgres::{PostgresUserService, PostgresProductService};
use tui::run_tui;
#[tokio::main]
async fn main() -> Result<()> {
dotenvy::dotenv().ok();
let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
let user_service = PostgresUserService::new(postgres::PostgresUserRepository::new(pool.clone()));
let product_service = PostgresProductService::new(postgres::PostgresProductRepository::new(pool));
run_tui(user_service, product_service).await
}

View file

@ -0,0 +1,15 @@
[package]
name = "tui"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
[dependencies]
anyhow = { workspace = true }
domain = { path = "../domain" }
application = { path = "../application" }
ratatui = { workspace = true }
crossterm = { workspace = true }
textwrap = "0.16"
tokio = { workspace = true }

View file

@ -0,0 +1,464 @@
use std::io;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::collections::VecDeque;
use application::UseCase;
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use domain::{CreateProduct, CreateUser, Product, User};
use ratatui::{
backend::{Backend, CrosstermBackend},
layout::{Constraint, Direction, Layout},
style::{Color, Style},
widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
Frame, Terminal,
};
use textwrap;
const MAX_HISTORY: usize = 100;
pub struct App {
input: String,
messages: Vec<String>,
should_quit: bool,
command_history: VecDeque<String>,
history_index: Option<usize>,
cursor_position: usize,
}
impl App {
pub fn new() -> Self {
Self {
input: String::new(),
messages: vec!["Welcome to Sharenet CLI!".to_string()],
should_quit: false,
command_history: VecDeque::with_capacity(MAX_HISTORY),
history_index: None,
cursor_position: 0,
}
}
pub fn add_message(&mut self, message: String) {
self.messages.push(message);
}
pub fn clear_input(&mut self) {
self.input.clear();
self.cursor_position = 0;
}
pub fn add_to_history(&mut self, command: String) {
if !command.trim().is_empty() {
self.command_history.push_front(command);
if self.command_history.len() > MAX_HISTORY {
self.command_history.pop_back();
}
}
}
pub fn move_cursor(&mut self, delta: isize) {
let new_pos = self.cursor_position as isize + delta;
if new_pos >= 0 && new_pos <= self.input.len() as isize {
self.cursor_position = new_pos as usize;
}
}
pub fn insert_char(&mut self, c: char) {
self.input.insert(self.cursor_position, c);
self.cursor_position += 1;
}
pub fn delete_char(&mut self) {
if self.cursor_position > 0 {
self.input.remove(self.cursor_position - 1);
self.cursor_position -= 1;
}
}
}
pub async fn run_tui<U, P>(user_service: U, product_service: P) -> anyhow::Result<()>
where
U: UseCase<User> + Clone + Send + 'static,
P: UseCase<Product> + Clone + Send + 'static,
{
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and run it
let app = App::new();
let res = run_app(&mut terminal, app, user_service, product_service).await;
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
if let Err(err) = res {
println!("{:?}", err);
}
Ok(())
}
async fn run_app<B: Backend, U, P>(
terminal: &mut Terminal<B>,
mut app: App,
user_service: U,
product_service: P,
) -> anyhow::Result<()>
where
U: UseCase<User> + Clone + Send + 'static,
P: UseCase<Product> + Clone + Send + 'static,
{
let (tx, rx) = mpsc::channel();
let user_service_clone = user_service.clone();
let product_service_clone = product_service.clone();
// Spawn a thread to handle user input
thread::spawn(move || {
loop {
if event::poll(Duration::from_millis(50)).unwrap() {
if let Event::Key(key) = event::read().unwrap() {
tx.send(key).unwrap();
}
}
}
});
loop {
terminal.draw(|f| ui(f, &app))?;
if let Ok(key) = rx.try_recv() {
match key.code {
KeyCode::Char(c) => {
app.insert_char(c);
}
KeyCode::Backspace => {
app.delete_char();
}
KeyCode::Left => {
app.move_cursor(-1);
}
KeyCode::Right => {
app.move_cursor(1);
}
KeyCode::Up => {
if let Some(index) = app.history_index {
if index + 1 < app.command_history.len() {
app.history_index = Some(index + 1);
app.input = app.command_history[index + 1].clone();
app.cursor_position = app.input.len();
}
} else if !app.command_history.is_empty() {
app.history_index = Some(0);
app.input = app.command_history[0].clone();
app.cursor_position = app.input.len();
}
}
KeyCode::Down => {
if let Some(index) = app.history_index {
if index > 0 {
app.history_index = Some(index - 1);
app.input = app.command_history[index - 1].clone();
app.cursor_position = app.input.len();
} else {
app.history_index = None;
app.clear_input();
}
}
}
KeyCode::Enter => {
let input = app.input.clone();
app.add_to_history(input.clone());
app.clear_input();
app.history_index = None;
// Display the command in a distinct color
app.add_message(format!("> {}", input));
// Handle commands
match input.trim() {
"exit" => {
app.add_message("Goodbye!".to_string());
app.should_quit = true;
}
"help" => {
print_help(&mut app);
}
cmd if cmd.starts_with("user create") => {
match parse_user_create(cmd) {
Ok((username, email)) => {
match user_service_clone
.create(CreateUser { username, email })
.await
{
Ok(user) => app.add_message(format!("Created user: {:?}", user)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"user list" => {
match user_service_clone.list().await {
Ok(users) => app.add_message(format!("Users: {:?}", users)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
cmd if cmd.starts_with("product create") => {
match parse_product_create(cmd) {
Ok((name, description)) => {
match product_service_clone
.create(CreateProduct { name, description })
.await
{
Ok(product) => app.add_message(format!("Created product: {:?}", product)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"product list" => {
match product_service_clone.list().await {
Ok(products) => app.add_message(format!("Products: {:?}", products)),
Err(e) => app.add_message(format!("Error: {}", e)),
}
}
"" => {}
_ => {
app.add_message("Unknown command. Type 'help' for available commands.".to_string());
}
}
}
KeyCode::Esc => {
app.should_quit = true;
}
_ => {}
}
}
if app.should_quit {
return Ok(());
}
}
}
fn print_help(app: &mut App) {
app.add_message("\nAvailable commands:".to_string());
app.add_message(" user create -u <username> -e <email>".to_string());
app.add_message(" Example: user create -u \"john doe\" -e \"john@example.com\"".to_string());
app.add_message(" user list".to_string());
app.add_message(" product create -n <name> -d <description>".to_string());
app.add_message(" Example: product create -n \"My Product\" -d \"A great product description\"".to_string());
app.add_message(" product list".to_string());
app.add_message("\nTips:".to_string());
app.add_message(" - Use quotes for values with spaces".to_string());
app.add_message(" - Use Up/Down arrows to navigate command history".to_string());
app.add_message(" - Press Esc to exit".to_string());
app.add_message(" - Type 'help' to show this message".to_string());
}
fn ui(f: &mut Frame, app: &App) {
// Create the layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([
Constraint::Min(1),
Constraint::Length(3),
])
.split(f.size());
// Create the messages list with styling and wrapping
let messages: Vec<ListItem> = app
.messages
.iter()
.flat_map(|msg| {
let style = if msg.starts_with("Error:") {
Style::default().fg(Color::Red)
} else if msg.starts_with("Created") {
Style::default().fg(Color::Green)
} else if msg.starts_with(">") {
Style::default().fg(Color::Cyan)
} else {
Style::default()
};
// Calculate available width for text (accounting for borders and margins)
let available_width = chunks[0].width.saturating_sub(2) as usize;
// Split message into wrapped lines
let wrapped_lines = textwrap::wrap(msg, available_width);
// Convert each wrapped line into a ListItem
wrapped_lines.into_iter().map(move |line| {
ListItem::new(line.to_string()).style(style)
})
})
.collect();
let messages = List::new(messages)
.block(Block::default().title("Messages").borders(Borders::ALL));
f.render_widget(messages, chunks[0]);
// Create the input box with cursor and wrapping
let input = Paragraph::new(app.input.as_str())
.style(Style::default().fg(Color::Yellow))
.block(Block::default().title("Input (Press 'Esc' to exit)").borders(Borders::ALL))
.wrap(Wrap { trim: true });
f.render_widget(input, chunks[1]);
// Show cursor
f.set_cursor(
chunks[1].x + app.cursor_position as u16 + 1,
chunks[1].y + 1,
);
}
fn parse_user_create(cmd: &str) -> anyhow::Result<(String, String)> {
let parts: Vec<&str> = cmd.split_whitespace().collect();
if parts.len() < 6 {
return Err(anyhow::anyhow!(
"Invalid command format. Use: user create -u <username> -e <email>\nExample: user create -u \"john doe\" -e \"john@example.com\""
));
}
let mut username = None;
let mut email = None;
let mut current_arg = None;
let mut current_value = Vec::new();
// Skip "user create" command
let mut i = 2;
while i < parts.len() {
match parts[i] {
"-u" => {
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("username");
current_value.clear();
i += 1;
}
"-e" => {
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("email");
current_value.clear();
i += 1;
}
_ => {
if current_arg.is_some() {
current_value.push(parts[i].trim_matches('"'));
}
i += 1;
}
}
}
// Handle the last argument
if let Some(arg_type) = current_arg {
match arg_type {
"username" => username = Some(current_value.join(" ")),
"email" => email = Some(current_value.join(" ")),
_ => {}
}
}
match (username, email) {
(Some(u), Some(e)) if !u.is_empty() && !e.is_empty() => Ok((u, e)),
_ => Err(anyhow::anyhow!(
"Invalid command format. Use: user create -u <username> -e <email>\nExample: user create -u \"john doe\" -e \"john@example.com\""
)),
}
}
fn parse_product_create(cmd: &str) -> anyhow::Result<(String, String)> {
let parts: Vec<&str> = cmd.split_whitespace().collect();
if parts.len() < 6 {
return Err(anyhow::anyhow!(
"Invalid command format. Use: product create -n <name> -d <description>\nExample: product create -n \"My Product\" -d \"A great product description\""
));
}
let mut name = None;
let mut description = None;
let mut current_arg = None;
let mut current_value = Vec::new();
// Skip "product create" command
let mut i = 2;
while i < parts.len() {
match parts[i] {
"-n" => {
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("name");
current_value.clear();
i += 1;
}
"-d" => {
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
current_arg = Some("description");
current_value.clear();
i += 1;
}
_ => {
if current_arg.is_some() {
current_value.push(parts[i].trim_matches('"'));
}
i += 1;
}
}
}
// Handle the last argument
if let Some(arg_type) = current_arg {
match arg_type {
"name" => name = Some(current_value.join(" ")),
"description" => description = Some(current_value.join(" ")),
_ => {}
}
}
match (name, description) {
(Some(n), Some(d)) if !n.is_empty() && !d.is_empty() => Ok((n, d)),
_ => Err(anyhow::anyhow!(
"Invalid command format. Use: product create -n <name> -d <description>\nExample: product create -n \"My Product\" -d \"A great product description\""
)),
}
}

View file

@ -0,0 +1,16 @@
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT NOT NULL,
email TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
description TEXT NOT NULL,
price DOUBLE PRECISION NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

41
frontend/.gitignore vendored Normal file
View file

@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
frontend/README.md Normal file
View file

@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

21
frontend/components.json Normal file
View file

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View file

@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

7
frontend/next.config.ts Normal file
View file

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

7542
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

40
frontend/package.json Normal file
View file

@ -0,0 +1,40 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@hookform/resolvers": "^5.1.1",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-slot": "^1.2.3",
"@shadcn/ui": "^0.0.4",
"axios": "^1.10.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.515.0",
"next": "15.3.3",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.58.0",
"tailwind-merge": "^3.3.1",
"zod": "^3.25.64"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.3.3",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.4",
"typescript": "^5"
}
}

View file

@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

1
frontend/public/file.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1 KiB

1
frontend/public/next.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View file

@ -0,0 +1,60 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Link from "next/link";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Sharenet Admin",
description: "Admin interface for Sharenet",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<div className="min-h-screen bg-gray-100">
<nav className="bg-white shadow-sm">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
<div className="flex">
<div className="flex-shrink-0 flex items-center">
<h1 className="text-xl font-bold">Sharenet Admin</h1>
</div>
<div className="hidden sm:ml-6 sm:flex sm:space-x-8">
<Link
href="/"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Dashboard
</Link>
<Link
href="/users"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Users
</Link>
<Link
href="/products"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Products
</Link>
</div>
</div>
</div>
</div>
</nav>
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
{children}
</main>
</div>
</body>
</html>
);
}

34
frontend/src/app/page.tsx Normal file
View file

@ -0,0 +1,34 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import Link from "next/link";
export default function Home() {
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Dashboard</h1>
<div className="grid gap-4 md:grid-cols-2">
<Link href="/users">
<Card className="hover:bg-gray-50 transition-colors">
<CardHeader>
<CardTitle>Users</CardTitle>
<CardDescription>Manage system users</CardDescription>
</CardHeader>
<CardContent>
<p>View, create, edit, and delete users</p>
</CardContent>
</Card>
</Link>
<Link href="/products">
<Card className="hover:bg-gray-50 transition-colors">
<CardHeader>
<CardTitle>Products</CardTitle>
<CardDescription>Manage product catalog</CardDescription>
</CardHeader>
<CardContent>
<p>View, create, edit, and delete products</p>
</CardContent>
</Card>
</Link>
</div>
</div>
);
}

View file

@ -0,0 +1,176 @@
'use client';
import { useState, useEffect } from 'react';
import { productApi, Product } from '@/lib/api';
import { Button } from '@/components/ui/button';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
export default function ProductsPage() {
const [products, setProducts] = useState<Product[]>([]);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
const [formData, setFormData] = useState({
name: '',
description: '',
price: '',
});
useEffect(() => {
loadProducts();
}, []);
const loadProducts = async () => {
try {
const response = await productApi.getAll();
setProducts(response.data);
} catch (error) {
console.error('Error loading products:', error);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const productData = {
...formData,
price: parseFloat(formData.price),
};
if (editingProduct) {
await productApi.update(editingProduct.id, productData);
} else {
await productApi.create(productData);
}
setIsDialogOpen(false);
setEditingProduct(null);
setFormData({ name: '', description: '', price: '' });
loadProducts();
} catch (error) {
console.error('Error saving product:', error);
}
};
const handleEdit = (product: Product) => {
setEditingProduct(product);
setFormData({
name: product.name,
description: product.description,
price: product.price.toString(),
});
setIsDialogOpen(true);
};
const handleDelete = async (id: number) => {
if (confirm('Are you sure you want to delete this product?')) {
try {
await productApi.delete(id);
loadProducts();
} catch (error) {
console.error('Error deleting product:', error);
}
}
};
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold">Products</h1>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button onClick={() => {
setEditingProduct(null);
setFormData({ name: '', description: '', price: '' });
}}>
Add Product
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{editingProduct ? 'Edit Product' : 'Add Product'}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Name</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Input
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="price">Price</Label>
<Input
id="price"
type="number"
step="0.01"
value={formData.price}
onChange={(e) => setFormData({ ...formData, price: e.target.value })}
required
/>
</div>
<Button type="submit">{editingProduct ? 'Update' : 'Create'}</Button>
</form>
</DialogContent>
</Dialog>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Description</TableHead>
<TableHead>Price</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{products.map((product) => (
<TableRow key={product.id}>
<TableCell>{product.id}</TableCell>
<TableCell>{product.name}</TableCell>
<TableCell>{product.description}</TableCell>
<TableCell>${product.price.toFixed(2)}</TableCell>
<TableCell>
<div className="space-x-2">
<Button variant="outline" size="sm" onClick={() => handleEdit(product)}>
Edit
</Button>
<Button variant="destructive" size="sm" onClick={() => handleDelete(product.id)}>
Delete
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}

View file

@ -0,0 +1,158 @@
'use client';
import { useState, useEffect } from 'react';
import { userApi, User } from '@/lib/api';
import { Button } from '@/components/ui/button';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
export default function UsersPage() {
const [users, setUsers] = useState<User[]>([]);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [formData, setFormData] = useState({
username: '',
email: '',
});
useEffect(() => {
loadUsers();
}, []);
const loadUsers = async () => {
try {
const response = await userApi.getAll();
setUsers(response.data);
} catch (error) {
console.error('Error loading users:', error);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (editingUser) {
await userApi.update(editingUser.id, formData);
} else {
await userApi.create(formData);
}
setIsDialogOpen(false);
setEditingUser(null);
setFormData({ username: '', email: '' });
loadUsers();
} catch (error) {
console.error('Error saving user:', error);
}
};
const handleEdit = (user: User) => {
setEditingUser(user);
setFormData({ username: user.username, email: user.email });
setIsDialogOpen(true);
};
const handleDelete = async (id: string) => {
if (confirm('Are you sure you want to delete this user?')) {
try {
await userApi.delete(id);
loadUsers();
} catch (error) {
console.error('Error deleting user:', error);
}
}
};
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold">Users</h1>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button onClick={() => {
setEditingUser(null);
setFormData({ username: '', email: '' });
}}>
Add User
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{editingUser ? 'Edit User' : 'Add User'}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
value={formData.username}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
/>
</div>
<Button type="submit">{editingUser ? 'Update' : 'Create'}</Button>
</form>
</DialogContent>
</Dialog>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Username</TableHead>
<TableHead>Email</TableHead>
<TableHead>Created At</TableHead>
<TableHead>Updated At</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.map((user) => (
<TableRow key={user.id}>
<TableCell>{user.id}</TableCell>
<TableCell>{user.username}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>{new Date(user.created_at).toLocaleString()}</TableCell>
<TableCell>{new Date(user.updated_at).toLocaleString()}</TableCell>
<TableCell>
<div className="space-x-2">
<Button variant="outline" size="sm" onClick={() => handleEdit(user)}>
Edit
</Button>
<Button variant="destructive" size="sm" onClick={() => handleDelete(user.id)}>
Delete
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}

View file

@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View file

@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View file

@ -0,0 +1,143 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View file

@ -0,0 +1,167 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View file

@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View file

@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View file

@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

39
frontend/src/lib/api.ts Normal file
View file

@ -0,0 +1,39 @@
import axios from 'axios';
const API_BASE_URL = 'http://127.0.0.1:3000';
export interface User {
id: string;
username: string;
email: string;
created_at: string;
updated_at: string;
}
export interface Product {
id: string;
name: string;
description: string;
created_at: string;
updated_at: string;
}
const api = axios.create({
baseURL: API_BASE_URL,
});
export const userApi = {
getAll: () => api.get<User[]>('/users'),
getById: (id: string) => api.get<User>(`/users/${id}`),
create: (data: Omit<User, 'id' | 'created_at' | 'updated_at'>) => api.post<User>('/users', data),
update: (id: string, data: Partial<Omit<User, 'id' | 'created_at' | 'updated_at'>>) => api.put<User>(`/users/${id}`, data),
delete: (id: string) => api.delete(`/users/${id}`),
};
export const productApi = {
getAll: () => api.get<Product[]>('/products'),
getById: (id: string) => api.get<Product>(`/products/${id}`),
create: (data: Omit<Product, 'id' | 'created_at' | 'updated_at'>) => api.post<Product>('/products', data),
update: (id: string, data: Partial<Omit<Product, 'id' | 'created_at' | 'updated_at'>>) => api.put<Product>(`/products/${id}`, data),
delete: (id: string) => api.delete(`/products/${id}`),
};

View file

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

27
frontend/tsconfig.json Normal file
View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}