Skip to content

Commit

Permalink
fix: remove env
Browse files Browse the repository at this point in the history
  • Loading branch information
dancixx committed Aug 29, 2024
1 parent a1c527a commit 4dca4ad
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ tracing = { version = "0.1", optional = true }
http = "1"
surrealdb = { version = "1.5.4", features = ["protocol-http"] }
chrono = "0.4.38"
serde = "1.0.204"
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.122"
pulldown-cmark = "0.11.0"
serde-wasm-bindgen = "0.6.5"
Expand Down
46 changes: 44 additions & 2 deletions src/posts.rs → src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,26 @@ impl Default for Post {
}

#[server(endpoint = "/posts")]
pub async fn select_posts() -> Result<Vec<Post>, ServerFnError> {
pub async fn select_posts(
#[server(default)] tags: Vec<String>,
) -> Result<Vec<Post>, ServerFnError> {
use crate::ssr::AppState;
use chrono::{DateTime, Utc};
use leptos::expect_context;

let AppState { db, .. } = expect_context::<AppState>();
let mut query = format!("SELECT *, author.* from post ORDER BY created_at DESC;");
if !tags.is_empty() {
let tags = tags
.iter()
.map(|tag| format!(r#""{}""#, tag))
.collect::<Vec<_>>();
query = format!(
"SELECT *, author.* from post WHERE tags CONTAINSANY [{0}] ORDER BY created_at DESC;",
tags.join(", ")
);
}

let query = format!("SELECT *, author.* from post ORDER BY created_at DESC;");
let query = db.query(&query).await;

if let Err(e) = query {
Expand All @@ -90,6 +102,36 @@ pub async fn select_posts() -> Result<Vec<Post>, ServerFnError> {
Ok(posts)
}

#[server(endpoint = "/tags")]
pub async fn select_tags() -> Result<Vec<String>, ServerFnError> {
use crate::ssr::AppState;
use leptos::expect_context;

let AppState { db, .. } = expect_context::<AppState>();

let query = format!("SELECT tags from post;");
let query = db.query(&query).await;

if let Err(e) = query {
return Err(ServerFnError::from(e));
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Tags {
tags: Vec<String>,
}
let tags = query?.take::<Vec<Tags>>(0)?;
let mut tags = tags.iter().flat_map(|t| t.tags.clone()).collect::<Vec<_>>();
tags.sort();
let tags = tags
.into_iter()
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();

Ok(tags)
}

#[server(endpoint = "/post")]
pub async fn select_post(slug: String) -> Result<Post, ServerFnError> {
use crate::ssr::AppState;
Expand Down
2 changes: 1 addition & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn App() -> impl IntoView {
view! { <ErrorTemplate outside_errors /> }.into_view()
}>
<Routes>
<Route path="" view=home::Component ssr=SsrMode::Async />
<Route path="" view=home::Component />
<Route path="/post/:slug" view=post::Component ssr=SsrMode::Async />
</Routes>
</Router>
Expand Down
68 changes: 65 additions & 3 deletions src/home.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
use leptos::*;
use leptos_router::*;

use crate::posts::{increment_views, select_posts};
use crate::api::{increment_views, select_posts, select_tags};

#[component]
pub fn Component() -> impl IntoView {
let navigate = use_navigate();
let posts = create_blocking_resource(
let selected_tags = create_rw_signal(Vec::<String>::new());
let tags = create_blocking_resource(
|| (),
move |_| async move { select_posts().await.unwrap_or_default() },
move |_| async move { select_tags().await.unwrap_or_default() },
);
let posts = create_blocking_resource(
move || selected_tags.get(),
move |selected_tags| async move { select_posts(selected_tags).await.unwrap_or_default() },
);
let increment_view = create_action(move |id: &String| {
let id = id.clone();
Expand All @@ -22,6 +27,63 @@ pub fn Component() -> impl IntoView {
{
let navigate = navigate.clone();
view! {
<div class="flex flex-wrap flex-row text-xs gap-1 px-4">
<button
on:click=move |_| selected_tags.update(|prev| prev.clear())
class="bg-primary text-white px-2 py-1 rounded-lg transition-all duration-500 cursor-pointer"
class=("underline", move || selected_tags.get().is_empty())
>
{"All"}
</button>
<For
each=move || tags.get().unwrap_or_default()
key=|tag| tag.clone()
children=move |tag| {
view! {
<button
on:click={
let tag = tag.clone();
move |_| {
selected_tags
.update(|prev| {
if prev.contains(&tag) {
*prev = prev
.clone()
.into_iter()
.filter(|v| v != &tag)
.collect::<Vec<_>>();
} else {
*prev = prev
.clone()
.into_iter()
.chain(std::iter::once(tag.clone()))
.collect();
}
});
}
}
class="px-2 py-1 rounded-lg transition-all duration-500 cursor-pointer hover:bg-white hover:text-black"
class=(
"bg-white",
{
let tag = tag.clone();
move || selected_tags.get().contains(&tag)
},
)
class=(
"text-black",
{
let tag = tag.clone();
move || selected_tags.get().contains(&tag)
},
)
>
{tag}
</button>
}
}
/>
</div>
<For
each=move || posts.get().unwrap_or_default()
key=|post| post.id.id.to_string()
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
pub mod api;
pub mod app;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fileserv;
pub mod home;
pub mod post;
pub mod posts;

#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
Expand Down
9 changes: 6 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ async fn main() {
use dotenvy::dotenv;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use surrealdb::{engine::remote::http::{Http, Https}, opt::auth::Root, Surreal};
use surrealdb::{
engine::remote::http::{Http, Https},
opt::auth::Root,
Surreal,
};

let env_result = dotenv();
if env_result.is_err() {
Expand All @@ -29,13 +33,12 @@ async fn main() {
let ns = env::var("SURREAL_NS").unwrap_or("rustblog".to_string());
let db_name = env::var("SURREAL_DB").unwrap_or("rustblog".to_string());


let db = if protocol == "http" {
Surreal::new::<Http>(host).await.unwrap()
} else {
Surreal::new::<Https>(host).await.unwrap()
};

db.signin(Root {
username: &username,
password: &password,
Expand Down
13 changes: 12 additions & 1 deletion src/post.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use pulldown_cmark::{html, Parser};

use crate::posts::select_post;
use crate::api::select_post;

#[component]
pub fn Component() -> impl IntoView {
Expand All @@ -15,6 +16,15 @@ pub fn Component() -> impl IntoView {

view! {
<Suspense fallback=|| ()>
{post
.get()
.unwrap_or_default()
.tags
.into_iter()
.map(|tag| {
view! { <Meta name=tag.to_string() content=tag.to_string() /> }
})
.collect::<Vec<_>>()}
{move || {
post.with(|post| {
let post = post.clone().unwrap_or_default();
Expand Down Expand Up @@ -51,6 +61,7 @@ pub fn Component() -> impl IntoView {
class="my-6 prose max-w-3xl mx-auto prose-h3:text-white prose-code:before:content-none prose-code:after:content-none prose-code:text-[#ffbd2e] prose-strong:text-white prose-h1:text-white prose-h1:text-3xl prose-h2:text-white prose-h2:text-2xl prose-ul:text-white prose-p:text-white prose-a:text-[#ffbd2e]"
inner_html=html_output
/>

</article>
}
})
Expand Down

0 comments on commit 4dca4ad

Please sign in to comment.