Created
September 28, 2020 12:19
-
-
Save kilroyjones/e92fc0f9417a6bf9ecb6ca30324e1c3f to your computer and use it in GitHub Desktop.
Error on eq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use crate::models::images::{Image, ImageJson, ImageNew, ImageUpdate}; | |
use crate::Pool; | |
use actix_web::{web, Error, HttpResponse}; | |
use diesel::dsl::insert_into; | |
use std::path::Path; | |
use anyhow::{Result}; | |
use tokio::fs::File; | |
use tokio::io::{AsyncWriteExt}; | |
use diesel::prelude::*; | |
pub async fn add_image( | |
pool: web::Data<Pool>, | |
item: web::Json<ImageJson>, | |
) -> Result<HttpResponse, Error> { | |
let image_path = download_image(&item.link).await.unwrap(); | |
Ok(web::block(move || add_single_image(pool, item, image_path)) | |
.await | |
.map(|link| HttpResponse::Created().json(link)) | |
.map_err(|_| HttpResponse::InternalServerError())?) | |
} | |
async fn download_image(url: &String) -> Result<String, Box<dyn std::error::Error>> { | |
let response = reqwest::get(url).await?; | |
let fname = response | |
.url() | |
.path_segments() | |
.and_then(|segments| segments.last()) | |
.and_then(|name| if name.is_empty() { None } else { Some(name) }) | |
.unwrap_or("tmp.bin"); | |
let p = Path::new("files/images/"); | |
let p = p.join(fname); | |
let mut file = File::create(fname).await?; | |
let content = response.bytes().await?; | |
file.write_all(&content).await?; | |
Ok(p.as_path().display().to_string()) | |
} | |
fn add_single_image( | |
pool: web::Data<Pool>, | |
item: web::Json<ImageJson>, | |
img_path: String | |
) -> Result<Image, diesel::result::Error> { | |
use crate::schema::images::dsl::*; | |
let conn = pool.get().unwrap(); | |
match images.filter(images.eq(&item.link)).first::<Image>(&conn) { | |
Ok(res) => Ok(res), | |
Err(_) => { | |
let new_image = ImageNew { | |
link: &item.link, | |
image_path: img_path.as_str(), | |
created: chrono::Local::now().naive_local(), | |
}; | |
let res = insert_into(images).values(&new_image).get_result(&conn)?; | |
Ok(res) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment