From 1ba6b0b64763f91ddffdea4ad9e2c37ec06a10b3 Mon Sep 17 00:00:00 2001 From: Sam Samai Date: Sun, 12 Sep 2021 11:39:53 +1000 Subject: [PATCH] List posts from the DB --- examples/actix_example/Cargo.toml | 8 ++-- examples/actix_example/src/main.rs | 70 +++++++++++++++++------------- 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/examples/actix_example/Cargo.toml b/examples/actix_example/Cargo.toml index 8cf3b6c8..b2bc80e2 100644 --- a/examples/actix_example/Cargo.toml +++ b/examples/actix_example/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "sea-orm-rocket-example" +name = "sea-orm-actix-example" version = "0.1.0" authors = ["Sam Samai "] edition = "2018" @@ -21,7 +21,7 @@ tera = "1.8.0" sea-orm = { path = "../../", version = "^0.2", features = [ "macros", "sqlx-all", - "runtime-tokio-native-tls", + "runtime-async-std-native-tls", ], default-features = false } serde = "1" env_logger = "0.8" @@ -29,9 +29,9 @@ env_logger = "0.8" [dependencies.sqlx] version = "^0.5" default-features = false -features = ["macros", "offline", "migrate"] +features = ["macros", "offline", "migrate", "runtime-async-std-native-tls"] [features] -default = ["sqlx-postgres"] +default = ["sqlx-mysql"] sqlx-mysql = ["sea-orm/sqlx-mysql"] sqlx-postgres = ["sea-orm/sqlx-postgres"] diff --git a/examples/actix_example/src/main.rs b/examples/actix_example/src/main.rs index bc897541..0d46e044 100644 --- a/examples/actix_example/src/main.rs +++ b/examples/actix_example/src/main.rs @@ -1,66 +1,74 @@ // use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder}; - +use actix_files as fs; use actix_http::{body::Body, Response}; use actix_web::dev::ServiceResponse; use actix_web::http::StatusCode; use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers}; -use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer, Result}; -use actix_files as fs; +use actix_web::{error, get, middleware, post, web, App, Error, HttpResponse, HttpServer, Result}; use tera::Tera; mod post; pub use post::Entity as Post; +use sea_orm::query::*; +use sea_orm::DatabaseConnection; +use sea_orm::EntityTrait; +mod setup; -// // store tera template in application state -// async fn index( -// tmpl: web::Data, -// query: web::Query>, -// ) -> Result { -// let s = if let Some(name) = query.get("name") { -// // submitted form -// let mut ctx = tera::Context::new(); -// ctx.insert("name", &name.to_owned()); -// ctx.insert("text", &"Welcome!".to_owned()); -// tmpl.render("user.html", &ctx) -// .map_err(|_| error::ErrorInternalServerError("Template error"))? -// } else { -// tmpl.render("index.html", &tera::Context::new()) -// .map_err(|_| error::ErrorInternalServerError("Template error"))? -// }; -// Ok(HttpResponse::Ok().content_type("text/html").body(s)) -// } +struct AppState { + db_url: String, + templates: tera::Tera, +} + +#[get("/")] +async fn list(data: web::Data) -> Result { + let template = &data.templates; + let conn = sea_orm::Database::connect(&data.db_url).await.unwrap(); + + let posts = Post::find() + .all(&conn) + .await + .expect("could not retrieve posts"); -async fn list( tmpl: web::Data) -> Result { - let posts: Vec = vec!(); let mut ctx = tera::Context::new(); ctx.insert("posts", &posts); ctx.insert("page", &0); ctx.insert("num_pages", &1); - let s = tmpl.render("index.html.tera", &ctx) - .map_err(|_| error::ErrorInternalServerError("Template error"))?; - Ok(HttpResponse::Ok().content_type("text/html").body(s)) + let body = template + .render("index.html.tera", &ctx) + .map_err(|_| error::ErrorInternalServerError("Template error"))?; + Ok(HttpResponse::Ok().content_type("text/html").body(body)) } #[actix_web::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); + let db_url = "mysql://root:@localhost/rocket_example"; + let conn = sea_orm::Database::connect(&db_url).await.unwrap(); + let _ = setup::create_post_table(&conn).await; println!("Listening on: 127.0.0.1:8080"); - HttpServer::new(|| { - let tera = - Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap(); + HttpServer::new(move || { + let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap(); App::new() - .data(tera) + .data(AppState { + db_url: db_url.to_owned(), + templates: templates, + }) .wrap(middleware::Logger::default()) // enable logger .service(fs::Files::new("/static", "./static").show_files_listing()) - .service(web::resource("/").route(web::get().to(list))) + .configure(init) // init todo routes }) .bind("127.0.0.1:8080")? .run() .await } + +// function that will be called on new Application to configure routes for this module +pub fn init(cfg: &mut web::ServiceConfig) { + cfg.service(list); +}