1
0
mirror of https://github.com/actix/examples synced 2025-04-22 08:34:52 +02:00

chore: updated from main

This commit is contained in:
Alex Ted 2025-01-21 20:41:27 +03:00
parent 631c5f9472
commit 2b275e8ed1
4 changed files with 109 additions and 35 deletions

78
Cargo.lock generated
View File

@ -1692,6 +1692,18 @@ dependencies = [
"log", "log",
] ]
[[package]]
name = "bb8"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89aabfae550a5c44b43ab941844ffcd2e993cb6900b342debf59e9ea74acdb8"
dependencies = [
"async-trait",
"futures-util",
"parking_lot",
"tokio",
]
[[package]] [[package]]
name = "bigdecimal" name = "bigdecimal"
version = "0.3.1" version = "0.3.1"
@ -2584,6 +2596,18 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "db-diesel-async"
version = "1.0.0"
dependencies = [
"actix-web",
"diesel",
"diesel-async",
"dotenvy",
"serde",
"uuid",
]
[[package]] [[package]]
name = "db-mongo" name = "db-mongo"
version = "1.0.0" version = "1.0.0"
@ -2811,6 +2835,21 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "diesel-async"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51a307ac00f7c23f526a04a77761a0519b9f0eb2838ebf5b905a58580095bdcb"
dependencies = [
"async-trait",
"bb8",
"diesel",
"futures-util",
"scoped-futures",
"tokio",
"tokio-postgres",
]
[[package]] [[package]]
name = "diesel_derives" name = "diesel_derives"
version = "2.2.3" version = "2.2.3"
@ -4340,6 +4379,17 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "inotify"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff"
dependencies = [
"bitflags 1.3.2",
"inotify-sys",
"libc",
]
[[package]] [[package]]
name = "inotify" name = "inotify"
version = "0.11.0" version = "0.11.0"
@ -5439,6 +5489,25 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
[[package]]
name = "notify"
version = "6.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d"
dependencies = [
"bitflags 2.6.0",
"crossbeam-channel",
"filetime",
"fsevent-sys",
"inotify 0.9.6",
"kqueue",
"libc",
"log",
"mio 0.8.11",
"walkdir",
"windows-sys 0.48.0",
]
[[package]] [[package]]
name = "notify" name = "notify"
version = "6.1.1" version = "6.1.1"
@ -7090,6 +7159,15 @@ dependencies = [
"parking_lot", "parking_lot",
] ]
[[package]]
name = "scoped-futures"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b24aae2d0636530f359e9d5ef0c04669d11c5e756699b27a6a6d845d8329091"
dependencies = [
"pin-project-lite",
]
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.2.0"

View File

@ -27,27 +27,27 @@ pub async fn find_item_by_uid(
Ok(item) Ok(item)
} }
/// Run query using Diesel to insert a new database row and return the result. /// Run query using Diesel to insert a new database row and return the result.
pub async fn insert_new_item( pub async fn insert_new_item(
conn: &mut AsyncPgConnection, conn: &mut AsyncPgConnection,
nm: &str, // prevent collision with `name` column imported inside the function nm: &str, // prevent collision with `name` column imported inside the function
) -> Result<models::Item, DbError> { ) -> Result<models::Item, DbError> {
// It is common when using Diesel with Actix Web to import schema-related // It is common when using Diesel with Actix Web to import schema-related
// modules inside a function's scope (rather than the normal module's scope) // modules inside a function's scope (rather than the normal module's scope)
// to prevent import collisions and namespace pollution. // to prevent import collisions and namespace pollution.
use crate::schema::items::dsl::*; use crate::schema::items::dsl::*;
let new_item = models::Item { let new_item = models::Item {
id: Uuid::new_v7(Timestamp::now(NoContext)), id: Uuid::new_v7(Timestamp::now(NoContext)),
name: nm.to_owned(), name: nm.to_owned(),
}; };
let item = diesel::insert_into(items) let item = diesel::insert_into(items)
.values(&new_item) .values(&new_item)
.returning(models::Item::as_returning()) .returning(models::Item::as_returning())
.get_result(conn) .get_result(conn)
.await .await
.expect("Error inserting person"); .expect("Error inserting person");
Ok(item) Ok(item)
} }

View File

@ -1,19 +1,16 @@
#[macro_use] #[macro_use]
extern crate diesel; extern crate diesel;
use std::env::VarError;
use actix_web::{error, get, post, web, App, HttpResponse, HttpServer, Responder}; use actix_web::{error, get, post, web, App, HttpResponse, HttpServer, Responder};
use diesel_async::pooled_connection::{bb8::Pool, AsyncDieselConnectionManager, PoolError}; use diesel_async::pooled_connection::{bb8::Pool, AsyncDieselConnectionManager};
use diesel_async::AsyncPgConnection; use diesel_async::AsyncPgConnection;
use dotenvy::dotenv; use dotenvy::dotenv;
use std::{env, io}; use std::{env, io};
use thiserror::Error as ThisError;
use uuid::Uuid; use uuid::Uuid;
pub mod actions; mod actions;
pub mod models; mod models;
pub mod schema; mod schema;
type DbPool = Pool<AsyncPgConnection>; type DbPool = Pool<AsyncPgConnection>;
@ -35,9 +32,9 @@ async fn get_item(
.expect("Couldn't get db connection from the pool"); .expect("Couldn't get db connection from the pool");
let item = actions::find_item_by_uid(&mut conn, item_uid) let item = actions::find_item_by_uid(&mut conn, item_uid)
.await .await
// map diesel query errors to a 500 error response // map diesel query errors to a 500 error response
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
Ok(match item { Ok(match item {
// item was found; return 200 response with JSON formatted item object // item was found; return 200 response with JSON formatted item object
@ -58,16 +55,15 @@ async fn add_item(
pool: web::Data<DbPool>, pool: web::Data<DbPool>,
form: web::Json<models::NewItem>, form: web::Json<models::NewItem>,
) -> actix_web::Result<impl Responder> { ) -> actix_web::Result<impl Responder> {
let mut conn = pool let mut conn = pool
.get() .get()
.await .await
.expect("Couldn't get db connection from the pool"); .expect("Couldn't get db connection from the pool");
let item = actions::insert_new_item(&mut conn, &form.name) let item = actions::insert_new_item(&mut conn, &form.name)
.await .await
// map diesel query errors to a 500 error response // map diesel query errors to a 500 error response
.map_err(error::ErrorInternalServerError)?; .map_err(error::ErrorInternalServerError)?;
// item was added successfully; return 201 response with new item info // item was added successfully; return 201 response with new item info
Ok(HttpResponse::Created().json(item)) Ok(HttpResponse::Created().json(item))
@ -88,7 +84,7 @@ async fn main() -> io::Result<()> {
.service(add_item) .service(add_item)
.service(get_item) .service(get_item)
}) })
.bind(("127.0.0.1", 5000))? .bind(("127.0.0.1", 8080))?
.run() .run()
.await .await
} }

View File

@ -1,6 +1,6 @@
use super::schema::items;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uuid::Uuid; use uuid::Uuid;
use super::schema::items;
/// Item details. /// Item details.
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, Insertable)] #[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, Insertable)]
@ -20,6 +20,6 @@ impl NewItem {
/// Constructs new item details from name. /// Constructs new item details from name.
#[cfg(test)] // only needed in tests #[cfg(test)] // only needed in tests
pub fn new(name: impl Into<String>) -> Self { pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), ..Default::default() } Self { name: name.into() }
} }
} }