feat: add likes

+ add ability for user to like a posts
+ add ability for user ot remove a like
+ add display of reply and like count
This commit is contained in:
Stevan Freeborn
2023-09-14 23:02:47 -05:00
parent 9cc9077017
commit 40515b3099
8 changed files with 161 additions and 12 deletions
+2 -1
View File
@@ -9,6 +9,7 @@
"rehype", "rehype",
"signup", "signup",
"svix", "svix",
"tailwindcss" "tailwindcss",
"totp"
] ]
} }
+2
View File
@@ -15,6 +15,7 @@ import type {
FunctionReference, FunctionReference,
} from "convex/server"; } from "convex/server";
import type * as http from "../http"; import type * as http from "../http";
import type * as likes from "../likes";
import type * as posts from "../posts"; import type * as posts from "../posts";
import type * as users from "../users"; import type * as users from "../users";
@@ -28,6 +29,7 @@ import type * as users from "../users";
*/ */
declare const fullApi: ApiFromModules<{ declare const fullApi: ApiFromModules<{
http: typeof http; http: typeof http;
likes: typeof likes;
posts: typeof posts; posts: typeof posts;
users: typeof users; users: typeof users;
}>; }>;
+99
View File
@@ -0,0 +1,99 @@
import { v } from 'convex/values';
import { mutation, query } from './_generated/server';
import { userQuery } from './users';
export const addLike = mutation({
args: { postId: v.id('posts') },
handler: async (ctx, args) => {
const clerkUser = await ctx.auth.getUserIdentity();
if (clerkUser === null) {
return;
}
const user = await userQuery(ctx, clerkUser.subject);
if (user === null) {
return;
}
const existingLike = await ctx.db
.query('likes')
.withIndex('by_user_post_id', q =>
q.eq('userId', user._id).eq('postId', args.postId)
)
.unique();
if (existingLike !== null) {
return;
}
await ctx.db.insert('likes', { postId: args.postId, userId: user._id });
},
});
export const removeLike = mutation({
args: { postId: v.id('posts') },
handler: async (ctx, args) => {
const clerkUser = await ctx.auth.getUserIdentity();
if (clerkUser === null) {
return;
}
const user = await userQuery(ctx, clerkUser.subject);
if (user === null) {
return;
}
const existingLike = await ctx.db
.query('likes')
.withIndex('by_user_post_id', q =>
q.eq('userId', user._id).eq('postId', args.postId)
)
.unique();
if (existingLike === null) {
return;
}
await ctx.db.delete(existingLike._id);
},
});
export const getLike = query({
args: { postId: v.id('posts') },
handler: async (ctx, args) => {
const clerkUser = await ctx.auth.getUserIdentity();
if (clerkUser === null) {
return;
}
const user = await userQuery(ctx, clerkUser.subject);
if (user === null) {
return;
}
return await ctx.db
.query('likes')
.withIndex('by_post_user_id', q =>
q.eq('postId', args.postId).eq('userId', user._id)
)
.unique();
},
});
export const getPostLikeCount = query({
args: { postId: v.id('posts') },
handler: async (ctx, args) => {
const likes = await ctx.db
.query('likes')
.withIndex('by_post_user_id', q => q.eq('postId', args.postId))
.collect();
return likes.length;
},
});
+12
View File
@@ -135,3 +135,15 @@ export const getRepliesByParentId = query({
return { ...replies, page: repliesWithUserData }; return { ...replies, page: repliesWithUserData };
}, },
}); });
export const getPostReplyCount = query({
args: { postId: v.id('posts') },
handler: async (ctx, args) => {
const replies = await ctx.db
.query('posts')
.withIndex('by_parent_id', q => q.eq('parentPostId', args.postId))
.collect();
return replies.length;
},
});
+6
View File
@@ -42,6 +42,12 @@ export default defineSchema(
}) })
.index('by_user_id', ['userId']) .index('by_user_id', ['userId'])
.index('by_parent_id', ['parentPostId']), .index('by_parent_id', ['parentPostId']),
likes: defineTable({
postId: v.id('posts'),
userId: v.id('users'),
})
.index('by_user_post_id', ['userId', 'postId'])
.index('by_post_user_id', ['postId', 'userId']),
}, },
{ schemaValidation: false } { schemaValidation: false }
); );
+1 -1
View File
@@ -32,7 +32,7 @@ export default function PostPage({
if (replyRef.current !== null && isReply) { if (replyRef.current !== null && isReply) {
replyRef.current.scrollIntoView(); replyRef.current.scrollIntoView();
} }
}, [isReply, post]); }, [isReply, user]);
async function submitAction({ async function submitAction({
clerkUserId, clerkUserId,
+37 -8
View File
@@ -1,6 +1,8 @@
import { useMutation, useQuery } from 'convex/react';
import Link from 'next/link'; import Link from 'next/link';
import { BiSolidLike } from 'react-icons/bi'; import { BiSolidLike } from 'react-icons/bi';
import { BsFillReplyFill } from 'react-icons/bs'; import { BsFillReplyFill } from 'react-icons/bs';
import { api } from '../../convex/_generated/api';
import { Id } from '../../convex/_generated/dataModel'; import { Id } from '../../convex/_generated/dataModel';
export default function PostActionButton({ export default function PostActionButton({
@@ -10,22 +12,49 @@ export default function PostActionButton({
postId: Id<'posts'>; postId: Id<'posts'>;
showReply: boolean; showReply: boolean;
}) { }) {
const like = useQuery(api.likes.getLike, { postId });
const likeCount = useQuery(api.likes.getPostLikeCount, { postId });
const replyCount = useQuery(api.posts.getPostReplyCount, { postId });
const removeLike = useMutation(api.likes.removeLike);
const addLike = useMutation(api.likes.addLike);
const isLiked = like !== null;
async function handleLikeClick() {
if (isLiked) {
await removeLike({ postId });
return;
}
await addLike({ postId });
}
return ( return (
<div className='flex items-center gap-4'> <div className='flex items-center gap-4'>
{showReply ? ( {showReply && replyCount !== undefined ? (
<Link <Link
className='px-3 py-2 border border-gray-600 rounded-md hover:bg-primary-accent hover:text-white' className='flex items-center justify-center gap-2 px-3 py-1 border border-gray-600 rounded-md hover:bg-primary-accent hover:text-white'
href={{ pathname: `/posts/${postId}`, query: { reply: true } }} href={{ pathname: `/posts/${postId}`, query: { reply: true } }}
> >
<BsFillReplyFill /> <BsFillReplyFill />
<div className='flex items-center justify-center h-6 w-6 rounded-full text-xs bg-secondary-gray text-white'>
{replyCount}
</div>
</Link> </Link>
) : null} ) : null}
<button {like !== undefined && likeCount !== undefined ? (
type='button' <button
className='px-3 py-2 border border-gray-600 rounded-md' onClick={handleLikeClick}
> type='button'
<BiSolidLike /> className={`flex items-center justify-center gap-2 px-3 py-1 border border-gray-600 rounded-md ${
</button> isLiked ? 'text-primary-accent' : ''
}`}
>
<BiSolidLike />{' '}
<div className='flex items-center justify-center h-6 w-6 rounded-full text-xs bg-secondary-gray text-white'>
{likeCount}
</div>
</button>
) : null}
</div> </div>
); );
} }
+2 -2
View File
@@ -27,7 +27,7 @@ export default function Reply({ post }: { post: PostWithUserDto }) {
</div> </div>
<div className='flex flex-col flex-1 w-full border border-gray-600 rounded-md'> <div className='flex flex-col flex-1 w-full border border-gray-600 rounded-md'>
<div className='flex flex-col w-full p-1'> <div className='flex flex-col w-full p-1'>
<div className='flex justify-between bg-primary-gray p-2'> <div className='flex justify-between dark:bg-primary-gray p-2'>
<div className='text-sm'> <div className='text-sm'>
{`${username} `} {`${username} `}
<span className='text-[#7a838f]'>{`replied on ${month} ${day}, ${year}`}</span> <span className='text-[#7a838f]'>{`replied on ${month} ${day}, ${year}`}</span>
@@ -37,7 +37,7 @@ export default function Reply({ post }: { post: PostWithUserDto }) {
) : null} ) : null}
</div> </div>
<div className='p-1'> <div className='p-1'>
<div className='p-2 rounded-md bg-secondary-gray'> <div className='p-2 rounded-md dark:bg-secondary-gray'>
<PostContent content={Text.of(post.content).toString()} /> <PostContent content={Text.of(post.content).toString()} />
</div> </div>
</div> </div>