Skip to content

Commit

Permalink
Reduce code
Browse files Browse the repository at this point in the history
  • Loading branch information
hongquan committed Sep 1, 2023
1 parent 13fea92 commit 80179ea
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 38 deletions.
9 changes: 5 additions & 4 deletions src/front/views/feeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use axum::extract::{Query, State, Host, OriginalUri};
use axum::response::{Result as AxumResult, IntoResponseParts, Json};
use chrono::{TimeZone, Utc};
use edgedb_tokio::Client as EdgeClient;
use http::header::CONTENT_TYPE;
use http::{header::CONTENT_TYPE, Uri};

use super::super::structs::LaxPaging;
use crate::consts::DEFAULT_PAGE_SIZE;
use crate::errors::PageError;
use crate::models::feeds::{JsonFeed, JsonItem};
use crate::models::feeds::{JsonFeed, JsonItem, EntryExt, DEFAULT_SITE_URL};
use crate::stores;
use crate::types::Paginator;

Expand All @@ -23,7 +23,7 @@ pub async fn gen_atom_feeds(
Query(paging): Query<LaxPaging>,
State(db): State<EdgeClient>,
) -> AxumResult<(impl IntoResponseParts, String)> {
let base_url = format!("https://{host}");
let base_url: Uri = format!("https://{host}").parse().unwrap_or(Uri::from_static(DEFAULT_SITE_URL));
let current_page = paging.get_page_as_number();
let page_size = DEFAULT_PAGE_SIZE;
let offset = ((current_page.get() - 1) * page_size as u16) as i64;
Expand Down Expand Up @@ -55,7 +55,8 @@ pub async fn gen_atom_feeds(
if let Some(url) = prev_page_url {
links.push(LinkBuilder::default().rel("previous".to_string()).href(format!("{base_url}{url}")).build())
}
let entries: Vec<Entry> = posts.iter().map(|p| p.to_atom_entry(Some(&host))).collect();
let mut entries: Vec<Entry> = posts.into_iter().map(Entry::from).collect();
entries.iter_mut().for_each(|e| e.prepend_url(&base_url));
let latest_post = stores::blog::get_last_updated_post(&db)
.await
.map_err(PageError::EdgeDBQueryError)?;
Expand Down
38 changes: 5 additions & 33 deletions src/models/blogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ use chrono::{Utc, DateTime};
use edgedb_derive::Queryable;
use edgedb_protocol::model::Datetime as EDatetime;
use edgedb_protocol::value::Value as EValue;
use http::Uri;
use serde::{Deserialize, Serialize};
use serde_json::Value as JValue;
use strum_macros::{Display, EnumString, IntoStaticStr};
use uuid::Uuid;
use atom_syndication::{Entry as AtomEntry, EntryBuilder, Link, LinkBuilder, Category as AtomCategory, CategoryBuilder, Text, Person};
use atom_syndication::{Entry as AtomEntry, EntryBuilder, LinkBuilder, Category as AtomCategory, CategoryBuilder, Text, Person};

use crate::types::conversions::{
serialize_edge_datetime, serialize_optional_edge_datetime,
Expand Down Expand Up @@ -74,36 +73,9 @@ pub struct MediumBlogPost {
}

impl MediumBlogPost {
pub fn get_view_url(&self, base_url: Option<&Uri>) -> String {
pub fn get_view_url(&self) -> String {
let created_at: DateTime<Utc> = self.created_at.into();
let url_path = format!("/post/{}/{}", created_at.format("%Y/%m"), self.slug);
let host = base_url.map(|u| u.authority()).flatten();
if let Some(host) = host {
let scheme = base_url.map(|u| u.scheme_str()).flatten().unwrap_or("https");
format!("{scheme}://{host}{url_path}")
} else {
url_path
}
}

pub fn to_atom_entry(&self, host: Option<&str>) -> AtomEntry {
let mut entry = AtomEntry::from(self.clone());
if let Some(host) = host {
let links = entry.links();
let absolute_links: Vec<Link> = links.into_iter().map(|l| {
let mut link = l.clone();
if l.href().starts_with("/") {
let path = l.href();
let scheme = if host == "localhost" { "http" } else { "https" };
link.set_href(format!("{scheme}://{host}{path}"));
link
} else {
link
}
}).collect();
entry.set_links(absolute_links);
};
entry
format!("/post/{}/{}", created_at.format("%Y/%m"), self.slug)
}
}

Expand All @@ -128,7 +100,7 @@ impl Default for MediumBlogPost {

impl From<MediumBlogPost> for AtomEntry {
fn from(value: MediumBlogPost) -> Self {
let url = value.get_view_url(None);
let url = value.get_view_url();
let MediumBlogPost {
id,
title,
Expand Down Expand Up @@ -167,7 +139,7 @@ impl From<MediumBlogPost> for AtomEntry {

impl From<MediumBlogPost> for JsonItem {
fn from(value: MediumBlogPost) -> Self {
let url = value.get_view_url(None);
let url = value.get_view_url();
let MediumBlogPost {
id,
title,
Expand Down
21 changes: 20 additions & 1 deletion src/models/feeds.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// Just copy from https://github.com/feed-rs/feed-rs/

use http::Uri;
use serde::Serialize;
use atom_syndication::Entry;

pub const DEFAULT_SITE_URL: &str = "https://quan.hoabinh.vn";

#[derive(Debug, Serialize)]
pub struct JsonFeed {
Expand All @@ -21,7 +25,7 @@ impl Default for JsonFeed {
Self {
version: "https://jsonfeed.org/version/1.1".into(),
title: "QuanWeb".into(),
home_page_url: Some("https://quan.hoabinh.vn".into()),
home_page_url: Some(DEFAULT_SITE_URL.to_string()),
feed_url: None,
next_url: None,
description: Some("Blog about programming, culture, history".into()),
Expand Down Expand Up @@ -54,3 +58,18 @@ pub struct JsonItem {
pub tags: Option<Vec<String>>,
pub language: Option<String>,
}

pub trait EntryExt {
fn prepend_url(&mut self, base_url: &Uri);
}

impl EntryExt for Entry {
fn prepend_url(&mut self, base_url: &Uri) {
self.links.iter_mut().for_each(|u| {
let old_url = u.href();
if old_url.starts_with("/") {
u.set_href(format!("{base_url}{old_url}"));
}
});
}
}

0 comments on commit 80179ea

Please sign in to comment.