feat: show author name instead of user x

This commit was merged in pull request #7.
This commit is contained in:
2025-06-24 21:14:35 -04:00
parent 7242579c17
commit 6bda5876ba
8 changed files with 154 additions and 39 deletions
+4 -5
View File
@@ -5,6 +5,8 @@ from sqlalchemy import pool
from alembic import context from alembic import context
from app.database import Base
# this is the Alembic Config object, which provides # this is the Alembic Config object, which provides
# access to the values within the .ini file in use. # access to the values within the .ini file in use.
config = context.config config = context.config
@@ -17,8 +19,7 @@ if config.config_file_name is not None:
# add your model's MetaData object here # add your model's MetaData object here
# for 'autogenerate' support # for 'autogenerate' support
# from myapp import mymodel # from myapp import mymodel
# target_metadata = mymodel.Base.metadata target_metadata = Base.metadata
target_metadata = None
# other values from the config, defined by the needs of env.py, # other values from the config, defined by the needs of env.py,
# can be acquired: # can be acquired:
@@ -64,9 +65,7 @@ def run_migrations_online() -> None:
) )
with connectable.connect() as connection: with connectable.connect() as connection:
context.configure( context.configure(connection=connection, target_metadata=target_metadata)
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction(): with context.begin_transaction():
context.run_migrations() context.run_migrations()
@@ -0,0 +1,71 @@
"""Add author_name to blogs
Revision ID: c9b28e38d00c
Revises:
Create Date: 2025-06-24 20:51:56.034469
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = 'c9b28e38d00c'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_blogs_author_id'), table_name='blogs')
op.drop_index(op.f('ix_blogs_id'), table_name='blogs')
op.drop_index(op.f('ix_blogs_title'), table_name='blogs')
op.drop_table('blogs')
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('blogs',
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('author_id', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('body', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), server_default=sa.text('now()'), autoincrement=False, nullable=False),
sa.Column('updated_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=True),
sa.Column('published_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=True),
sa.Column('word_count', sa.INTEGER(), autoincrement=False, nullable=True),
sa.Column('version', sa.INTEGER(), autoincrement=False, nullable=True),
sa.Column('read_time', sa.INTEGER(), autoincrement=False, nullable=True),
sa.Column('language', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True),
sa.Column('view_count', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column('like_count', sa.INTEGER(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('blogs_pkey'))
)
op.create_index(op.f('ix_blogs_title'), 'blogs', ['title'], unique=False)
op.create_index(op.f('ix_blogs_id'), 'blogs', ['id'], unique=False)
op.create_index(op.f('ix_blogs_author_id'), 'blogs', ['author_id'], unique=False)
op.create_table('users',
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column('username', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('hashed_password', sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column('permissions', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),
sa.Column('subscriber', sa.BOOLEAN(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('users_pkey'))
)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
# ### end Alembic commands ###
+1
View File
@@ -16,6 +16,7 @@ class Blog(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True) title = Column(String, index=True)
author_id = Column(Integer, nullable=False, index=True) author_id = Column(Integer, nullable=False, index=True)
author_name = Column(String, nullable=False, index=True)
description = Column(String, nullable=True) description = Column(String, nullable=True)
body = Column(String, nullable=False) body = Column(String, nullable=False)
created_at = Column( created_at = Column(
+2
View File
@@ -5,6 +5,7 @@ from pydantic import AwareDatetime, BaseModel, EmailStr
class BlogBase(BaseModel): class BlogBase(BaseModel):
title: str title: str
author_id: int author_id: int
author_name: str
description: Optional[str] = None description: Optional[str] = None
body: str body: str
created_at: AwareDatetime created_at: AwareDatetime
@@ -30,6 +31,7 @@ class BlogUpdate(BaseModel):
title: Optional[str] = None title: Optional[str] = None
description: Optional[str] = None description: Optional[str] = None
author_name: Optional[str] = None
body: Optional[str] = None body: Optional[str] = None
created_at: Optional[str] = None created_at: Optional[str] = None
updated_at: Optional[str] = None updated_at: Optional[str] = None
+19 -18
View File
@@ -64,6 +64,7 @@ const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
const logout = () => { const logout = () => {
localStorage.removeItem("token"); localStorage.removeItem("token");
localStorage.removeItem("user_id");
setIsAuthenticated(false); setIsAuthenticated(false);
navigate("/signin"); navigate("/signin");
}; };
@@ -107,7 +108,10 @@ function BlogPage() {
className="block p-4 border rounded hover:bg-gray-100 dark:hover:bg-gray-800" className="block p-4 border rounded hover:bg-gray-100 dark:hover:bg-gray-800"
> >
<h3 className="text-xl font-semibold">{blog.title}</h3> <h3 className="text-xl font-semibold">{blog.title}</h3>
<p className="text-sm text-gray-500">By {blog.author_id}</p> <p className="italic text-gray-600 dark:text-gray-400">
{blog.description}
</p>
<p className="text-sm text-gray-500">By {blog.author_name}</p>
</Link> </Link>
))} ))}
</div> </div>
@@ -118,10 +122,9 @@ function BlogPage() {
// Page for creating a blog post // Page for creating a blog post
function CreateBlog() { function CreateBlog() {
const [fileName, setFileName] = useState<string>(""); const [fileName, setFileName] = useState<string>("");
const [title, setTitle] = useState<string>(""); const [title, setTitle] = useState("");
const username = localStorage.getItem("user_id") || ""; const [description, setDescription] = useState("");
const [author, setAuthor] = useState<string>(username); const [authorName, setAuthorName] = useState("");
const [description, setDescription] = useState<string>("");
const [content, setContent] = useState<string>(""); const [content, setContent] = useState<string>("");
const navigate = useNavigate(); const navigate = useNavigate();
@@ -135,33 +138,31 @@ function CreateBlog() {
setFileName(file.name); setFileName(file.name);
const baseName = file.name.replace(/\.[^.]+$/, ""); const baseName = file.name.replace(/\.[^.]+$/, "");
setTitle(baseName); setTitle(baseName);
setAuthor(username); setAuthorName(authorName);
}; };
reader.readAsText(file); reader.readAsText(file);
}; };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const userId = Number(localStorage.getItem("user_id"));
try { try {
const body = { const body = {
title: title, title,
author_id: localStorage.getItem("user_id"), author_id: userId, // still from localStorage
author_name: authorName, // from the form field
description: description, description: description,
body: content, body: content,
created_at: new Date(Date.now()).toISOString(), created_at: new Date().toISOString(),
updated_at: new Date(Date.now()).toISOString(), updated_at: new Date().toISOString(),
published_at: new Date(Date.now()).toISOString(), published_at: new Date().toISOString(),
word_count: countWords(content), word_count: countWords(content),
version: 1,
read_time: 0,
language: "US",
}; };
const res = await fetch(`${API_URL}/blogs`, { await fetch(`${API_URL}/blogs`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
alert(res);
navigate("/blog"); navigate("/blog");
} catch (err: any) { } catch (err: any) {
alert(err.message); alert(err.message);
@@ -203,8 +204,8 @@ function CreateBlog() {
<input <input
id="author" id="author"
type="text" type="text"
value={author} value={authorName}
onChange={(e) => setAuthor(e.target.value)} onChange={(e) => setAuthorName(e.target.value)}
className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2" className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2"
/> />
</div> </div>
+27 -5
View File
@@ -26,21 +26,43 @@ export function BlogViewer() {
const isAuthor = me === String(blog.author_id); const isAuthor = me === String(blog.author_id);
const handleDelete = async () => {
if (!window.confirm(`Are you sure you want to delete ${blog.title}`))
return;
try {
const res = await fetch(`${API_URL}/blogs/${slug}`, {
method: "DELETE",
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(await res.text());
navigate("/");
} catch (err) {
console.error("Delete failed:", err);
alert("Could not delete post. See console for details.");
}
};
return ( return (
<div className="max-w-2xl mx-auto py-10 space-y-6"> <div className="max-w-2xl mx-auto py-10 space-y-6">
{isAuthor && ( {isAuthor && (
<div className="flex space-x-4">
<button <button
onClick={() => navigate(`/blog/${slug}/edit`)} onClick={() => navigate(`/blog/${slug}/edit`)}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
> >
Edit this post Edit
</button> </button>
<button
onClick={handleDelete}
className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
>
Delete
</button>
</div>
)} )}
<h1 className="text-3xl font-bold">{blog.title.toUpperCase()}</h1> <h1 className="text-3xl font-bold">{blog.title.toUpperCase()}</h1>
<p className="text-sm text-gray-500">By User {blog.author_id}</p> <p className="text-sm text-gray-500">By {blog.author_name}</p>
<p className="italic text-gray-600 dark:text-gray-400">
{blog.description}
</p>
<div className="markdown-body mx-auto p-4"> <div className="markdown-body mx-auto p-4">
<Markdown <Markdown
remarkPlugins={[remarkGfm, remarkRehype]} remarkPlugins={[remarkGfm, remarkRehype]}
+16 -5
View File
@@ -7,10 +7,11 @@ import { countWords } from "./countWords";
export function EditBlog() { export function EditBlog() {
const { slug } = useParams<{ slug: string }>(); const { slug } = useParams<{ slug: string }>();
const [blog, setBlog] = useState<Blog | undefined>(undefined); const [blog, setBlog] = useState<Blog | null>(null);
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [description, setDescription] = useState(""); const [description, setDescription] = useState("");
const [body, setBody] = useState(""); const [body, setBody] = useState("");
const [authorName, setAuthorName] = useState("");
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
@@ -22,6 +23,7 @@ export function EditBlog() {
setTitle(data.title); setTitle(data.title);
setDescription(data.description); setDescription(data.description);
setBody(data.body); setBody(data.body);
setAuthorName(data.author_name);
}) })
.catch(console.error); .catch(console.error);
}, [slug]); }, [slug]);
@@ -30,14 +32,14 @@ export function EditBlog() {
async function handleSubmit(e: FormEvent) { async function handleSubmit(e: FormEvent) {
e.preventDefault(); e.preventDefault();
const updatedBlog = { const updatedBlog = {
title, title,
description, description,
body, body,
author_name: authorName, // from the form field
updated_at: new Date().toISOString(), updated_at: new Date().toISOString(),
word_count: countWords(body), word_count: countWords(body),
version: blog ? blog.version : 1, version: blog ? blog.version + 1 : 1,
}; };
const res = await fetch(`${API_URL}/blogs/${slug}`, { const res = await fetch(`${API_URL}/blogs/${slug}`, {
@@ -45,9 +47,8 @@ export function EditBlog() {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(updatedBlog), body: JSON.stringify(updatedBlog),
}); });
if (res.ok) { if (res.ok) {
navigate(`/blog/${slug}`); // go back to the viewer navigate(`/blogs/${slug}`); // go back to the viewer
} else { } else {
console.error("Update failed:", await res.text()); console.error("Update failed:", await res.text());
alert("Could not update the post. See console for details."); alert("Could not update the post. See console for details.");
@@ -74,6 +75,16 @@ export function EditBlog() {
className="w-full border px-2 py-1 rounded" className="w-full border px-2 py-1 rounded"
/> />
</div> </div>
<div>
<label className="block font-medium">Author Name</label>
<input
type="text"
value={authorName}
onChange={(e) => setAuthorName(e.target.value)}
className="w-full border px-2 py-1 rounded"
required
/>
</div>
<div> <div>
<label className="block font-medium">Body (Markdown)</label> <label className="block font-medium">Body (Markdown)</label>
<textarea <textarea
+9 -1
View File
@@ -1,8 +1,16 @@
export interface Blog { export interface Blog {
id: number; id: number;
title: string; title: string;
author_id: string;
description: string; description: string;
body: string; body: string;
author_id: number;
author_name: string;
created_at: string;
updated_at: string;
published_at: string;
word_count: number;
version: number; version: number;
read_time: number;
language: string;
tags: string[];
} }