mirror of
https://github.com/Noratrieb/karlheinz.git
synced 2026-01-14 14:35:03 +01:00
nicer
This commit is contained in:
parent
b9b7c93572
commit
b4bcd6a6dd
2 changed files with 20 additions and 23 deletions
|
|
@ -30,3 +30,10 @@ pub fn find_person_by_id(con: &PgConnection, person_id: &str) -> QueryResult<Opt
|
||||||
.optional()?;
|
.optional()?;
|
||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn find_post_by_id(con: &PgConnection, post_id: i32) -> QueryResult<Option<Post>> {
|
||||||
|
use crate::schema::posts::dsl::*;
|
||||||
|
|
||||||
|
let post = posts.filter(id.eq(post_id)).first::<Post>(con).optional()?;
|
||||||
|
Ok(post)
|
||||||
|
}
|
||||||
|
|
|
||||||
34
src/main.rs
34
src/main.rs
|
|
@ -7,7 +7,7 @@ use std::error::Error;
|
||||||
|
|
||||||
use crate::models::{Person, Post};
|
use crate::models::{Person, Post};
|
||||||
use actix_web::web::Data;
|
use actix_web::web::Data;
|
||||||
use actix_web::{get, post, web, App, Either, HttpResponse, HttpServer, Responder};
|
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use diesel::r2d2::{ConnectionManager, Pool};
|
use diesel::r2d2::{ConnectionManager, Pool};
|
||||||
use dotenv::dotenv;
|
use dotenv::dotenv;
|
||||||
|
|
@ -21,30 +21,20 @@ type DbPool = Pool<ConnectionManager<PgConnection>>;
|
||||||
type WebResult<T> = Result<T, actix_web::Error>;
|
type WebResult<T> = Result<T, actix_web::Error>;
|
||||||
|
|
||||||
#[get("/post/{id}")]
|
#[get("/post/{id}")]
|
||||||
async fn get_post(web::Path(path_id): web::Path<usize>) -> impl Responder {
|
async fn get_post(
|
||||||
use self::schema::posts::dsl::*;
|
web::Path(path_id): web::Path<usize>,
|
||||||
|
pool: Data<DbPool>,
|
||||||
|
) -> WebResult<HttpResponse> {
|
||||||
|
let con = pool.get().expect("Could not get connection from pool");
|
||||||
|
|
||||||
let result = web::block::<_, Vec<Post>, _>(move || {
|
let result = web::block(move || actions::find_post_by_id(&con, path_id as i32))
|
||||||
let connection = establish_connection();
|
|
||||||
|
|
||||||
posts
|
|
||||||
.filter(id.eq(path_id as i32))
|
|
||||||
.load::<Post>(&connection)
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(internal_server_error)?;
|
||||||
eprintln!("{:?}", e);
|
|
||||||
HttpResponse::InternalServerError().finish()
|
|
||||||
})
|
|
||||||
.map(|mut vec| {
|
|
||||||
if vec.len() > 0 {
|
|
||||||
Either::A(HttpResponse::Ok().json(vec.remove(0)))
|
|
||||||
} else {
|
|
||||||
Either::B(HttpResponse::NotFound().finish())
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
result
|
match result {
|
||||||
|
Some(p) => Ok(HttpResponse::Ok().json(p)),
|
||||||
|
None => Ok(HttpResponse::NotFound().finish()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/post")]
|
#[get("/post")]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue