Compare commits
3 commits
3178ccac2f
...
868539cfad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
868539cfad | ||
|
|
1bdc48f5c9 | ||
| 11cba5caf0 |
13 changed files with 445 additions and 263 deletions
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
|
@ -15,6 +15,7 @@
|
|||
"rundgelutschte",
|
||||
"Törnplanung",
|
||||
"Trintella",
|
||||
"uuidv",
|
||||
"vergenusswurzeln"
|
||||
],
|
||||
"python.testing.pytestArgs": [
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
from dotenv.main import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
from .routers import users, comments, newsletters, health
|
||||
from .routers import users, comments, newsletters, health, reactions
|
||||
from backend.internal.database import create_db_and_tables
|
||||
from fastapi import FastAPI
|
||||
from fastapi_crons import Crons
|
||||
|
|
@ -22,5 +22,6 @@ def on_startup():
|
|||
|
||||
app.include_router(users.router)
|
||||
app.include_router(comments.router)
|
||||
app.include_router(reactions.router)
|
||||
app.include_router(newsletters.router)
|
||||
app.include_router(health.router)
|
||||
|
|
@ -3,3 +3,17 @@
|
|||
|
||||
#Reference: https://isaacfei.com/posts/simple-like-system/
|
||||
|
||||
from sqlmodel import UUID
|
||||
import uuid
|
||||
from sqlmodel import table
|
||||
from dataclasses import dataclass
|
||||
from sqlmodel import Field
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
class BaseReaction(SQLModel):
|
||||
pass
|
||||
|
||||
@dataclass
|
||||
class Reaction(BaseReaction, table=True):
|
||||
slug: str = Field(primary_key=True)
|
||||
browser_id: str = Field(primary_key=True)
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health", include_in_schema=False)
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ router = APIRouter(
|
|||
|
||||
@router.post(
|
||||
path="/approve",
|
||||
tags=["newsletter"],
|
||||
status_code=201
|
||||
)
|
||||
def approve_newsletter(secret: str = Form(), session: Session = Depends(get_session)):
|
||||
|
|
|
|||
|
|
@ -1,5 +1,50 @@
|
|||
from os import stat
|
||||
from sqlmodel import select
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from fastapi import HTTPException
|
||||
from backend.models.reaction import Reaction
|
||||
from backend.internal.database import get_session
|
||||
from fastapi import Depends
|
||||
from sqlmodel import Session
|
||||
from fastapi import APIRouter
|
||||
router = APIRouter(
|
||||
prefix="/reactions",
|
||||
tags=["reactions"]
|
||||
)
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_reaction(reaction: Reaction, session: Session = Depends(get_session)):
|
||||
print(reaction)
|
||||
try:
|
||||
session.add(reaction)
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
session.rollback()
|
||||
raise HTTPException(HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
# addReaction
|
||||
# delete Reaction
|
||||
# get Reactions by slug
|
||||
@router.get("/{slug}", status_code=200)
|
||||
def get_reaction_count_for_post(slug: str, session: Session = Depends(get_session))-> int:
|
||||
reactions = session.exec(select(Reaction).where(Reaction.slug == slug)).all()
|
||||
print(reactions)
|
||||
return len(reactions)
|
||||
|
||||
@router.get("/", status_code=200)
|
||||
def have_i_reacted(slug:str, browser_id: str, session: Session = Depends(get_session)) -> bool:
|
||||
result = session.exec(select(Reaction).where(Reaction.slug == slug, Reaction.browser_id == browser_id)).one_or_none()
|
||||
if (result): return True
|
||||
else: return False
|
||||
|
||||
@router.delete("", status_code=200)
|
||||
def delete_reaction(reaction: Reaction, session: Session = Depends(get_session)) :
|
||||
db_reaction = session.exec(select(Reaction).where(Reaction.slug == reaction.slug, Reaction.browser_id == reaction.browser_id)).one_or_none()
|
||||
try:
|
||||
session.delete(db_reaction)
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
session.rollback()
|
||||
raise HTTPException(HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ from fastapi_limiter.depends import RateLimiter
|
|||
|
||||
router = APIRouter(
|
||||
prefix="/users",
|
||||
dependencies=[],
|
||||
tags=["users"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
|
@ -73,7 +73,7 @@ def register_user(new_user: NewUser, session: Session = Depends(get_session)):
|
|||
|
||||
@router.post(
|
||||
path="/login",
|
||||
status_code=201,
|
||||
status_code=200,
|
||||
dependencies=[Depends(RateLimiter(limiter=Limiter(Rate(3, Duration.SECOND * 30))))]
|
||||
)
|
||||
def login(user_code: str = Form(), session: Session = Depends(get_session)) -> str:
|
||||
|
|
@ -94,18 +94,18 @@ def forgot_user_code(email: str = Form(), session: Session = Depends(get_session
|
|||
pass # TODO: send Mail
|
||||
|
||||
|
||||
@router.get(path="/me", status_code=201)
|
||||
@router.get(path="/me", status_code=200)
|
||||
def get_current_user_info(current_user: User = Depends(get_current_user)) -> UserInfo:
|
||||
return UserInfo.model_validate(current_user)
|
||||
|
||||
|
||||
@router.delete(path="/me", status_code=201)
|
||||
@router.delete(path="/me", status_code=200)
|
||||
def delete(current_user: User = Depends(get_current_user), session: Session = Depends(get_session)) :
|
||||
session.delete(current_user)
|
||||
session.commit()
|
||||
|
||||
|
||||
@router.put(path="/me/subscription", status_code=201)
|
||||
@router.put(path="/me/subscription", status_code=200)
|
||||
def change_subscription(
|
||||
subscription: bool = Form(),
|
||||
current_user: User = Depends(get_current_user),
|
||||
|
|
|
|||
24
blog/package-lock.json
generated
24
blog/package-lock.json
generated
|
|
@ -10,9 +10,11 @@
|
|||
"@astrojs/mdx": "^7.0.8",
|
||||
"@astrojs/preact": "^6.0.5",
|
||||
"@astrojs/rss": "^4.0.19",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"astro": "^7.2.2",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"preact": "^10.29.8"
|
||||
"preact": "^10.29.8",
|
||||
"uuid": "^14.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jsonwebtoken": "^9.0.10"
|
||||
|
|
@ -2219,6 +2221,12 @@
|
|||
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@ungap/structured-clone": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.3.tgz",
|
||||
|
|
@ -6512,8 +6520,17 @@
|
|||
"engines": {
|
||||
"node": ">=18.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sxzz"
|
||||
"node_modules/uuid": {
|
||||
"version": "14.0.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.2.tgz",
|
||||
"integrity": "sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist-node/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/vfile": {
|
||||
|
|
@ -6770,4 +6787,5 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -15,9 +15,11 @@
|
|||
"@astrojs/mdx": "^7.0.8",
|
||||
"@astrojs/preact": "^6.0.5",
|
||||
"@astrojs/rss": "^4.0.19",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"astro": "^7.2.2",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"preact": "^10.29.8"
|
||||
"preact": "^10.29.8",
|
||||
"uuid": "^14.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jsonwebtoken": "^9.0.10"
|
||||
|
|
|
|||
67
blog/src/islands/Reaction.tsx
Normal file
67
blog/src/islands/Reaction.tsx
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { useEffect, useState } from "preact/hooks"
|
||||
import { api, BROWSER_ID, type Reaction } from "../lib/api"
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
export default function Reaction({ slug }: { slug: string }) {
|
||||
const [reaction, setReaction] = useState<Reaction>({ slug: slug, browser_id: "" })
|
||||
const [reactionCount, setReactionCount] = useState(0)
|
||||
const [haveReacted, setHaveReacted] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let browserId = localStorage.getItem(BROWSER_ID)
|
||||
|
||||
if (!browserId) {
|
||||
browserId = uuidv7()
|
||||
localStorage.setItem(BROWSER_ID, browserId)
|
||||
}
|
||||
|
||||
api.haveIReacted({ ...reaction, browser_id: browserId }).then((response: boolean) => {
|
||||
setHaveReacted(response)
|
||||
})
|
||||
|
||||
api.reactionCount(slug).then((count) => {
|
||||
setReactionCount(count)
|
||||
})
|
||||
|
||||
setReaction(prev => ({ ...prev, browser_id: browserId }))
|
||||
}, [])
|
||||
|
||||
const handleReaction = () => {
|
||||
let hasError = false
|
||||
if (!haveReacted) {
|
||||
try { api.createReaction(reaction) }
|
||||
catch (e) { hasError = true }
|
||||
finally {
|
||||
if (!hasError) {
|
||||
setHaveReacted(true)
|
||||
setReactionCount(prev => prev + 1)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try { api.deleteReaction(reaction) }
|
||||
catch (e) { hasError = true }
|
||||
finally {
|
||||
if (!hasError) {
|
||||
setHaveReacted(false)
|
||||
setReactionCount(prev => prev - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<button onClick={handleReaction}
|
||||
|
||||
style="
|
||||
font-size: 1rem;
|
||||
width: 100%;
|
||||
padding:8px;
|
||||
font-family:Arial, Helvetica, sans-serif;
|
||||
">
|
||||
|
||||
|
||||
{haveReacted ? "♥ Yeah!" : "Hattest du Spaß beim Lesen?"} {reactionCount}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
import { useEffect, useState } from 'preact/hooks';
|
||||
import { api, type User } from '../lib/api';
|
||||
import React from 'preact/compat';
|
||||
import { navigateBack, isEmailValid } from './Util';
|
||||
|
||||
export default function RegisterForm() {
|
||||
const [user, setUser] = React.useState<User>({ 'email': '', 'name': '', 'subscription': true });
|
||||
const [user, setUser] = useState<User>({ 'email': '', 'name': '', 'subscription': true });
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleRegistration = async () => {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import Main from "./Main.astro";
|
|||
import { formatLocalizedDateString } from "../lib/formatDate";
|
||||
import type { PostData } from "../content.config";
|
||||
import NavBack from "../islands/NavBack";
|
||||
import Reaction from "../islands/Reaction";
|
||||
|
||||
interface Props {
|
||||
postData: PostData;
|
||||
|
|
@ -34,6 +35,9 @@ const localeDate = formatLocalizedDateString(postData.date);
|
|||
</div>
|
||||
<article class="markdown-content">
|
||||
<slot />
|
||||
<div id="react">
|
||||
<Reaction slug={postData.slug} client:load />
|
||||
</div>
|
||||
<NavBack client:load />
|
||||
<p class="disclaimer">
|
||||
Disclaimer: Dieser Artikel ist ausschließlich privat und wird nicht
|
||||
|
|
|
|||
|
|
@ -1,12 +1,20 @@
|
|||
import { v7 as uuidv7, type UUIDTypes } from 'uuid';
|
||||
|
||||
export interface User {
|
||||
email: string;
|
||||
name: string;
|
||||
subscription: boolean;
|
||||
}
|
||||
|
||||
export interface Reaction {
|
||||
slug: string,
|
||||
browser_id: UUIDTypes
|
||||
}
|
||||
|
||||
const API_BASE = import.meta.env.PUBLIC_API_URL;
|
||||
export const AUTH_TOKEN_KEY = 'authToken'
|
||||
export const USER_KEY = 'user'
|
||||
export const BROWSER_ID = 'browser_id'
|
||||
|
||||
|
||||
|
||||
|
|
@ -91,6 +99,28 @@ class BlauwasserAPI {
|
|||
body: formData
|
||||
})
|
||||
}
|
||||
|
||||
async createReaction(reaction: Reaction): Promise<void> {
|
||||
return await this.fetchAPI('/reactions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(reaction)
|
||||
})
|
||||
}
|
||||
|
||||
async deleteReaction(reaction: Reaction): Promise<void> {
|
||||
return await this.fetchAPI('/reactions', {
|
||||
method: 'DELETE',
|
||||
body: JSON.stringify(reaction)
|
||||
})
|
||||
}
|
||||
|
||||
async reactionCount(slug: string): Promise<number> {
|
||||
return await this.fetchAPI(`/reactions/${slug}`, { method: 'GET' })
|
||||
}
|
||||
|
||||
async haveIReacted(reaction: Reaction): Promise<boolean> {
|
||||
return await this.fetchAPI(`/reactions/?slug=${reaction.slug}&browser_id=${reaction.browser_id}`, {method: 'GET'})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue