Create a post #[post("/", data = "<post>")]

This commit is contained in:
Sam Samai 2021-08-27 22:20:46 +10:00
parent 11c1e4e399
commit 41d25225e2
4 changed files with 51 additions and 64 deletions

View File

@ -1,7 +1,5 @@
#[macro_use] #[macro_use]
extern crate rocket; extern crate rocket;
#[macro_use]
extern crate rocket_db_pools;
mod sqlx; mod sqlx;

View File

@ -1,15 +1,12 @@
use rocket::fairing::{self, AdHoc}; use rocket::fairing::AdHoc;
use rocket::response::status::Created; use rocket::response::status::Created;
use rocket::serde::{json::Json, Deserialize, Serialize}; use rocket::serde::json::Json;
use rocket::{futures, Build, Rocket}; use rocket::{futures, Build, Rocket};
use rocket_db_pools::{sqlx, Connection, Database}; use rocket_db_pools::{sqlx, Connection, Database};
use futures::{future::TryFutureExt, stream::TryStreamExt};
use sea_orm::entity::*; use sea_orm::entity::*;
use sea_orm::{ use sea_orm::{DatabaseBackend, Statement};
DatabaseBackend, QueryFilter, SqlxSqliteConnector, SqlxSqlitePoolConnection, Statement,
};
mod setup; mod setup;
@ -19,38 +16,30 @@ struct Db(sea_orm::Database);
type Result<T, E = rocket::response::Debug<sqlx::Error>> = std::result::Result<T, E>; type Result<T, E = rocket::response::Debug<sqlx::Error>> = std::result::Result<T, E>;
// use post::*;
mod post; mod post;
pub use post::Entity as Post; pub use post::Entity as Post;
use sea_orm::DatabaseConnection;
// #[derive(Debug, Clone, Deserialize, Serialize)] #[post("/", data = "<post>")]
// #[serde(crate = "rocket::serde")] async fn create(
// struct Post { conn: Connection<Db>,
// #[serde(skip_deserializing, skip_serializing_if = "Option::is_none")] post: Json<post::Model>,
// id: Option<i64>, ) -> Result<Created<Json<post::Model>>> {
// title: String, let _post = post::ActiveModel {
// text: String, title: Set(post.title.to_owned()),
// } text: Set(post.text.to_owned()),
..Default::default()
}
.save(&conn)
.await
.expect("could not insert post");
// #[post("/", data = "<post>")] Ok(Created::new("/").body(post))
// async fn create(mut db: Connection<Db>, post: Json<Post>) -> Result<Created<Json<Post>>> { }
// // There is no support for `RETURNING`.
// sqlx::query!(
// "INSERT INTO posts (title, text) VALUES (?, ?)",
// post.title,
// post.text
// )
// .execute(&mut *db)
// .await?;
// Ok(Created::new("/").body(post))
// }
#[get("/")] #[get("/")]
async fn list(mut con: Connection<Db>) -> Result<Json<Vec<i64>>> { async fn list(conn: Connection<Db>) -> Result<Json<Vec<i64>>> {
let ids = Post::find() let ids = Post::find()
.all(&con) .all(&conn)
.await .await
.expect("could not retrieve posts") .expect("could not retrieve posts")
.into_iter() .into_iter()
@ -61,9 +50,9 @@ async fn list(mut con: Connection<Db>) -> Result<Json<Vec<i64>>> {
} }
#[get("/<id>")] #[get("/<id>")]
async fn read(mut con: Connection<Db>, id: i64) -> Option<Json<post::Model>> { async fn read(conn: Connection<Db>, id: i64) -> Option<Json<post::Model>> {
let post: Option<post::Model> = Post::find_by_id(id) let post: Option<post::Model> = Post::find_by_id(id)
.one(&con) .one(&conn)
.await .await
.expect("could not find post"); .expect("could not find post");
@ -74,7 +63,7 @@ async fn read(mut con: Connection<Db>, id: i64) -> Option<Json<post::Model>> {
} }
#[delete("/<id>")] #[delete("/<id>")]
async fn delete(mut conn: Connection<Db>, id: i64) -> Result<Option<()>> { async fn delete(conn: Connection<Db>, id: i64) -> Result<Option<()>> {
let post: post::ActiveModel = Post::find_by_id(id) let post: post::ActiveModel = Post::find_by_id(id)
.one(&conn) .one(&conn)
.await .await
@ -87,7 +76,7 @@ async fn delete(mut conn: Connection<Db>, id: i64) -> Result<Option<()>> {
} }
#[delete("/")] #[delete("/")]
async fn destroy(mut conn: Connection<Db>) -> Result<()> { async fn destroy(conn: Connection<Db>) -> Result<()> {
let _result = Post::delete_many().exec(&conn).await.unwrap(); let _result = Post::delete_many().exec(&conn).await.unwrap();
Ok(()) Ok(())
} }
@ -206,7 +195,7 @@ pub fn stage() -> AdHoc {
// None => Err(rocket), // None => Err(rocket),
// } // }
})) }))
.mount("/sqlx", routes![list, read, delete, destroy]) .mount("/sqlx", routes![create, delete, destroy, list, read,])
}) })
} }

View File

@ -1,4 +1,4 @@
use rocket::serde::{json::Json, Deserialize, Serialize}; use rocket::serde::{Deserialize, Serialize};
use sea_orm::entity::prelude::*; use sea_orm::entity::prelude::*;
#[derive(Copy, Clone, Default, Debug, DeriveEntity, Deserialize, Serialize)] #[derive(Copy, Clone, Default, Debug, DeriveEntity, Deserialize, Serialize)]

View File

@ -1,6 +1,6 @@
use sea_orm::{error::*, sea_query, DbConn, ExecResult}; use sea_orm::{error::*, sea_query, DbConn, ExecResult};
use sea_orm::sea_query::{ColumnDef, ForeignKey, ForeignKeyAction, Index, TableCreateStatement}; use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
// mod post; // mod post;
pub use super::post::*; pub use super::post::*;