mirror of
https://github.com/Lumither/nocturne.git
synced 2026-10-17 10:26:21 +00:00
feat(blog) pagination
This commit is contained in:
14 files changed
+219
-88
No files matched your search
@@ -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()})))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use crate::constants::PAGE_SIZE;
|
||||
use axum::{extract::Query, extract::State, http::StatusCode, Json};
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures::future::join_all;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
use sqlx::{PgPool, postgres::PgRow, query, Row};
|
||||
use sqlx::{postgres::PgRow, query, PgPool, Row};
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -12,13 +13,19 @@ pub struct Params {
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
const PAGE_SIZE: u32 = 6;
|
||||
|
||||
pub async fn get_post_list(
|
||||
State(db_connection): State<PgPool>,
|
||||
Query(params): Query<Params>,
|
||||
) -> 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")
|
||||
.bind(PAGE_SIZE as i32)
|
||||
@@ -34,7 +41,7 @@ pub async fn get_post_list(
|
||||
);
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json::from(json!(("error", e.to_string()))),
|
||||
Json::from(json!({"error": e.to_string()})),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod get_page_count;
|
||||
pub mod get_post;
|
||||
pub mod get_post_list;
|
||||
@@ -1 +1,3 @@
|
||||
pub const GLOBAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%z";
|
||||
|
||||
pub const PAGE_SIZE: u32 = 6;
|
||||
+31
-12
@@ -4,16 +4,16 @@ use std::num::ParseIntError;
|
||||
use std::process::exit;
|
||||
use std::str::FromStr;
|
||||
|
||||
use axum::Router;
|
||||
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_page_count::get_page_count;
|
||||
use crate::api::get::get_post::get_post;
|
||||
use crate::api::get::get_post_list::get_post_list;
|
||||
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 constants;
|
||||
@@ -23,6 +23,16 @@ mod model;
|
||||
|
||||
#[tokio::main]
|
||||
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() {
|
||||
Ok(_) => {
|
||||
println!("[Info] env loaded from .env file, starting up...")
|
||||
@@ -42,11 +52,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
Err(_) => 3001,
|
||||
};
|
||||
|
||||
let db_uri: String = env::var("DB_URI").unwrap_or_else(|e| {
|
||||
error!("Invalid or missing env var: DB_URI: {}", e.to_string());
|
||||
exit(1);
|
||||
});
|
||||
let db_connect_option = PgConnectOptions::from_str(&db_uri)
|
||||
let db_connect_option = PgConnectOptions::from_str(dbg!(&parse_db_uri()))
|
||||
.unwrap()
|
||||
.disable_statement_logging();
|
||||
|
||||
@@ -64,6 +70,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app = Router::new()
|
||||
.route("/refresh_posts", post(refresh))
|
||||
.route("/get_post_list", get(get_post_list))
|
||||
.route("/get_page_count", get(get_page_count))
|
||||
.route("/get_post/:post_id", get(get_post))
|
||||
.with_state(db_pool);
|
||||
|
||||
@@ -81,3 +88,15 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
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}")
|
||||
}
|
||||
Reference in new issue
Block a user