add: shared structs, caching services, import task change

This commit is contained in:
wymiller committed 2026-11-09 00:04:22 -05:00
1 parent b64d5ba0ad
commit 5cb5dd8eb8
41 files changed
+875 -770

No files matched your search

@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"query": "SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": {
"columns": [
{
@@ -30,16 +30,21 @@
},
{
"ordinal": 5,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"ordinal": 7,
"name": "publish_date",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"ordinal": 8,
"name": "author_id",
"type_info": "Int4"
}
@@ -59,8 +64,9 @@
false,
true,
true,
true,
false
]
},
"hash": "3831b52c2db3d1114c4b01a761c74168b66904bacff847844d463454b7fcde43"
"hash": "1ae4bbbfd835587ea4389b3b4500d1b0f549d682f892a10586815014519bb8c4"
}
@@ -0,0 +1,68 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.is_featured IS true GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "post_id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "author_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "first_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "last_name",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "body",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
false,
false,
true,
true,
true
]
},
"hash": "24f4b8dd651c57a8cab3ffc2fae9bfe4cb276521854b2a0a0fba2e7081093421"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id LEFT JOIN comments c ON p.post_id = c.post_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY COUNT(c.comment_id) DESC LIMIT 3",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3",
"describe": {
"columns": [
{
@@ -35,11 +35,16 @@
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
}
@@ -55,8 +60,9 @@
false,
false,
true,
true,
true
]
},
"hash": "49768c8b986078bdfaad191b3ea1f07ca033b2a734162a3f8fcf0ef0a44c1e7f"
"hash": "4557c49e323c6b7c3246903e63e1c61c0f008e80308f65066bff7f4b70a8c7dd"
}
@@ -0,0 +1,68 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id LEFT JOIN comments c ON p.post_id = c.post_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY COUNT(c.comment_id) DESC LIMIT 3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "post_id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "author_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "first_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "last_name",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "body",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
false,
false,
true,
true,
true
]
},
"hash": "464d1fdbed6800f3b09e3abca989d79dfcca8a6680cb0ee324ba0790e4ec3484"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.created_at DESC LIMIT 10",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.view_count DESC LIMIT 3",
"describe": {
"columns": [
{
@@ -35,11 +35,16 @@
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
}
@@ -55,8 +60,9 @@
false,
false,
true,
true,
true
]
},
"hash": "053f5b53a743065aa0105903cdd0ec803861a2477c38a02754d2d350a34aaa68"
"hash": "7998c2354eacb1cfbeece7dc001f57e0ce4d3ca15b28940a631cd249b72d6dc3"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.created_at DESC LIMIT 10",
"describe": {
"columns": [
{
@@ -35,11 +35,16 @@
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
}
@@ -55,8 +60,9 @@
false,
false,
true,
true,
true
]
},
"hash": "0ec6c9d94fceba56112e78c82acc56ae01bc3c641e28ee21e331c06e2fd9e551"
"hash": "9cc954af48cf92abaa30a8d26499fded1ce30609c29b34d10cf98573d40bdbb6"
}
@@ -1,62 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.is_featured IS true GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "post_id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "author_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "first_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "last_name",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "body",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "publish_date",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
false,
false,
true,
true
]
},
"hash": "9d93a8a7c0a2442a511108af36d4adfb1ef8a2fac82448205654742f43dc4e75"
}
@@ -1,62 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.view_count DESC LIMIT 3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "post_id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "author_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "first_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "last_name",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "body",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "publish_date",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
false,
false,
true,
true
]
},
"hash": "ad39df8c37105f13b620f8898e570cdbc54d4bd4e402aac65a28c9aa81803831"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date, p.is_featured FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.post_id = $1 ORDER BY p.created_at DESC",
"query": "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date, p.is_featured FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.post_id = $1 ORDER BY p.created_at DESC",
"describe": {
"columns": [
{
@@ -35,16 +35,21 @@
},
{
"ordinal": 6,
"name": "body_gemtext",
"type_info": "Text"
},
{
"ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"ordinal": 8,
"name": "publish_date",
"type_info": "Timestamptz"
},
{
"ordinal": 8,
"ordinal": 9,
"name": "is_featured",
"type_info": "Bool"
}
@@ -63,8 +68,9 @@
false,
true,
true,
true,
false
]
},
"hash": "0891ec97ff1d5d5ab7fbc848ceb4e7ea4f46e2f6282170dfdf90ebc6ab6d5fd9"
"hash": "fb4bcc2eb710ceb4bb50ec1c62326b7d709cd53d44944acc2da2e371642bfe1a"
}
+2 -1
View File
@@ -1552,7 +1552,7 @@ dependencies = [
[[package]]
name = "public"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"axum 0.8.4",
"cache",
@@ -1560,6 +1560,7 @@ dependencies = [
"dotenvy",
"fred",
"gemi",
"rustls",
"serde",
"serde_json",
"sqlx",
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "public"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
authors = ["Wyatt J. Miller <wyatt@wyattjmiller.com"]
@@ -18,6 +18,7 @@ sqlx = { version = "0.8.2", features = [
"chrono",
"json",
] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
dotenvy = "0.15.7"
+2 -2
View File
@@ -1,7 +1,7 @@
use sqlx::{Pool, Postgres};
use crate::{
routes::{authors::Author, posts::Post},
models::{authors::Author, posts::Post},
utils::pagination::Pagination,
};
@@ -53,7 +53,7 @@ impl AuthorsDatasource {
let posts_query = sqlx::query_as!(
Post,
"SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
author_id,
pagination.limit,
offset,
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::{
routes::comments::{Comment, CommentInputPayload},
models::comments::{Comment, CommentInputPayload},
utils::pagination::Pagination,
};
use sqlx::{Pool, Postgres};
+7 -7
View File
@@ -1,11 +1,11 @@
use sqlx::{Pool, Postgres};
use crate::routes::posts::{Post, PostFeaturedVariant};
use crate::models::posts::{Post, PostFeaturedVariant};
pub struct PostsDatasource;
impl PostsDatasource {
pub async fn get_all(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.created_at DESC LIMIT 10")
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.created_at DESC LIMIT 10")
.fetch_all(pool)
.await
}
@@ -19,31 +19,31 @@ impl PostsDatasource {
.execute(pool)
.await;
sqlx::query_as!(PostFeaturedVariant, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date, p.is_featured FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.post_id = $1 ORDER BY p.created_at DESC", post_id)
sqlx::query_as!(PostFeaturedVariant, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date, p.is_featured FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.post_id = $1 ORDER BY p.created_at DESC", post_id)
.fetch_one(pool)
.await
}
pub async fn get_recent(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3")
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3")
.fetch_all(pool)
.await
}
pub async fn get_popular(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id LEFT JOIN comments c ON p.post_id = c.post_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY COUNT(c.comment_id) DESC LIMIT 3")
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id LEFT JOIN comments c ON p.post_id = c.post_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY COUNT(c.comment_id) DESC LIMIT 3")
.fetch_all(pool)
.await
}
pub async fn get_hot(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.view_count DESC LIMIT 3")
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.view_count DESC LIMIT 3")
.fetch_all(pool)
.await
}
pub async fn get_featured(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.is_featured IS true GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3")
sqlx::query_as!(Post, "SELECT p.post_id, p.author_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.is_featured IS true GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3")
.fetch_all(pool)
.await
}
+2 -2
View File
@@ -1,6 +1,6 @@
use sqlx::{FromRow, Pool, Postgres, Row};
use sqlx::{Pool, Postgres};
use crate::routes::projects::Project;
use crate::models::projects::Project;
pub struct ProjectsDatasource;
impl ProjectsDatasource {
+20 -17
View File
@@ -18,7 +18,9 @@ use tracing_subscriber::{filter, layer::SubscriberExt, prelude::*, util::Subscri
mod config;
mod datasources;
mod models;
mod routes;
mod services;
mod state;
mod utils;
@@ -125,19 +127,18 @@ async fn main() {
config::ServeAppConfig::Http => {
let state = app_state.clone();
let app = Router::new()
.merge(routes::root::RootRoute::routes())
.merge(routes::posts::PostsRoute::routes(&state))
.merge(routes::comments::CommentsRoute::routes(&state))
.merge(routes::authors::AuthorsRoute::routes(&state))
.merge(routes::projects::ProjectsRoute::routes(&state))
.merge(routes::http::root::RootRoute::routes())
.merge(routes::http::posts::PostsRoute::routes(&state))
.merge(routes::http::comments::CommentsRoute::routes(&state))
.merge(routes::http::authors::AuthorsRoute::routes(&state))
.merge(routes::http::projects::ProjectsRoute::routes(&state))
.layer(CorsLayer::permissive())
.layer(
TraceLayer::new_for_http()
.make_span_with(trace::DefaultMakeSpan::new().level(tracing::Level::INFO))
.on_response(trace::DefaultOnResponse::new().level(tracing::Level::INFO)),
)
.fallback(routes::root::RootRoute::not_found);
.fallback(routes::http::root::RootRoute::not_found);
// run it with hyper
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
@@ -148,24 +149,26 @@ async fn main() {
.unwrap();
}
config::ServeAppConfig::Gemini => {
rustls::crypto::ring::default_provider()
.install_default()
.expect("failed to install Rustls crypto provider");
let gemini_state = app_state.clone();
let mut router = GeminiRouter::default();
router.add_route("/", hello).unwrap();
// router.nest(prefix, endpoint)
let config = GeminiConfig::new("0.0.0.0:1965");
router.nest("/", routes::gemini::root::RootGeminiRoutes::routes().expect("Failed to construct Gemini root routes"));
router.nest("/posts", routes::gemini::posts::PostsGeminiRoutes::routes().expect("Failed to construct Gemini posts routes"));
let config = GeminiConfig::new("localhost");
let app = router.with_state(gemini_state);
let server = GeminiServer::new(app, "cert.der", "key.der", config).unwrap();
server.serve().await.unwrap();
let server = GeminiServer::new(app, "dev-cert.der", "dev-key.der", config).unwrap();
server
.serve_with_shutdown(shutdown_signal())
.await
.unwrap();
}
};
}
async fn hello() -> impl Into<GeminiResponse> {
"Hello, Gemini!"
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
+15
View File
@@ -0,0 +1,15 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Clone)]
pub struct Author {
pub author_id: i32,
pub first_name: String,
pub last_name: String,
pub bio: Option<String>,
pub image: Option<String>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct AuthorGetOneParams {
pub id: i32,
}
+26
View File
@@ -0,0 +1,26 @@
use serde::{Serialize, Deserialize};
use chrono::Utc;
use crate::utils::datetime::*;
#[derive(Deserialize, Serialize)]
pub struct CommentPathParams {
pub id: i32,
}
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Comment {
pub comment_id: i32,
pub name: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct CommentInputPayload {
pub name: String,
pub body: String,
pub post_id: i32,
}
+4
View File
@@ -0,0 +1,4 @@
pub mod authors;
pub mod posts;
pub mod projects;
pub mod comments;
+44
View File
@@ -0,0 +1,44 @@
use serde::{Deserialize, Serialize};
use chrono::Utc;
use crate::utils::datetime::*;
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub title: String,
pub body: String,
pub body_gemtext: Option<String>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub publish_date: Option<chrono::DateTime<Utc>>,
}
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct PostFeaturedVariant {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub title: String,
pub body: String,
pub body_gemtext: Option<String>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub publish_date: Option<chrono::DateTime<Utc>>,
pub is_featured: Option<bool>,
}
#[derive(Deserialize)]
pub struct PostGetOneParams {
pub id: i32,
}
+18
View File
@@ -0,0 +1,18 @@
use serde::{Serialize, Deserialize};
use crate::utils::datetime::*;
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Project {
pub project_id: i32,
pub title: String,
pub repo: Option<String>,
pub summary: String,
pub tech: String,
pub wip: Option<bool>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}
+2
View File
@@ -0,0 +1,2 @@
pub mod posts;
pub mod root;
+23
View File
@@ -0,0 +1,23 @@
use crate::state::AppState;
use gemi::{GeminiResponse, GeminiRouter};
pub struct PostsGeminiRoutes;
impl PostsGeminiRoutes {
pub fn routes() -> gemi::Result<GeminiRouter<AppState>> {
let mut router = GeminiRouter::default();
router.add_route("/", Self::root)?;
Ok(router)
}
async fn root() -> impl Into<GeminiResponse> {
"Hello, Gemini!"
}
async fn post_one() -> impl Into<GeminiResponse> {
// make call to database
// format post to Gemtext
// return response
""
}
}
+16
View File
@@ -0,0 +1,16 @@
use crate::state::AppState;
use gemi::{GeminiResponse, GeminiRouter};
pub struct RootGeminiRoutes;
impl RootGeminiRoutes {
pub fn routes() -> gemi::Result<GeminiRouter<AppState>> {
let mut router = GeminiRouter::default();
router.add_route("/", Self::root)?;
Ok(router)
}
async fn root() -> impl Into<GeminiResponse> {
"Hello, Gemini!"
}
}
@@ -10,24 +10,18 @@ use serde::{Deserialize, Serialize};
use crate::{
datasources::authors::AuthorsDatasource,
routes::posts::Post,
models::{
posts::Post,
authors::{
Author,
AuthorGetOneParams,
}
},
services::authors::*,
state::AppState,
utils::pagination::{Pagination, PaginationQuery},
};
#[derive(Deserialize, Serialize, Clone)]
pub struct Author {
pub author_id: i32,
pub first_name: String,
pub last_name: String,
pub bio: Option<String>,
pub image: Option<String>,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct AuthorGetOneParams {
pub id: i32,
}
#[derive(Deserialize, Serialize)]
pub struct AuthorPostsResponse {
@@ -55,39 +49,19 @@ impl AuthorsRoute {
};
let mut state = app_state.lock().await;
let cached: Option<Vec<Author>> = state
.cache
.get(String::from("authors:all"))
.await
.unwrap_or(None);
let cached = authors_cache::<Vec<Author>>(&mut state, String::from("all")).await;
if let Some(authors) = cached {
tracing::info!("grabbing all authors from cache");
return Ok(Json(authors));
}
match AuthorsDatasource::get_all(&state.database, pagination).await {
Ok(authors) => {
tracing::info!("grabbing all authors from the database");
if let a = &authors {
let author_cloned = a.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("authors:all"),
&author_cloned,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
}
set_authors_cache(
&app_state,
String::from("all"),
authors.clone(),
Expiration::EX(5),
);
Ok(Json(authors))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
@@ -99,40 +73,21 @@ impl AuthorsRoute {
Path(params): Path<AuthorGetOneParams>,
) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Author> = state
.cache
.get(format!("authors:{}", params.id))
.await
.unwrap_or(None);
let cached = authors_cache::<Author>(&mut state, params.id.to_string()).await;
if let Some(author) = cached {
tracing::info!("grabbing one author from cache");
return Ok(Json(author));
}
match AuthorsDatasource::get_one(&state.database, params.id).await {
Ok(author) => {
tracing::info!("grabbing all authors from the database");
if let a = &author {
let author_cloned = a.clone();
let state = app_state.clone();
set_authors_cache(
&app_state,
author.author_id.to_string(),
author.clone(),
Expiration::EX(5),
);
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
format!("authors:{}", author_cloned.author_id),
&author_cloned,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
}
Ok(Json(author))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
@@ -1,8 +1,8 @@
use crate::{
datasources::comments::CommentsDatasource,
models::comments::*,
state::AppState,
utils::{
datetime::*,
pagination::{Pagination, PaginationQuery},
},
};
@@ -14,29 +14,6 @@ use axum::{
Json,
};
use cache::{Expiration, SetOptions};
use chrono::Utc;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug)]
pub struct CommentInputPayload {
pub name: String,
pub body: String,
pub post_id: i32,
}
#[derive(Deserialize, Serialize)]
pub struct CommentPathParams {
id: i32,
}
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Comment {
pub comment_id: i32,
pub name: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
}
pub struct CommentsRoute;
impl CommentsRoute {
@@ -74,7 +51,6 @@ impl CommentsRoute {
let state = app_state.clone();
tokio::spawn(async move {
tracing::info!("update cache if key already exists!");
let mut s = state.lock().await;
let _ = s
.cache
+5
View File
@@ -0,0 +1,5 @@
pub mod authors;
pub mod comments;
pub mod posts;
pub mod projects;
pub mod root;
+253
View File
@@ -0,0 +1,253 @@
use crate::{
datasources::posts::PostsDatasource,
models::posts::*,
services::posts::*,
state::AppState,
utils::{
rss,
sitemap::{self, SitemapEntry},
},
};
use axum::http::{HeaderMap, HeaderValue};
use axum::{
extract::{Path, State},
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Json, Router,
};
use cache::Expiration;
use std::collections::HashMap;
pub struct PostsRoute;
impl PostsRoute {
pub fn routes(app_state: &AppState) -> Router {
// add more post routes here!
Router::new()
.route("/posts/all", get(PostsRoute::get_all))
.route("/posts/{id}", get(PostsRoute::get_one))
.route("/posts/recent", get(PostsRoute::get_recent_posts))
.route("/posts/popular", get(PostsRoute::get_popular_posts))
.route("/posts/hot", get(PostsRoute::get_hot_posts))
.route("/posts/featured", get(PostsRoute::get_featured_posts))
.route("/posts/rss", get(PostsRoute::get_rss_posts))
.route("/posts/sitemap", get(PostsRoute::get_sitemap))
.with_state(app_state.clone())
}
// get all posts
async fn get_all(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<Vec<Post>>(&mut state, String::from("all")).await;
if let Some(posts) = cached {
return Ok(Json(posts));
};
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
set_posts_cache(
&app_state,
String::from("all"),
posts.clone(),
Expiration::EX(10),
);
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get one post
async fn get_one(
State(app_state): State<AppState>,
Path(params): Path<PostGetOneParams>,
) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<PostFeaturedVariant>(&mut state, params.id.to_string()).await;
if let Some(post) = cached {
return Ok(Json(post));
};
match PostsDatasource::get_one(&state.database, params.id).await {
Ok(post) => {
set_posts_cache(
&app_state,
params.id.to_string(),
post.clone(),
Expiration::EX(10),
);
Ok(Json(post))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get recent posts
async fn get_recent_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<Vec<Post>>(&mut state, String::from("recent")).await;
if let Some(posts) = cached {
return Ok(Json(posts));
};
match PostsDatasource::get_recent(&state.database).await {
Ok(posts) => {
set_posts_cache(
&app_state,
String::from("recent"),
posts.clone(),
Expiration::EX(5),
);
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the highest view count
async fn get_popular_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<Vec<Post>>(&mut state, String::from("popular")).await;
if let Some(posts) = cached {
return Ok(Json(posts));
};
match PostsDatasource::get_popular(&state.database).await {
Ok(posts) => {
set_posts_cache(
&app_state,
String::from("popular"),
posts.clone(),
Expiration::EX(5),
);
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the most comments
async fn get_hot_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<Vec<Post>>(&mut state, String::from("hot")).await;
if let Some(posts) = cached {
return Ok(Json(posts));
};
match PostsDatasource::get_hot(&state.database).await {
Ok(posts) => {
set_posts_cache(
&app_state,
String::from("hot"),
posts.clone(),
Expiration::EX(5),
);
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get posts that are featured
async fn get_featured_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = posts_cache::<Vec<Post>>(&mut state, String::from("featured")).await;
if let Some(posts) = cached {
return Ok(Json(posts));
};
match PostsDatasource::get_featured(&state.database).await {
Ok(posts) => {
set_posts_cache(
&app_state,
String::from("featured"),
posts.clone(),
Expiration::EX(5),
);
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get rss posts
async fn get_rss_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let state = app_state.lock().await;
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
let web_url =
std::env::var("BASE_URI_WEB").expect("Environment BASE_URI_WEB variable found");
let mapped_posts: HashMap<String, Post> = posts
.into_iter()
.map(|post| (post.post_id.to_string(), post))
.collect();
let xml: String = rss::generate_rss(
"Wyatt's blog",
"Wyatt and friends",
web_url.as_str(),
&mapped_posts,
);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
async fn get_sitemap(State(app_state): State<AppState>) -> impl IntoResponse {
let state = app_state.lock().await;
// let cached: Option<Vec<Post>> = None; // TODO: maybe implement cache, later??
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
let web_url =
std::env::var("BASE_URI_WEB").expect("Environment BASE_URI_WEB variable found");
let mut entries: HashMap<String, SitemapEntry> = posts
.into_iter()
.map(|p| {
(
p.post_id.to_string(),
SitemapEntry {
location: format!("{}/posts/{}", web_url, p.post_id.to_string()),
lastmod: p.created_at.unwrap_or_else(|| chrono::Utc::now()),
},
)
})
.collect();
sitemap::get_static_pages(&mut entries, &web_url);
let xml: String = sitemap::generate_sitemap(&entries);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
}
@@ -0,0 +1,52 @@
use crate::{
datasources::projects::ProjectsDatasource,
state::AppState,
services::projects::*,
models::projects::*
};
use axum::{
extract::State,
http::StatusCode,
response::IntoResponse,
routing::get,
Json,
Router
};
use cache::Expiration;
pub struct ProjectsRoute;
impl ProjectsRoute {
pub fn routes(app_state: &AppState) -> Router {
Router::new()
.route("/projects", get(ProjectsRoute::get_all))
.with_state(app_state.clone())
}
async fn get_all(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached = projects_cache::<Vec<Project>>(&mut state, String::from("all")).await;
if let Some(projects) = cached {
return Ok(Json(projects));
};
match ProjectsDatasource::get_all(&state.database).await {
Ok(projects) => {
if let p = &projects {
let projects = p.clone();
set_projects_cache(
&app_state,
String::from("all"),
projects.clone(),
Expiration::EX(10),
);
};
Ok(Json(projects))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
}
File renamed without changes.
+2 -5
View File
@@ -1,5 +1,2 @@
pub mod authors;
pub mod comments;
pub mod posts;
pub mod projects;
pub mod root;
pub mod http;
pub mod gemini;
-407
View File
@@ -1,407 +0,0 @@
use crate::{
datasources::posts::PostsDatasource,
state::AppState,
utils::{
datetime::*,
rss,
sitemap::{self, SitemapEntry},
},
};
use axum::http::{HeaderMap, HeaderValue};
use axum::{
extract::{Path, State},
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Json, Router,
};
use cache::Expiration;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub publish_date: Option<chrono::DateTime<Utc>>,
}
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct PostFeaturedVariant {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub publish_date: Option<chrono::DateTime<Utc>>,
pub is_featured: Option<bool>,
}
#[derive(Deserialize)]
pub struct PostGetOneParams {
pub id: i32,
}
pub struct PostsRoute;
impl PostsRoute {
pub fn routes(app_state: &AppState) -> Router {
// add more post routes here!
Router::new()
.route("/posts/all", get(PostsRoute::get_all))
.route("/posts/{id}", get(PostsRoute::get_one))
.route("/posts/recent", get(PostsRoute::get_recent_posts))
.route("/posts/popular", get(PostsRoute::get_popular_posts))
.route("/posts/hot", get(PostsRoute::get_hot_posts))
.route("/posts/featured", get(PostsRoute::get_featured_posts))
.route("/posts/rss", get(PostsRoute::get_rss_posts))
.route("/posts/sitemap", get(PostsRoute::get_sitemap))
.with_state(app_state.clone())
}
// get all posts
async fn get_all(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:all"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing all posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing all posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:all"),
&posts,
Some(Expiration::EX(10)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get one post
async fn get_one(
State(app_state): State<AppState>,
Path(params): Path<PostGetOneParams>,
) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<PostFeaturedVariant> = state
.cache
.get(format!("posts:{}", params.id))
.await
.unwrap_or(None);
if let Some(post) = cached {
tracing::info!("grabbing one post from cache");
return Ok(Json(post));
};
match PostsDatasource::get_one(&state.database, params.id).await {
Ok(post) => {
tracing::info!("grabbing one post from database");
if let p = &post {
let post = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
format!("posts:{}", params.id),
&post,
Some(Expiration::EX(10)),
None,
false,
)
.await;
});
};
Ok(Json(post))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get recent posts
async fn get_recent_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:recent"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing recent posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_recent(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing recent posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:recent"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the highest view count
async fn get_popular_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:popular"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing popular posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_popular(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing popular posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:popular"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the most comments
async fn get_hot_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:hot"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing hot posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_hot(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing hot posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:hot"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get posts that are featured
async fn get_featured_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:featured"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing featured posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_featured(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing featured posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:featured"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get rss posts
async fn get_rss_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let state = app_state.lock().await;
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
let web_url =
std::env::var("BASE_URI_WEB").expect("Environment BASE_URI_WEB variable found");
let mapped_posts: HashMap<String, Post> = posts
.into_iter()
.map(|post| (post.post_id.to_string(), post))
.collect();
let xml: String = rss::generate_rss(
"Wyatt's blog",
"Wyatt and friends",
web_url.as_str(),
&mapped_posts,
);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
async fn get_sitemap(State(app_state): State<AppState>) -> impl IntoResponse {
let state = app_state.lock().await;
// let cached: Option<Vec<Post>> = None; // TODO: maybe implement cache, later??
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
let web_url =
std::env::var("BASE_URI_WEB").expect("Environment BASE_URI_WEB variable found");
let mut entries: HashMap<String, SitemapEntry> = posts
.into_iter()
.map(|p| {
(
p.post_id.to_string(),
SitemapEntry {
location: format!("{}/posts/{}", web_url, p.post_id.to_string()),
lastmod: p.created_at.unwrap_or_else(|| chrono::Utc::now()),
},
)
})
.collect();
sitemap::get_static_pages(&mut entries, &web_url);
let xml: String = sitemap::generate_sitemap(&entries);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
}
-70
View File
@@ -1,70 +0,0 @@
use crate::{datasources::projects::ProjectsDatasource, state::AppState, utils::datetime::*};
use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use cache::Expiration;
use serde::{Deserialize, Serialize};
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Project {
pub project_id: i32,
pub title: String,
pub repo: Option<String>,
pub summary: String,
pub tech: String,
pub wip: Option<bool>,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}
pub struct ProjectsRoute;
impl ProjectsRoute {
pub fn routes(app_state: &AppState) -> Router {
Router::new()
.route("/projects", get(ProjectsRoute::get_all))
.with_state(app_state.clone())
}
async fn get_all(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Project>> = state
.cache
.get(String::from("projects:all"))
.await
.unwrap_or(None);
if let Some(projects) = cached {
tracing::info!("grabbing all projects from cache");
return Ok(Json(projects));
};
match ProjectsDatasource::get_all(&state.database).await {
Ok(projects) => {
tracing::info!("grabbing all projects from database");
if let p = &projects {
let projects = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("projects:all"),
&projects,
Some(Expiration::EX(10)),
None,
false,
)
.await;
});
};
Ok(Json(projects))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
}
+35
View File
@@ -0,0 +1,35 @@
use cache::Expiration;
use crate::state::{AppInternalState, AppState};
use serde::de::DeserializeOwned;
use serde::Serialize;
pub async fn authors_cache<T: DeserializeOwned>(
app_state: &mut AppInternalState,
key: String,
) -> Option<T> {
app_state
.cache
.get(format!("authors:{key}"))
.await
.unwrap_or(None)
}
pub fn set_authors_cache<T>(app_state: &AppState, key: String, value: T, expiration: Expiration)
where
T: Serialize + DeserializeOwned + Send + Sync + 'static,
{
let app_state = app_state.clone();
tokio::spawn(async move {
let mut s = app_state.lock().await;
let _ = s
.cache
.set(
format!("authors:{key}"),
&value,
Some(expiration),
None,
false,
)
.await;
});
}
+3
View File
@@ -0,0 +1,3 @@
pub mod authors;
pub mod posts;
pub mod projects;
+34
View File
@@ -0,0 +1,34 @@
use crate::state::{AppInternalState, AppState};
use cache::Expiration;
use serde::{de::DeserializeOwned, Serialize};
pub async fn posts_cache<T: DeserializeOwned>(
app_state: &mut AppInternalState,
key: String,
) -> Option<T> {
app_state
.cache
.get(format!("posts:{key}"))
.await
.unwrap_or(None)
}
pub fn set_posts_cache<T>(app_state: &AppState, key: String, value: T, expiration: Expiration)
where
T: Serialize + DeserializeOwned + Send + Sync + 'static,
{
let app_state = app_state.clone();
tokio::spawn(async move {
let mut s = app_state.lock().await;
let _ = s
.cache
.set(
format!("posts:{key}"),
&value,
Some(expiration),
None,
false,
)
.await;
});
}
+35
View File
@@ -0,0 +1,35 @@
use cache::Expiration;
use crate::state::{AppInternalState, AppState};
use serde::de::DeserializeOwned;
use serde::Serialize;
pub async fn projects_cache<T: DeserializeOwned>(
app_state: &mut AppInternalState,
key: String,
) -> Option<T> {
app_state
.cache
.get(format!("projects:{key}"))
.await
.unwrap_or(None)
}
pub fn set_projects_cache<T>(app_state: &AppState, key: String, value: T, expiration: Expiration)
where
T: Serialize + DeserializeOwned + Send + Sync + 'static,
{
let app_state = app_state.clone();
tokio::spawn(async move {
let mut s = app_state.lock().await;
let _ = s
.cache
.set(
format!("projects:{key}"),
&value,
Some(expiration),
None,
false,
)
.await;
});
}
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::routes::posts;
use crate::models::posts;
use std::collections::HashMap;
use xml::escape::escape_str_pcdata;