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

+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())),
}
}
}