Skip to content

Commit

Permalink
refactor: make /api/articles more simpler
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanglun committed Dec 29, 2023
1 parent 1d26931 commit 6d2e56f
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 192 deletions.
157 changes: 40 additions & 117 deletions src-tauri/src/feed/article.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use chrono::{Utc, Duration};
use crate::core::config::get_user_config;
use chrono::{Duration, Utc};
use diesel::prelude::*;
use diesel::sql_types::*;
use serde::{Deserialize, Serialize};
use crate::core::config::get_user_config;

use crate::db::establish_connection;
use crate::models;
Expand All @@ -19,7 +19,9 @@ pub enum ArticleReadStatus {
#[derive(Debug, Serialize, Deserialize)]
pub struct ArticleFilter {
pub feed_uuid: Option<String>,
pub folder_uuid: Option<String>,
pub item_type: Option<String>,
pub is_today: Option<i32>,
pub read_status: Option<i32>,
pub cursor: Option<i32>,
pub limit: Option<i32>,
Expand Down Expand Up @@ -84,14 +86,14 @@ impl Article {
if let Some(item_type) = filter.item_type {
if item_type == String::from("folder") {
relations = schema::feed_metas::dsl::feed_metas
.filter(schema::feed_metas::folder_uuid.eq(&channel_uuid))
.load::<models::FeedMeta>(&mut connection)
.expect("Expect find channel");
} else {
.filter(schema::feed_metas::folder_uuid.eq(&channel_uuid))
.load::<models::FeedMeta>(&mut connection)
.expect("Expect find channel");
} else {
relations = schema::feed_metas::dsl::feed_metas
.filter(schema::feed_metas::uuid.eq(&channel_uuid))
.load::<models::FeedMeta>(&mut connection)
.expect("Expect find channel");
.filter(schema::feed_metas::uuid.eq(&channel_uuid))
.load::<models::FeedMeta>(&mut connection)
.expect("Expect find channel");
}
}

Expand Down Expand Up @@ -136,48 +138,9 @@ impl Article {
for uuid in channel_uuids {
query = query.bind::<Text, _>(uuid);
}
}

match filter.read_status {
Some(0) => {
1;
}
Some(status) => {
query = query
.sql(" AND A.read_status = ?")
.bind::<Integer, _>(status);
}
None => {
1;
}
}

query = query.sql(" ORDER BY A.pub_date DESC ");

if let Some(l) = filter.limit {
query = query.sql(" limit ?").bind::<Integer, _>(l);
limit = l;
}

if let Some(c) = filter.cursor {
query = query.sql(" OFFSET ?").bind::<Integer, _>((c - 1) * limit);
}

let result = query
.load::<ArticleQueryItem>(&mut connection)
.expect("Expect loading articles");

ArticleQueryResult { list: result }
}

/// get today articles for Today collection
pub fn get_today_articles(filter: ArticleFilter) -> ArticleQueryResult {
let mut connection = establish_connection();
let mut query = diesel::sql_query("").into_boxed();
let mut limit = 12;

query = query.sql(
"
} else if let Some(_is_today) = filter.is_today {
query = query.sql(
"
SELECT
A.id, A.uuid,
A.feed_uuid,
Expand All @@ -196,67 +159,30 @@ impl Article {
articles as A
ON C.uuid = A.feed_uuid
WHERE DATE(A.create_date) = DATE('now')",
);

match filter.read_status {
Some(0) => {
1;
}
Some(status) => {
query = query
.sql(" AND A.read_status = ?")
.bind::<Integer, _>(status);
}
None => {
1;
}
}

query = query.sql(" ORDER BY A.pub_date DESC ");

if let Some(l) = filter.limit {
query = query.sql(" limit ?").bind::<Integer, _>(l);
limit = l;
}

if let Some(c) = filter.cursor {
query = query.sql(" OFFSET ?").bind::<Integer, _>((c - 1) * limit);
);
} else {
query = query.sql(
"
SELECT
A.id, A.uuid,
A.feed_uuid,
C.title as feed_title,
C.link as feed_url,
A.link,
A.title,
A.feed_url,
A.description as description,
A.pub_date,
A.create_date,
A.read_status
FROM
feeds as C
LEFT JOIN
articles as A
ON C.uuid = A.feed_uuid ",
);
}

let result = query
.load::<ArticleQueryItem>(&mut connection)
.expect("Expect loading articles");

ArticleQueryResult { list: result }
}

/// get all articles for All Items collection
pub fn get_all_articles(filter: ArticleFilter) -> ArticleQueryResult {
let mut connection = establish_connection();
let mut query = diesel::sql_query("").into_boxed();
let mut limit = 12;

query = query.sql(
"
SELECT
A.id, A.uuid,
A.feed_uuid,
C.title as feed_title,
C.link as feed_url,
A.link,
A.title,
A.feed_url,
A.description as description,
A.pub_date,
A.create_date,
A.read_status
FROM
feeds as C
LEFT JOIN
articles as A
ON C.uuid = A.feed_uuid ",
);

match filter.read_status {
Some(0) => {
1;
Expand Down Expand Up @@ -324,7 +250,7 @@ impl Article {
result.pop()
} else {
None
}
};
}

pub fn mark_as_read(params: MarkAllUnreadParam) -> usize {
Expand Down Expand Up @@ -449,7 +375,7 @@ impl Article {
pub fn purge_articles() -> usize {
let user_config = get_user_config();

if let Some(cfg) = user_config {
if let Some(cfg) = user_config {
if cfg.purge_on_days == 0 {
return 0;
}
Expand All @@ -462,12 +388,9 @@ impl Article {
query = query.filter(schema::articles::read_status.eq(2));
}

let query = query
.filter(schema::articles::create_date.lt(expired_date));
let query = query.filter(schema::articles::create_date.lt(expired_date));

let result = query
.execute(&mut connection)
.expect("purge failed!");
let result = query.execute(&mut connection).expect("purge failed!");

log::info!("{:?} articles purged", result);

Expand Down
40 changes: 3 additions & 37 deletions src-tauri/src/server/handlers/article.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use actix_web::{get, post, put, web, Responder, Result};
use actix_web::{get, post, web, Responder, Result};
use serde::{Deserialize, Serialize};

use crate::core;
Expand Down Expand Up @@ -89,7 +89,9 @@ pub async fn handle_articles(
) -> Result<impl Responder> {
let filter = feed::article::ArticleFilter {
feed_uuid: query.feed_uuid.clone(),
folder_uuid: query.folder_uuid.clone(),
item_type: query.item_type.clone(),
is_today: query.is_today.clone(),
read_status: query.read_status.clone(),
cursor: query.cursor.clone(),
limit: query.limit.clone(),
Expand All @@ -100,40 +102,6 @@ pub async fn handle_articles(
Ok(web::Json(res))
}

#[get("/api/all-articles")]
pub async fn handle_get_all_articles(
query: web::Query<feed::article::ArticleFilter>,
) -> Result<impl Responder> {
let filter = feed::article::ArticleFilter {
feed_uuid: query.feed_uuid.clone(),
item_type: query.item_type.clone(),
read_status: query.read_status.clone(),
cursor: query.cursor.clone(),
limit: query.limit.clone(),
};

let res = feed::article::Article::get_all_articles(filter);

Ok(web::Json(res))
}

#[get("/api/today-articles")]
pub async fn handle_get_today_articles(
query: web::Query<feed::article::ArticleFilter>,
) -> Result<impl Responder> {
let filter = feed::article::ArticleFilter {
feed_uuid: query.feed_uuid.clone(),
item_type: query.item_type.clone(),
read_status: query.read_status.clone(),
cursor: query.cursor.clone(),
limit: query.limit.clone(),
};

let res = feed::article::Article::get_today_articles(filter);

Ok(web::Json(res))
}

pub fn config(cfg: &mut web::ServiceConfig) {
cfg
.service(handle_get_article_best_image)
Expand All @@ -144,7 +112,5 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.service(handle_mark_as_read)
.service(handle_update_article_read_status)
.service(handle_articles)
.service(handle_get_all_articles)
.service(handle_get_today_articles)
;
}
1 change: 0 additions & 1 deletion src-tauri/src/server/handlers/common.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use actix_web::{get, post, web, Responder, Result};
use log::kv::ToValue;
use serde::{Deserialize, Serialize};

use crate::core::common;
Expand Down
1 change: 0 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { appWindow } from "@tauri-apps/api/window";
import { emit, listen } from "@tauri-apps/api/event";

import { useBearStore } from "@/stores";
import * as dataAgent from "./helpers/dataAgent";
import { RouteConfig } from "./config";

import { CommandPanel } from "./command";
Expand Down
16 changes: 0 additions & 16 deletions src/helpers/dataAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,22 +87,6 @@ export const getArticleList = async (
return req;
};

export const getTodayArticleList = async (filter: any) => {
return request.get('/today-articles', {
params: {
...filter
}
});
};

export const getAllArticleList = async (filter: any) => {
return request.get('/all-articles', {
params: {
...filter
}
})
};

export const fetchFeed = async (url: string): Promise<[any, string]> => {
return invoke("fetch_feed", { url });
};
Expand Down
1 change: 0 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { ArticleContainer } from "./layout/Article";
import { SearchPage } from "./layout/Search";
import { LocalPage } from "./layout/Local";
import { SettingPage } from "./layout/Setting";

import "./index.css";

const router = createBrowserRouter([
Expand Down
11 changes: 6 additions & 5 deletions src/layout/Article/Layout1.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { useEffect, useRef, useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import { ArticleList } from "@/components/ArticleList";
import { useBearStore } from "@/stores";
import { useQuery } from "@/helpers/parseXML";

import { Filter, CheckCheck, RefreshCw } from "lucide-react";
import {
Expand All @@ -20,10 +19,11 @@ import { useArticle } from "./useArticle";
import { loadFeed } from "@/hooks/useLoadFeed";

export const Layout1 = React.memo(
(props: { feedUuid: string; type: string }) => {
(props: { feedUuid?: string; type?: string }) => {
const { feedUuid, type } = props;
// @ts-ignore
const params: { name: string } = useParams();

const store = useBearStore((state) => ({
viewMeta: state.viewMeta,
article: state.article,
Expand Down Expand Up @@ -53,7 +53,8 @@ export const Layout1 = React.memo(
}
};

const markAllRead = () => {};
const markAllRead = () => {
};

const changeFilter = (id: any) => {
if (store.filterList.some((_) => _.id === parseInt(id, 10))) {
Expand All @@ -64,7 +65,7 @@ export const Layout1 = React.memo(
};

return (
<div className="grow-0 basis-[var(--app-article-width)] border-r">
<div className="shrink-0 basis-[var(--app-article-width)] border-r">
<div className="h-[var(--app-toolbar-height)] grid grid-cols-[auto_1fr] items-center justify-between border-b">
<div
className="
Expand Down
4 changes: 2 additions & 2 deletions src/layout/Article/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import styles from "./index.module.scss";
import { useQuery } from "@/helpers/parseXML";

export const ArticleContainer = (): JSX.Element => {
const [feedUrl, type, feedUuid] = useQuery();
const [, type, feedUuid] = useQuery();
const store = useBearStore((state) => ({
article: state.article,
setArticle: state.setArticle,
Expand All @@ -26,7 +26,7 @@ export const ArticleContainer = (): JSX.Element => {

return (
<div className={classNames(styles.article)}>
<Layout1 feedUuid={feedUuid || ""} type={type || ""} />
<Layout1 feedUuid={feedUuid} type={type} />
<View />

<ArticleDialogView
Expand Down
Loading

0 comments on commit 6d2e56f

Please sign in to comment.