1
0
mirror of https://github.com/actix/examples synced 2025-06-26 09:17:41 +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

View File

@ -27,27 +27,27 @@ pub async fn find_item_by_uid(
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(
conn: &mut AsyncPgConnection,
nm: &str, // prevent collision with `name` column imported inside the function
) -> Result<models::Item, DbError> {
// 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)
// to prevent import collisions and namespace pollution.
use crate::schema::items::dsl::*;
let new_item = models::Item {
id: Uuid::new_v7(Timestamp::now(NoContext)),
name: nm.to_owned(),
// 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)
// to prevent import collisions and namespace pollution.
use crate::schema::items::dsl::*;
let new_item = models::Item {
id: Uuid::new_v7(Timestamp::now(NoContext)),
name: nm.to_owned(),
};
let item = diesel::insert_into(items)
.values(&new_item)
.returning(models::Item::as_returning())
.get_result(conn)
.await
.expect("Error inserting person");
.values(&new_item)
.returning(models::Item::as_returning())
.get_result(conn)
.await
.expect("Error inserting person");
Ok(item)
}
}

View File

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

View File

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