From f97c081c2aeaeba235421fb97db4988fb47fd213 Mon Sep 17 00:00:00 2001 From: Sam Samai Date: Sun, 12 Sep 2021 17:12:20 +1000 Subject: [PATCH] Add new post --- examples/actix_example/src/main.rs | 36 +++++++++++++++++- .../actix_example/templates/new.html.tera | 38 +++++++++++++++++++ examples/rocket_example/src/main.rs | 2 +- 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 examples/actix_example/templates/new.html.tera diff --git a/examples/actix_example/src/main.rs b/examples/actix_example/src/main.rs index 5aadeb29..fd32f0ff 100644 --- a/examples/actix_example/src/main.rs +++ b/examples/actix_example/src/main.rs @@ -9,6 +9,7 @@ use actix_web::{ error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result, }; use listenfd::ListenFd; +use sea_orm::entity::*; use sea_orm::query::*; use sea_orm::DatabaseConnection; use sea_orm::EntityTrait; @@ -20,7 +21,7 @@ mod post; pub use post::Entity as Post; mod setup; -const DEFAULT_POSTS_PER_PAGE: usize = 4; +const DEFAULT_POSTS_PER_PAGE: usize = 25; struct AppState { db_url: String, @@ -62,6 +63,37 @@ async fn list(req: HttpRequest, data: web::Data) -> Result) -> Result { + let template = &data.templates; + let ctx = tera::Context::new(); + let body = template + .render("new.html.tera", &ctx) + .map_err(|_| error::ErrorInternalServerError("Template error"))?; + Ok(HttpResponse::Ok().content_type("text/html").body(body)) +} + +#[post("/")] +async fn create( + data: web::Data, + post_form: web::Form, +) -> Result { + let conn = sea_orm::Database::connect(&data.db_url).await.unwrap(); + + let form = post_form.into_inner(); + + post::ActiveModel { + title: Set(form.title.to_owned()), + text: Set(form.text.to_owned()), + ..Default::default() + } + .save(&conn) + .await + .expect("could not insert post"); + + Ok(HttpResponse::Found().header("location", "/").finish()) +} + #[actix_web::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); @@ -104,4 +136,6 @@ async fn main() -> std::io::Result<()> { pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(list); + cfg.service(new); + cfg.service(create); } diff --git a/examples/actix_example/templates/new.html.tera b/examples/actix_example/templates/new.html.tera new file mode 100644 index 00000000..dee19565 --- /dev/null +++ b/examples/actix_example/templates/new.html.tera @@ -0,0 +1,38 @@ +{% extends "layout.html.tera" %} {% block content %} +
+

New Post

+
+
+ + +
+
+
+ + + +
+
+
+ +
+
+
+
+{% endblock content %} diff --git a/examples/rocket_example/src/main.rs b/examples/rocket_example/src/main.rs index d1f23244..98d53680 100644 --- a/examples/rocket_example/src/main.rs +++ b/examples/rocket_example/src/main.rs @@ -29,7 +29,7 @@ pub use post::Entity as Post; const DEFAULT_POSTS_PER_PAGE: usize = 25; #[get("/new")] -fn new() -> Template { +async fn new() -> Template { Template::render("new", &Context::default()) }