feat(blog) pagination

This commit is contained in:
lumither committed 2024-08-13 22:32:27 +08:00
1 parent 9f72bb01b7
commit eb7ea991ac
14 files changed
+219 -88

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
use crate::constants::PAGE_SIZE;
use axum::extract::State;
use axum::Json;
use serde_json::{json, Value};
use sqlx::{query, PgPool, Row};
use tracing::error;
pub async fn get_page_count(
State(db_connection): State<PgPool>,
) -> Result<Json<Value>, Json<Value>> {
match query("select cast(ceil(count(*) / $1) as integer) as res from post")
.bind(PAGE_SIZE as f32)
.fetch_one(&db_connection)
.await
{
Ok(res) => {
let res: i32 = res.get("res");
Ok(Json::from(json!({"res": res})))
}
Err(e) => {
error!("Failed to get blog page count: {}", e.to_string());
Err(Json::from(json!({"error": e.to_string()})))
}
}
}
+12 -5
View File
@@ -1,9 +1,10 @@
use crate::constants::PAGE_SIZE;
use axum::{extract::Query, extract::State, http::StatusCode, Json}; use axum::{extract::Query, extract::State, http::StatusCode, Json};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use futures::future::join_all; use futures::future::join_all;
use serde::Deserialize; use serde::Deserialize;
use serde_json::{json, Map, Value}; use serde_json::{json, Map, Value};
use sqlx::{PgPool, postgres::PgRow, query, Row}; use sqlx::{postgres::PgRow, query, PgPool, Row};
use tracing::error; use tracing::error;
use uuid::Uuid; use uuid::Uuid;
@@ -12,13 +13,19 @@ pub struct Params {
page: Option<u32>, page: Option<u32>,
} }
const PAGE_SIZE: u32 = 6;
pub async fn get_post_list( pub async fn get_post_list(
State(db_connection): State<PgPool>, State(db_connection): State<PgPool>,
Query(params): Query<Params>, Query(params): Query<Params>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> { ) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let offset = PAGE_SIZE * (params.page.unwrap_or(1) - 1); let search_param_page = params.page.unwrap_or(1);
if search_param_page < 1 {
return Err((
StatusCode::BAD_REQUEST,
Json::from(json!({"error": "`page` should be greater than 0"})),
));
}
let offset = PAGE_SIZE * (search_param_page - 1);
let post_list = sqlx::query("SELECT * FROM post ORDER BY first_update DESC LIMIT $1 OFFSET $2") let post_list = sqlx::query("SELECT * FROM post ORDER BY first_update DESC LIMIT $1 OFFSET $2")
.bind(PAGE_SIZE as i32) .bind(PAGE_SIZE as i32)
@@ -34,7 +41,7 @@ pub async fn get_post_list(
); );
return Err(( return Err((
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
Json::from(json!(("error", e.to_string()))), Json::from(json!({"error": e.to_string()})),
)); ));
} }
}; };
+1
View File
@@ -1,2 +1,3 @@
pub mod get_page_count;
pub mod get_post; pub mod get_post;
pub mod get_post_list; pub mod get_post_list;
+2
View File
@@ -1 +1,3 @@
pub const GLOBAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%z"; pub const GLOBAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%z";
pub const PAGE_SIZE: u32 = 6;
+31 -12
View File
@@ -4,16 +4,16 @@ use std::num::ParseIntError;
use std::process::exit; use std::process::exit;
use std::str::FromStr; use std::str::FromStr;
use axum::Router; use crate::api::get::get_page_count::get_page_count;
use axum::routing::{get, post};
use dotenv::dotenv;
use sqlx::ConnectOptions;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use tracing::{error, info, warn};
use crate::api::get::get_post::get_post; use crate::api::get::get_post::get_post;
use crate::api::get::get_post_list::get_post_list; use crate::api::get::get_post_list::get_post_list;
use crate::api::post::refresh::refresh; use crate::api::post::refresh::refresh;
use axum::routing::{get, post};
use axum::Router;
use dotenv::dotenv;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::ConnectOptions;
use tracing::{error, info, warn};
mod api; mod api;
mod constants; mod constants;
@@ -23,6 +23,16 @@ mod model;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
if let Some(env_file) = env::args().nth(1) {
match dotenv::from_filename(&env_file) {
Ok(_) => {
println!("[Info] env loaded from {}", env_file);
}
Err(e) => {
panic!("[Fatal] failed to read {}: {}", env_file, e);
}
}
};
match dotenv() { match dotenv() {
Ok(_) => { Ok(_) => {
println!("[Info] env loaded from .env file, starting up...") println!("[Info] env loaded from .env file, starting up...")
@@ -42,11 +52,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
Err(_) => 3001, Err(_) => 3001,
}; };
let db_uri: String = env::var("DB_URI").unwrap_or_else(|e| { let db_connect_option = PgConnectOptions::from_str(dbg!(&parse_db_uri()))
error!("Invalid or missing env var: DB_URI: {}", e.to_string());
exit(1);
});
let db_connect_option = PgConnectOptions::from_str(&db_uri)
.unwrap() .unwrap()
.disable_statement_logging(); .disable_statement_logging();
@@ -64,6 +70,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let app = Router::new() let app = Router::new()
.route("/refresh_posts", post(refresh)) .route("/refresh_posts", post(refresh))
.route("/get_post_list", get(get_post_list)) .route("/get_post_list", get(get_post_list))
.route("/get_page_count", get(get_page_count))
.route("/get_post/:post_id", get(get_post)) .route("/get_post/:post_id", get(get_post))
.with_state(db_pool); .with_state(db_pool);
@@ -81,3 +88,15 @@ async fn main() -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }
fn parse_db_uri() -> String {
let postgres_user = env::var("POSTGRES_USER").unwrap_or("".to_string());
let postgres_password = env::var("POSTGRES_PASSWORD").unwrap_or("".to_string());
let db_host = env::var("DB_HOST").unwrap_or("localhost".to_string());
let db_port = env::var("DB_PORT")
.unwrap_or("5432".to_string())
.to_string();
let postgres_db = env::var("POSTGRES_DB").unwrap_or("nocturne".to_string());
format!("postgresql://{postgres_user}:{postgres_password}@{db_host}:{db_port}/{postgres_db}")
}
+52
View File
@@ -0,0 +1,52 @@
'use client';
import React, { useEffect, useState } from 'react';
import { Pagination as NextUIPagination } from '@nextui-org/react';
import { useRouter, useSearchParams } from 'next/navigation';
const Pagination = ({ total }: {
total: number,
}) => {
const parsePage = Number(useSearchParams().get('page'));
const currPage = parsePage > 0 ? parsePage : 1;
const router = useRouter();
const maxMobileWidth: number = 768;
const [ isMobile, setIsMobile ] = useState(false);
useEffect(() => {
const updateMobileWidth = () => {
if (window.innerWidth <= maxMobileWidth) {
setIsMobile(true);
} else {
setIsMobile(false);
}
};
updateMobileWidth();
window.addEventListener('resize', updateMobileWidth);
return () => {
window.removeEventListener('resize', updateMobileWidth);
};
}, []);
return (
<div className={ 'w-full p-4 pt-6 flex justify-center' }>
<NextUIPagination
initialPage={ currPage }
total={ total }
siblings={ isMobile ? 0 : 1 }
size={ isMobile ? 'sm' : 'md' }
showControls
showShadow
color={ 'default' }
variant={ 'light' }
onChange={ (page) => {
router.push(`?page=${ page }`, { scroll: false });
} }
/>
</div>
);
};
export default Pagination;
+42
View File
@@ -0,0 +1,42 @@
'use server';
import React from 'react';
import { fetchNocturneApi } from '@/app/blog/api';
import { MotionDiv } from '@/app/public/MotionDiv';
import BlogPostCard from '@/app/blog/BlogPostCard';
import { Card, CardBody } from '@nextui-org/card';
const PostList = async ({ page }: { page: number }) => {
try {
const res = await fetchNocturneApi(`/get_post_list?page=${ page }`);
let posts = (await res.json() as any)['posts'];
return (
// blog list
<div className={ 'w-full' }>
<ul className={ 'flex flex-col items-center w-full space-y-7' }>
{ posts.map((post: JSON, key: number) => (
<li key={ key } className={ 'w-full' }>
<MotionDiv
initial={ { y: 20, opacity: 0 } }
animate={ { y: 0, opacity: 1 } }
transition={ { ease: 'easeInOut', duration: 0.5, delay: key * .2 + .25 } }
>
<BlogPostCard post={ post } />
</MotionDiv>
</li>)
) }
</ul>
</div>
);
} catch (e: any) {
return (
// todo: use Error.tsx
<Card className={ `w-full` }>
<CardBody>
Fatal: { e.toString() }
</CardBody>
</Card>);
}
};
export default PostList;
+2 -8
View File
@@ -13,15 +13,9 @@ const NOCTURNE_ENDPOINT = ((isServerSide = true) => {
} }
}); });
export async function fetchNocturneApi(path: string, isServerSideRequest = true): Promise<{ code: number, ret: any }> { export async function fetchNocturneApi(path: string, isServerSideRequest = true) {
let res = await fetch(`${ NOCTURNE_ENDPOINT(isServerSideRequest) }${ path }`, { return await fetch(`${ NOCTURNE_ENDPOINT(isServerSideRequest) }${ path }`, {
cache: 'no-cache' cache: 'no-cache'
}); });
if (!res.ok) {
return { code: res.status, ret: (await res.json()) };
}
return { code: res.status, ret: await res.json() };
} }
+20 -33
View File
@@ -1,39 +1,26 @@
import React from 'react'; import PostList from '@/app/blog/PostList';
import BlogPostCard from '@/app/blog/BlogPostCard'; import Pagination from '@/app/blog/Pagination';
import { Card, CardBody } from '@nextui-org/card';
import { MotionDiv } from '@/app/public/MotionDiv';
import { fetchNocturneApi } from '@/app/blog/api'; import { fetchNocturneApi } from '@/app/blog/api';
async function Blog() { async function Blog({ searchParams }: {
searchParams?: {
page?: number
};
}) {
const { code, ret } = await fetchNocturneApi('/get_post_list'); const parsePage = Number(searchParams?.page);
if (code == 200) { const currPage = parsePage > 0 ? parsePage : 1;
let posts = ret['posts']; const ret = await fetchNocturneApi(`/get_page_count`);
return ( const pageCount = (await ret.json() as any)['res'] as number;
// blog list
<ul className={ 'flex flex-col items-center w-full space-y-7' }> console.log(currPage);
{ posts.map((post: JSON, key: number) => (
<li key={ key } className={ 'w-full' }> return (
<MotionDiv <div className={ 'w-full min-w-full space-y-4' }>
initial={ { y: 20, opacity: 0 } } <PostList page={ currPage } />
animate={ { y: 0, opacity: 1 } } <Pagination total={ pageCount + 10 } />
transition={ { ease: 'easeInOut', duration: 0.5, delay: key * .2 + .25 } } </div>
> );
<BlogPostCard post={ post } />
</MotionDiv>
</li>)
) }
</ul>
);
} else {
return (
// todo: use Error.tsx
<Card className={ `w-full` }>
<CardBody>
Fatal: { ret }
</CardBody>
</Card>);
}
} }
export default Blog; export default Blog;
@@ -23,13 +23,15 @@ const MinifyPostCard = (props: Props) => {
<p className={ `text-tiny uppercase font-bold ${ img_url ? 'text-white/60' : 'text-black/60 dark:text-white/60' }` }>{ desc }</p> <p className={ `text-tiny uppercase font-bold ${ img_url ? 'text-white/60' : 'text-black/60 dark:text-white/60' }` }>{ desc }</p>
</CardHeader> </CardHeader>
{ img_url && { img_url &&
<div> <div className={ 'h-full' }>
<Image <div className={ 'relative h-[300px] overflow-hidden' }>
className={ 'object-cover object-center ' } <Image
src={ img_url } className={ 'object-cover object-center ' }
alt={ post.title } src={ img_url }
fill alt={ post.title }
/> fill
/>
</div>
<CardFooter <CardFooter
className="absolute transition-colors bg-zinc-300/80 dark:bg-gray-600/25 dark:backdrop-brightness-75 bottom-0 justify-between rounded-none"> className="absolute transition-colors bg-zinc-300/80 dark:bg-gray-600/25 dark:backdrop-brightness-75 bottom-0 justify-between rounded-none">
<div> <div>
+5 -5
View File
@@ -17,11 +17,11 @@ type Props = {
} }
async function PostCard(props: Props) { async function PostCard(props: Props) {
const { code, ret } = await fetchNocturneApi(`/get_post/${ props.id }`);
if (code == 200) {
try {
const res = await fetchNocturneApi(`/get_post/${ props.id }`);
const ret: any = await res.json();
return ( return (
<div> <div>
<Card className={ `max-w-full relative` }> <Card className={ `max-w-full relative` }>
@@ -85,11 +85,11 @@ async function PostCard(props: Props) {
</Card> </Card>
</div> </div>
); );
} else { } catch (e: any) {
return <div> return <div>
<Card className={ `w-full` }> <Card className={ `w-full` }>
<CardBody> <CardBody>
Fatal: { ret } Fatal: { e.toString() }
</CardBody> </CardBody>
</Card> </Card>
</div>; </div>;
+2 -2
View File
@@ -89,11 +89,11 @@ function Navbar() {
}, [ path ]); }, [ path ]);
const minMobileWidth: number = 1024; const maxMobileWidth: number = 1024;
const [ isMobile, setIsMobile ] = useState(false); const [ isMobile, setIsMobile ] = useState(false);
useEffect(() => { useEffect(() => {
const updateMobileWidth = () => { const updateMobileWidth = () => {
if (window.innerWidth <= minMobileWidth) { if (window.innerWidth <= maxMobileWidth) {
setIsMobile(true); setIsMobile(true);
} else { } else {
setIsMobile(false); setIsMobile(false);
+2 -2
View File
@@ -11,8 +11,8 @@ const nextConfig = {
hostname: 'pic.re' hostname: 'pic.re'
} }
] ]
}, }
output: 'standalone' // output: 'standalone'
}; };
export default nextConfig; export default nextConfig;
+14 -14
View File
@@ -9,15 +9,15 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@nextui-org/react": "^2.3.5", "@nextui-org/react": "^2.4.6",
"@types/react-syntax-highlighter": "^15.5.13", "@types/react-syntax-highlighter": "^15.5.13",
"framer-motion": "^11.2.10", "framer-motion": "^11.3.24",
"lxgw-wenkai-webfont": "^1.7.0", "lxgw-wenkai-webfont": "^1.7.0",
"next": "14.2.3", "next": "14.2.3",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"react": "^18", "react": "^18.3.1",
"react-dom": "^18", "react-dom": "^18.3.1",
"react-icons": "^5.1.0", "react-icons": "^5.2.1",
"react-markdown": "^9.0.1", "react-markdown": "^9.0.1",
"react-syntax-highlighter": "^15.5.0", "react-syntax-highlighter": "^15.5.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
@@ -28,15 +28,15 @@
"sharp": "^0.33.4" "sharp": "^0.33.4"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/typography": "^0.5.13", "@tailwindcss/typography": "^0.5.14",
"@types/node": "^20", "@types/node": "^20.14.15",
"@types/react": "^18", "@types/react": "^18.3.3",
"@types/react-dom": "^18", "@types/react-dom": "^18.3.0",
"autoprefixer": "^10.4.19", "autoprefixer": "^10.4.20",
"eslint": "^8", "eslint": "^8.57.0",
"eslint-config-next": "14.2.2", "eslint-config-next": "14.2.2",
"postcss": "^8", "postcss": "^8.4.41",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.9",
"typescript": "^5" "typescript": "^5.5.4"
} }
} }