Likes / Votes Toggle
elements man recipes/likes-toggleA "like" or "vote" toggles a row in a join table: insert when the user toggles
on, delete when they toggle off. Use this pattern for likes, hearts,
upvotes, bookmarks, follows, and similar one-row-per-user-per-thing
reactions. Partition the LiveTable by the parent id
so a like reaches only the pages watching that item; the insert handler sets the
row's userId from the session, and the delete handler refuses a row whose
userId is not the caller's.
Migration
Scaffold the migration with elements create migration. The -tables flag
stubs out the table with the standard primary key, timestamps, and
touchUpdatedAt trigger so you don't write that boilerplate by hand.
Terminalelements create migration 'add comment likes' -tables=commentLikes
That writes app/migrations/<timestamp>-add-comment-likes.migration.sql. Open
it and add the foreign-key columns plus the unique constraint, the parts
specific to this feature.
app/migrations/<timestamp>-add-comment-likes.migration.sql-- add comment likes -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table commentLikes ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), commentId uuid not null references comments(id) on delete cascade, userId uuid not null references users(id) on delete cascade, unique (commentId, userId) ); create trigger commentLikesTouchUpdatedAt before update on commentLikes for each row execute function touchUpdatedAt();
The three lines added to the scaffold's table are commentId, userId, and
unique (commentId, userId). The unique constraint makes Postgres reject a
second like from the same user on the same comment, so two clicks at the same
time insert one row.
Comment template
Terminalelements create template comment
That writes app/shared/templates/comment/{index.ehtml, style.css}. Update
index.ehtml.
The template declares its own LiveTable at module level and exports it so parent
pages can open a view per row. The onToggle function is declared in the same
file, since only this template calls it.
app/shared/templates/comment/index.ehtmlimport "./style.css"; import { LiveTable, LiveView, ForbiddenError, session } from "@elements/app"; export interface Comment { id: string; postId: string; userId: string; body: string; } export interface CommentLike { id: string; commentId: string; userId: string; } export let commentLikes: LiveTable<CommentLike> = new LiveTable<CommentLike>({ insert: (item) => { session.isLoggedInOrThrow(); return commentLikes.insert({ ...item, userId: session.getOrThrow('userId'), }); }, delete: (item) => { session.isLoggedInOrThrow(); if (item.userId !== session.getOrThrow('userId')) { throw new ForbiddenError(); } return commentLikes.delete(item); }, }); function onToggle(likes: LiveView<CommentLike>) { let mine = likes.find(l => l.userId === session.getOrThrow('userId')); if (mine) { likes.delete(mine); } else { likes.insert({ userId: session.getOrThrow('userId') }); } } <CommentItem ( c: Comment, likes: LiveView<CommentLike>, )> <p>{c.body}</p> <button onclick={() => onToggle(likes)}> {likes.length} {likes.length === 1 ? "like" : "likes"} </button> </CommentItem>
The page below opens the table with view({ commentId }). Each app server sends
a like only to the views whose commentId it matches, so the count for one
comment only updates templates watching that comment. Both handlers call session.isLoggedInOrThrow() first,
which throws AuthError for an anonymous caller; only then do they read
session.getOrThrow('userId'). insert overwrites userId with the session's,
so a signed-in user cannot like as somebody else. delete refuses a row the
caller does not own.
Both handlers finish by calling commentLikes.insert or commentLikes.delete
on the declaration, which runs the LiveTable's generated statement against the
table. The declaration carries an explicit
LiveTable<CommentLike> annotation because its initializer refers to it.
likes.length is reactive, so the button label updates on every insert and
delete.
Post page
Terminalelements create page post
The page renders a list of comments and opens one view per comment, then passes
each view to <CommentItem> in the likes attribute. CommentItem is a named
export of its .ehtml module, like every template that is not the page's
<html>. view() runs in
the route on the server, and the browser receives the view with its rows,
subscribed to later changes.
app/pages/post/index.tsimport { Request, Response, sql, LiveView } from "@elements/app"; import { Comment, CommentLike, commentLikes } from "#app/shared/templates/comment"; import post, { Post } from "./template"; export default function route(req: Request, res: Response) { let p = sql<Post>(` select * from posts where id = ${req.params.id} `).firstOrThrow("post not found"); let comments = sql<Comment>(` select * from comments where postId = ${p.id} `).all(); let likes: Record<string, LiveView<CommentLike>> = {}; for (let c of comments) { likes[c.id] = commentLikes.view({ commentId: c.id }); } return new post({ post: p, comments, likes, }); }
firstOrThrow("post not found") raises NotFoundError (a safe 404) when no row
matches, so the client gets a 404 response and the route never reads a missing row.
The likes are opened here, one view per comment, because view() has to run on
the server: it reads rows and opens a subscription, and a template also renders
in the browser, where there is no database to read and no channel to open. The
views are keyed by comment id, so the template passes likes[c.id] to each
CommentItem.
app/pages/post/template.ehtmlimport "./style.css"; import { LiveView } from "@elements/app"; import { CommentItem, Comment, CommentLike, } from "#app/shared/templates/comment"; export interface Post { id: string; title: string; } <html class="page-post" ( post: Post, comments: Comment[], likes: Record<string, LiveView<CommentLike>>, )> <main class="page-shell"> <h1>{post.title}</h1> <CommentItem e:for={c of comments} c={c} likes={likes[c.id]}/> </main> </html>
Routes
Register the page in index.ts:
index.tsimport post from "#app/pages/post"; // ... app.route("/posts/:id", post);
Notes
- The partition fills
commentIdon insert, so the payload inonTogglecarries onlyuserId. PassingcommentIdwith a value other than the view's throwsPartitionMismatchErrorbefore anything is sent. - A second click while the delete is still being sent likes the comment again.
The optimistic delete has already removed the row from the view, so
likes.findreturns nothing andonToggleinserts a new row. - The same pattern handles upvote / downvote (store the direction as a
value: 1 | -1column), star ratings (store aratingint), or any other one-row-per-user-per-thing reaction.