List posts from the DB

This commit is contained in:
Sam Samai 2021-09-12 11:39:53 +10:00
parent 8f3a45e6ae
commit 1ba6b0b647
2 changed files with 43 additions and 35 deletions

View File

@ -1,5 +1,5 @@
[package]
name = "sea-orm-rocket-example"
name = "sea-orm-actix-example"
version = "0.1.0"
authors = ["Sam Samai <sam@studio2pi.com.au>"]
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"]

View File

@ -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<tera::Tera>,
// query: web::Query<HashMap<String, String>>,
// ) -> Result<HttpResponse, Error> {
// 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<AppState>) -> Result<HttpResponse, Error> {
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<tera::Tera>) -> Result<HttpResponse, Error> {
let posts: Vec<post::Model> = 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);
}