mirror of
https://github.com/actix/examples
synced 2025-06-27 01:27:43 +02:00
Restructure folders (#411)
This commit is contained in:
committed by
GitHub
parent
9db98162b2
commit
c3407627d0
12
graphql/juniper-advanced/src/db.rs
Normal file
12
graphql/juniper-advanced/src/db.rs
Normal file
@ -0,0 +1,12 @@
|
||||
use r2d2_mysql::mysql::{Opts, OptsBuilder};
|
||||
use r2d2_mysql::MysqlConnectionManager;
|
||||
|
||||
pub type Pool = r2d2::Pool<MysqlConnectionManager>;
|
||||
|
||||
pub fn get_db_pool() -> Pool {
|
||||
let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
let opts = Opts::from_url(&db_url).unwrap();
|
||||
let builder = OptsBuilder::from_opts(opts);
|
||||
let manager = MysqlConnectionManager::new(builder);
|
||||
r2d2::Pool::new(manager).expect("Failed to create DB Pool")
|
||||
}
|
39
graphql/juniper-advanced/src/handlers.rs
Normal file
39
graphql/juniper-advanced/src/handlers.rs
Normal file
@ -0,0 +1,39 @@
|
||||
use actix_web::{web, Error, HttpResponse};
|
||||
use juniper::http::graphiql::graphiql_source;
|
||||
use juniper::http::GraphQLRequest;
|
||||
|
||||
use crate::db::Pool;
|
||||
use crate::schemas::root::{create_schema, Context, Schema};
|
||||
|
||||
pub async fn graphql(
|
||||
pool: web::Data<Pool>,
|
||||
schema: web::Data<Schema>,
|
||||
data: web::Json<GraphQLRequest>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let ctx = Context {
|
||||
dbpool: pool.get_ref().to_owned(),
|
||||
};
|
||||
let res = web::block(move || {
|
||||
let res = data.execute(&schema, &ctx);
|
||||
Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?)
|
||||
})
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(res))
|
||||
}
|
||||
|
||||
pub async fn graphql_playground() -> HttpResponse {
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/html; charset=utf-8")
|
||||
.body(graphiql_source("/graphql"))
|
||||
}
|
||||
|
||||
pub fn register(config: &mut web::ServiceConfig) {
|
||||
config
|
||||
.data(create_schema())
|
||||
.route("/graphql", web::post().to(graphql))
|
||||
.route("/graphiql", web::get().to(graphql_playground));
|
||||
}
|
33
graphql/juniper-advanced/src/main.rs
Normal file
33
graphql/juniper-advanced/src/main.rs
Normal file
@ -0,0 +1,33 @@
|
||||
#[macro_use]
|
||||
extern crate juniper;
|
||||
extern crate r2d2;
|
||||
extern crate r2d2_mysql;
|
||||
extern crate serde_json;
|
||||
|
||||
use actix_web::{middleware, web, App, HttpServer};
|
||||
|
||||
use crate::db::get_db_pool;
|
||||
use crate::handlers::register;
|
||||
|
||||
mod db;
|
||||
mod handlers;
|
||||
mod schemas;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
dotenv::dotenv().ok();
|
||||
std::env::set_var("RUST_LOG", "actix_web=info,info");
|
||||
env_logger::init();
|
||||
let pool = get_db_pool();
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.data(pool.clone())
|
||||
.wrap(middleware::Logger::default())
|
||||
.configure(register)
|
||||
.default_service(web::to(|| async { "404" }))
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.await
|
||||
}
|
3
graphql/juniper-advanced/src/schemas/mod.rs
Normal file
3
graphql/juniper-advanced/src/schemas/mod.rs
Normal file
@ -0,0 +1,3 @@
|
||||
pub mod product;
|
||||
pub mod root;
|
||||
pub mod user;
|
51
graphql/juniper-advanced/src/schemas/product.rs
Normal file
51
graphql/juniper-advanced/src/schemas/product.rs
Normal file
@ -0,0 +1,51 @@
|
||||
use mysql::{from_row, params, Error as DBError, Row};
|
||||
|
||||
use crate::schemas::root::Context;
|
||||
use crate::schemas::user::User;
|
||||
|
||||
/// Product
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Product {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub name: String,
|
||||
pub price: f64,
|
||||
}
|
||||
|
||||
#[juniper::object(Context = Context)]
|
||||
impl Product {
|
||||
fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
fn user_id(&self) -> &str {
|
||||
&self.user_id
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn price(&self) -> f64 {
|
||||
self.price
|
||||
}
|
||||
|
||||
fn user(&self, context: &Context) -> Option<User> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let user: Result<Option<Row>, DBError> = conn.first_exec(
|
||||
"SELECT * FROM user WHERE id=:id",
|
||||
params! {"id" => &self.user_id},
|
||||
);
|
||||
if let Err(err) = user {
|
||||
None
|
||||
} else {
|
||||
let (id, name, email) = from_row(user.unwrap().unwrap());
|
||||
Some(User { id, name, email })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(GraphQLInputObject)]
|
||||
#[graphql(description = "Product Input")]
|
||||
pub struct ProductInput {
|
||||
pub user_id: String,
|
||||
pub name: String,
|
||||
pub price: f64,
|
||||
}
|
175
graphql/juniper-advanced/src/schemas/root.rs
Normal file
175
graphql/juniper-advanced/src/schemas/root.rs
Normal file
@ -0,0 +1,175 @@
|
||||
use juniper::{FieldError, FieldResult, RootNode};
|
||||
use mysql::{from_row, params, Error as DBError, Row};
|
||||
|
||||
use crate::db::Pool;
|
||||
|
||||
use super::product::{Product, ProductInput};
|
||||
use super::user::{User, UserInput};
|
||||
|
||||
pub struct Context {
|
||||
pub dbpool: Pool,
|
||||
}
|
||||
|
||||
impl juniper::Context for Context {}
|
||||
|
||||
pub struct QueryRoot;
|
||||
|
||||
#[juniper::object(Context = Context)]
|
||||
impl QueryRoot {
|
||||
#[graphql(description = "List of all users")]
|
||||
fn users(context: &Context) -> FieldResult<Vec<User>> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let users = conn
|
||||
.prep_exec("select * from user", ())
|
||||
.map(|result| {
|
||||
result
|
||||
.map(|x| x.unwrap())
|
||||
.map(|mut row| {
|
||||
let (id, name, email) = from_row(row);
|
||||
User { id, name, email }
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap();
|
||||
Ok(users)
|
||||
}
|
||||
|
||||
#[graphql(description = "Get Single user reference by user ID")]
|
||||
fn user(context: &Context, id: String) -> FieldResult<User> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
|
||||
let user: Result<Option<Row>, DBError> =
|
||||
conn.first_exec("SELECT * FROM user WHERE id=:id", params! {"id" => id});
|
||||
|
||||
if let Err(err) = user {
|
||||
return Err(FieldError::new(
|
||||
"User Not Found",
|
||||
graphql_value!({ "not_found": "user not found" }),
|
||||
));
|
||||
}
|
||||
|
||||
let (id, name, email) = from_row(user.unwrap().unwrap());
|
||||
Ok(User { id, name, email })
|
||||
}
|
||||
|
||||
#[graphql(description = "List of all users")]
|
||||
fn products(context: &Context) -> FieldResult<Vec<Product>> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let products = conn
|
||||
.prep_exec("select * from product", ())
|
||||
.map(|result| {
|
||||
result
|
||||
.map(|x| x.unwrap())
|
||||
.map(|mut row| {
|
||||
let (id, user_id, name, price) = from_row(row);
|
||||
Product {
|
||||
id,
|
||||
user_id,
|
||||
name,
|
||||
price,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap();
|
||||
Ok(products)
|
||||
}
|
||||
|
||||
#[graphql(description = "Get Single user reference by user ID")]
|
||||
fn product(context: &Context, id: String) -> FieldResult<Product> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let product: Result<Option<Row>, DBError> =
|
||||
conn.first_exec("SELECT * FROM user WHERE id=:id", params! {"id" => id});
|
||||
if let Err(err) = product {
|
||||
return Err(FieldError::new(
|
||||
"Product Not Found",
|
||||
graphql_value!({ "not_found": "product not found" }),
|
||||
));
|
||||
}
|
||||
|
||||
let (id, user_id, name, price) = from_row(product.unwrap().unwrap());
|
||||
Ok(Product {
|
||||
id,
|
||||
user_id,
|
||||
name,
|
||||
price,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MutationRoot;
|
||||
|
||||
#[juniper::object(Context = Context)]
|
||||
impl MutationRoot {
|
||||
fn create_user(context: &Context, user: UserInput) -> FieldResult<User> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let new_id = uuid::Uuid::new_v4().to_simple().to_string();
|
||||
|
||||
let insert: Result<Option<Row>, DBError> = conn.first_exec(
|
||||
"INSERT INTO user(id, name, email) VALUES(:id, :name, :email)",
|
||||
params! {
|
||||
"id" => &new_id,
|
||||
"name" => &user.name,
|
||||
"email" => &user.email,
|
||||
},
|
||||
);
|
||||
|
||||
match insert {
|
||||
Ok(opt_row) => Ok(User {
|
||||
id: new_id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
}),
|
||||
Err(err) => {
|
||||
let msg = match err {
|
||||
DBError::MySqlError(err) => err.message,
|
||||
_ => "internal error".to_owned(),
|
||||
};
|
||||
Err(FieldError::new(
|
||||
"Failed to create new user",
|
||||
graphql_value!({ "internal_error": msg }),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_product(context: &Context, product: ProductInput) -> FieldResult<Product> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
let new_id = uuid::Uuid::new_v4().to_simple().to_string();
|
||||
|
||||
let insert: Result<Option<Row>, DBError> = conn.first_exec(
|
||||
"INSERT INTO product(id, user_id, name, price) VALUES(:id, :user_id, :name, :price)",
|
||||
params! {
|
||||
"id" => &new_id,
|
||||
"user_id" => &product.user_id,
|
||||
"name" => &product.name,
|
||||
"price" => &product.price.to_owned(),
|
||||
},
|
||||
);
|
||||
|
||||
match insert {
|
||||
Ok(opt_row) => Ok(Product {
|
||||
id: new_id,
|
||||
user_id: product.user_id,
|
||||
name: product.name,
|
||||
price: product.price,
|
||||
}),
|
||||
Err(err) => {
|
||||
let msg = match err {
|
||||
DBError::MySqlError(err) => err.message,
|
||||
_ => "internal error".to_owned(),
|
||||
};
|
||||
Err(FieldError::new(
|
||||
"Failed to create new product",
|
||||
graphql_value!({ "internal_error": msg }),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Schema = RootNode<'static, QueryRoot, MutationRoot>;
|
||||
|
||||
pub fn create_schema() -> Schema {
|
||||
Schema::new(QueryRoot, MutationRoot)
|
||||
}
|
58
graphql/juniper-advanced/src/schemas/user.rs
Normal file
58
graphql/juniper-advanced/src/schemas/user.rs
Normal file
@ -0,0 +1,58 @@
|
||||
use mysql::{from_row, params};
|
||||
|
||||
use crate::schemas::product::Product;
|
||||
use crate::schemas::root::Context;
|
||||
|
||||
/// User
|
||||
#[derive(Default, Debug)]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(GraphQLInputObject)]
|
||||
#[graphql(description = "User Input")]
|
||||
pub struct UserInput {
|
||||
pub name: String,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[juniper::object(Context = Context)]
|
||||
impl User {
|
||||
fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn email(&self) -> &str {
|
||||
&self.email
|
||||
}
|
||||
|
||||
fn products(&self, context: &Context) -> Vec<Product> {
|
||||
let mut conn = context.dbpool.get().unwrap();
|
||||
|
||||
conn.prep_exec(
|
||||
"select * from product where user_id=:user_id",
|
||||
params! {
|
||||
"user_id" => &self.id
|
||||
},
|
||||
)
|
||||
.map(|result| {
|
||||
result
|
||||
.map(|x| x.unwrap())
|
||||
.map(|mut row| {
|
||||
let (id, user_id, name, price) = from_row(row);
|
||||
Product {
|
||||
id,
|
||||
user_id,
|
||||
name,
|
||||
price,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user