Created
September 28, 2020 12:21
-
-
Save kilroyjones/872c9e6ff2643d5cc5c24b015ec77cd6 to your computer and use it in GitHub Desktop.
Working
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::links::{Link, LinkJson, LinkNew, LinkUpdate}; | |
use crate::Pool; | |
use actix_web::{web, Error, HttpResponse}; | |
use diesel::dsl::insert_into; | |
use diesel::prelude::*; | |
use regex::Regex; | |
use reqwest::Url; | |
pub async fn add_link( | |
pool: web::Data<Pool>, | |
item: web::Json<LinkJson>, | |
) -> Result<HttpResponse, Error> { | |
let title = get_site_title(&item.link).await.unwrap(); | |
Ok(web::block(move || add_single_link(pool, item, title)) | |
.await | |
.map(|link| HttpResponse::Created().json(link)) | |
.map_err(|_| HttpResponse::InternalServerError())?) | |
} | |
async fn get_site_title(url: &String) -> Result<String, Box<dyn std::error::Error>> { | |
let body = reqwest::get(Url::parse(&url).unwrap()) | |
.await? | |
.text() | |
.await?; | |
let re = Regex::new("<title>(.*?)</title>").unwrap(); | |
match re.captures(body.as_str()) { | |
Some(data) => Ok(data.get(1).unwrap().as_str().to_owned()), | |
None => Ok("None".to_string()), | |
} | |
} | |
fn add_single_link( | |
pool: web::Data<Pool>, | |
item: web::Json<LinkJson>, | |
site_title: String, | |
) -> Result<Link, diesel::result::Error> { | |
use crate::schema::links::dsl::*; | |
let conn = pool.get().unwrap(); | |
match links.filter(link.eq(&item.link)).first::<Link>(&conn) { | |
Ok(res) => Ok(res), | |
Err(_) => { | |
let new_link = LinkNew { | |
link: &item.link, | |
title: &site_title, | |
created: chrono::Local::now().naive_local(), | |
}; | |
let res = insert_into(links).values(&new_link).get_result(&conn)?; | |
Ok(res) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment