Merge pull request #26 from StevanFreeborn/stevanfreeborn/feat/add-follows

feat: add follows
This commit is contained in:
Stevan Freeborn
2023-09-15 17:59:51 -05:00
committed by GitHub
17 changed files with 376 additions and 36 deletions
+2
View File
@@ -14,6 +14,7 @@ import type {
FilterApi,
FunctionReference,
} from "convex/server";
import type * as follows from "../follows";
import type * as http from "../http";
import type * as likes from "../likes";
import type * as posts from "../posts";
@@ -28,6 +29,7 @@ import type * as users from "../users";
* ```
*/
declare const fullApi: ApiFromModules<{
follows: typeof follows;
http: typeof http;
likes: typeof likes;
posts: typeof posts;
+116
View File
@@ -0,0 +1,116 @@
import { v } from 'convex/values';
import { mutation, query } from './_generated/server';
import { userQuery } from './users';
export const addFollow = mutation({
args: { followingId: v.id('users') },
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 existingFollow = await ctx.db
.query('follows')
.withIndex('by_following_follower_id', q =>
q.eq('following', args.followingId).eq('follower', user._id)
)
.unique();
if (existingFollow !== null) {
return;
}
await ctx.db.insert('follows', {
following: args.followingId,
follower: user._id,
});
},
});
export const removeFollow = mutation({
args: { followingId: v.id('users') },
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 existingFollow = await ctx.db
.query('follows')
.withIndex('by_following_follower_id', q =>
q.eq('following', args.followingId).eq('follower', user._id)
)
.unique();
if (existingFollow === null) {
return;
}
await ctx.db.delete(existingFollow._id);
},
});
export const getUserFollowerCount = query({
args: { userId: v.id('users') },
handler: async (ctx, args) => {
const followers = await ctx.db
.query('follows')
.withIndex('by_following', q => q.eq('following', args.userId))
.collect();
return followers.length;
},
});
export const getUserFollowingCount = query({
args: { userId: v.id('users') },
handler: async (ctx, args) => {
const followings = await ctx.db
.query('follows')
.withIndex('by_follower', q => q.eq('follower', args.userId))
.collect();
return followings.length;
},
});
export const getFollowing = query({
args: { followingId: v.id('users') },
handler: async (ctx, args) => {
const currentClerkUser = await ctx.auth.getUserIdentity();
if (currentClerkUser == null) {
return false;
}
const user = await userQuery(ctx, currentClerkUser.subject);
if (user == null) {
return false;
}
const following = await ctx.db
.query('follows')
.withIndex('by_following_follower_id', q =>
q.eq('following', args.followingId).eq('follower', user._id)
)
.unique();
return following !== null;
},
});
+56
View File
@@ -147,3 +147,59 @@ export const getPostReplyCount = query({
return replies.length;
},
});
export const getUserPostCount = query({
args: { userId: v.id('users') },
handler: async (ctx, args) => {
const posts = await ctx.db
.query('posts')
.withIndex('by_user_id', q => q.eq('userId', args.userId))
.filter(q => q.eq(q.field('parentPostId'), undefined))
.collect();
return posts.length;
},
});
export const getAllPostsWithUser = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const posts = await ctx.db
.query('posts')
.filter(q => q.eq(q.field('parentPostId'), undefined))
.order('desc')
.paginate(args.paginationOpts);
const postsWithUser = await Promise.all(
posts.page.map(async post => {
const user = await ctx.db.get(post.userId);
if (user === null) {
return {
...post,
user: {
_id: '' as Id<'users'>,
_creationTime: 0,
clerkUsername: null,
clerkImageUrl: '',
clerkUserId: '',
},
};
}
return {
...post,
user: {
_id: user._id,
_creationTime: user._creationTime,
clerkUsername: user.clerkUser.username,
clerkImageUrl: user.clerkUser.image_url,
clerkUserId: user.clerkUser.id,
},
};
})
);
return { ...posts, page: postsWithUser };
},
});
+7
View File
@@ -48,6 +48,13 @@ export default defineSchema(
})
.index('by_user_post_id', ['userId', 'postId'])
.index('by_post_user_id', ['postId', 'userId']),
follows: defineTable({
following: v.id('users'), // person being followed
follower: v.id('users'), // person following
})
.index('by_following', ['following'])
.index('by_follower', ['follower'])
.index('by_following_follower_id', ['following', 'follower']),
},
{ schemaValidation: false }
);
+17
View File
@@ -93,6 +93,15 @@ export const deleteUser = internalMutation({
.withIndex('by_user_post_id', q => q.eq('userId', userRecord._id))
.collect();
const userFollowers = await ctx.db
.query('follows')
.withIndex('by_following', q => q.eq('following', userRecord._id))
.collect();
const userFollowings = await ctx.db
.query('follows')
.withIndex('by_follower', q => q.eq('follower', userRecord._id))
.collect();
await Promise.all(
userPosts.map(async post => await ctx.db.delete(post._id))
);
@@ -101,6 +110,14 @@ export const deleteUser = internalMutation({
userLikes.map(async like => await ctx.db.delete(like._id))
);
await Promise.all(
userFollowers.map(async follower => await ctx.db.delete(follower._id))
);
await Promise.all(
userFollowings.map(async following => await ctx.db.delete(following._id))
);
await ctx.db.delete(userRecord._id);
},
});
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

Before

Width:  |  Height:  |  Size: 629 B

+10 -1
View File
@@ -1,3 +1,12 @@
import AllPosts from '@/components/AllPosts';
export default function Home() {
return <main className='flex-1'></main>;
return (
<main className='flex flex-col items-center flex-1'>
<div className='flex flex-col w-full max-w-4xl gap-4'>
<h1 className='text-4xl font-bold'>Home</h1>
<AllPosts />
</div>
</main>
);
}
+39
View File
@@ -0,0 +1,39 @@
'use client';
import { usePaginatedQuery } from 'convex/react';
import { api } from '../../convex/_generated/api';
import Loader from './Loader';
import Post from './Post';
export default function AllPosts() {
const PAGE_SIZE = 10;
const pager = usePaginatedQuery(
api.posts.getAllPostsWithUser,
{},
{ initialNumItems: PAGE_SIZE }
);
function handleLoadMoreClick() {
pager.loadMore(PAGE_SIZE);
}
return (
<div className='flex flex-col items-center w-full'>
<div className='flex flex-col items-center w-full'>
{pager.results.map(post => (
<div
key={post._id}
className='w-full border border-t-0 border-gray-600 first:border-t last:rounded-b-md p-1 last:mb-4'
>
<Post post={post} />
</div>
))}
</div>
<Loader
isLoading={pager.isLoading}
status={pager.status}
loadButtonClickHandler={handleLoadMoreClick}
/>
</div>
);
}
+2 -2
View File
@@ -11,7 +11,7 @@ export default function Loader({
}) {
if (isLoading) {
return (
<div className='flex w-full items-center justify-center gap-2 p-5 border-t border-gray-600'>
<div className='flex w-full items-center justify-center gap-2 p-5 border-t border-gray-600 text-sm'>
<SpinningLoader className='animate-spin w-5 h-5' />
Loading...
</div>
@@ -25,7 +25,7 @@ export default function Loader({
return (
<div className='flex items-center'>
<button
className='bg-primary-accent text-white px-3 py-1 rounded-full'
className='bg-primary-accent text-white px-3 py-1 rounded-full text-sm'
onClick={loadButtonClickHandler}
disabled={status !== 'CanLoadMore'}
>
+14
View File
@@ -3,6 +3,7 @@
import { SignedIn, SignedOut, useUser } from '@clerk/nextjs';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { AiFillHome } from 'react-icons/ai';
import { BiLogIn, BiPlus } from 'react-icons/bi';
import { BsPersonPlusFill } from 'react-icons/bs';
import { ImProfile } from 'react-icons/im';
@@ -64,6 +65,19 @@ export default function Navbar() {
/>
</div>
</li>
<li>
<div className='flex items-center gap-2'>
<div className='p-1 md:hidden'>
<AiFillHome className='w-6 h-6' />
</div>
<Link
onClick={() => setNavOpen(false)}
href='/'
>
Home
</Link>
</div>
</li>
<li>
<div className='flex items-center gap-2'>
<div className='p-1 md:hidden'>
+2
View File
@@ -46,6 +46,7 @@ export default function Post({
return (
<div className='flex w-full gap-4 p-8 bg-white dark:bg-secondary-gray flex-wrap'>
<div className='flex-shrink-0'>
<Link href={`/profile/${post.user.clerkUserId}`}>
<Image
alt='user profile image'
src={post.user.clerkImageUrl}
@@ -53,6 +54,7 @@ export default function Post({
height={40}
className='rounded-full object-cover border-4 border-primary-accent'
/>
</Link>
</div>
<div className='flex flex-1 flex-col gap-2 min-w-0'>
<div className='flex items-center justify-between gap-2'>
+3 -3
View File
@@ -36,7 +36,7 @@ export default function PostActionButton({
href={{ pathname: `/posts/${postId}`, query: { reply: true } }}
>
<BsFillReplyFill />
<div className='flex items-center justify-center h-6 w-6 rounded-full text-xs bg-secondary-gray text-white'>
<div className='flex items-center justify-center h-6 w-6 rounded-full text-xs bg-primary-gray text-white'>
{replyCount}
</div>
</Link>
@@ -49,8 +49,8 @@ export default function PostActionButton({
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'>
<BiSolidLike className='flex-shrink-0' />
<div className='flex items-center justify-center h-6 w-6 rounded-full text-xs bg-primary-gray text-white'>
{likeCount}
</div>
</button>
+3
View File
@@ -2,6 +2,7 @@ import { PostWithUserDto } from '@/app/types';
import { useUser } from '@clerk/nextjs';
import { Text } from '@codemirror/state';
import Image from 'next/image';
import Link from 'next/link';
import PostActionButton from './PostActionButtons';
import PostActionModal from './PostActionModal';
import PostContent from './PostContent';
@@ -17,6 +18,7 @@ export default function Reply({ post }: { post: PostWithUserDto }) {
return (
<div className='flex w-full gap-4'>
<div>
<Link href={`/profile/${post.user.clerkUserId}`}>
<Image
alt='user profile image'
src={post.user.clerkImageUrl}
@@ -24,6 +26,7 @@ export default function Reply({ post }: { post: PostWithUserDto }) {
height={40}
className='rounded-full object-cover border-4 border-primary-accent'
/>
</Link>
</div>
<div className='flex flex-col flex-1 w-full border border-gray-600 rounded-md'>
<div className='flex flex-col w-full p-1'>
+2 -1
View File
@@ -1,8 +1,9 @@
'use client';
import { useMountedEffect } from '@/hooks';
import { UserButton as ClerkUserButton } from '@clerk/nextjs';
import { ReactNode } from 'react';
export default function UserButton() {
export default function UserButton({ children }: { children?: ReactNode }) {
const { mounted } = useMountedEffect();
if (mounted === false) {
+2 -2
View File
@@ -42,12 +42,12 @@ export default function UserPosts({ user }: { user: UserDto }) {
}
return (
<div className='flex flex-col items-center w-full gap-4'>
<div className='flex flex-col items-center w-full'>
<div className='flex flex-col items-center w-full'>
{postsWithUser.map(post => (
<div
key={post._id}
className='w-full border border-t-0 border-gray-600 first:border-t last:rounded-b-md p-1'
className='w-full border border-t-0 border-gray-600 first:border-t last:rounded-b-md p-1 last:mb-4'
>
<Post post={post} />
</div>
+78 -2
View File
@@ -1,15 +1,53 @@
'use client';
import { UserDto } from '@/app/types';
import { useUser } from '@clerk/nextjs';
import { useMutation, useQuery } from 'convex/react';
import Image from 'next/image';
import { AiFillCalendar } from 'react-icons/ai';
import { api } from '../../convex/_generated/api';
export default function UserProfile({ user }: { user: UserDto }) {
const { isLoaded, isSignedIn, user: currentUser } = useUser();
const addFollow = useMutation(api.follows.addFollow);
const removeFollow = useMutation(api.follows.removeFollow);
const followerCount = useQuery(api.follows.getUserFollowerCount, {
userId: user._id,
});
const followingCount = useQuery(api.follows.getUserFollowingCount, {
userId: user._id,
});
const isFollowing = useQuery(api.follows.getFollowing, {
followingId: user._id,
});
const postCount = useQuery(api.posts.getUserPostCount, { userId: user._id });
const username = user.clerkUsername ?? user._id;
const userCreatedDate = new Date(user._creationTime);
const monthJoined = userCreatedDate.toLocaleString(undefined, {
month: 'short',
});
const yearJoined = userCreatedDate.getFullYear();
const countDataLoaded =
postCount !== undefined &&
followerCount !== undefined &&
followingCount !== undefined;
async function handleFollowButtonClick() {
if (isFollowing) {
await removeFollow({ followingId: user._id });
return;
}
await addFollow({ followingId: user._id });
}
return (
<div className='w-full'>
<div className='shadow-md bg-gradient-to-r from-violet-600 via-violet-600 to-indigo-600 rounded-t-md pt-20 px-5'>
@@ -23,7 +61,8 @@ export default function UserProfile({ user }: { user: UserDto }) {
className='rounded-full object-cover border-4 border-primary-accent'
/>
</div>
<div className='flex flex-col flex-1 min-w-0 text-white'>
<div className='flex flex-col-reverse mb-[25px] flex-1 min-w-0 gap-0.5 md:flex-row md:mb-0 md:gap-2'>
<div className='flex flex-col min-w-0 text-white'>
<h1
className='font-bold overflow-hidden text-ellipsis'
title={username}
@@ -35,9 +74,46 @@ export default function UserProfile({ user }: { user: UserDto }) {
{`Joined ${monthJoined} ${yearJoined}`}
</div>
</div>
<div>
{isLoaded && isSignedIn && currentUser.id !== user.clerkUserId ? (
<button
onClick={handleFollowButtonClick}
type='button'
className={`py-0.5 px-3 rounded-full text-sm border border-white text-white ${
isFollowing ? 'bg-primary-accent' : 'o'
}`}
>
Follow
</button>
) : null}
</div>
</div>
</div>
</div>
<div className='flex flex-1 bg-white dark:bg-primary-gray pl-5 border border-gray-600 border-b-0'>
<div className='flex flex-col min-h-[25px] items-start gap-1 py-1 pl-[116px] md:flex-row md:items-center md:gap-4'>
{countDataLoaded ? (
<>
<div>
<span className='font-bold whitespace-nowrap'>{postCount}</span>{' '}
posts
</div>
<div className='min-w-0'>
<span className='font-bold whitespace-nowrap'>
{followerCount}
</span>{' '}
followers
</div>
<div>
<span className='font-bold whitespace-nowrap'>
{followingCount}
</span>{' '}
following
</div>
</>
) : null}
</div>
</div>
<div className='h-[50px] bg-white dark:bg-primary-gray pl-5 pr-40 border border-gray-600 border-b-0'></div>
</div>
);
}