Skip to content

Commit

Permalink
feat(be): implement follow, unfollow and check functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
acatzk committed Jan 30, 2024
1 parent 42f6b62 commit 3eb0d1f
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
2 changes: 2 additions & 0 deletions server/api/root.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { createTRPCRouter } from './trpc'
import { userRouter } from './routers/user'
import { postRouter } from './routers/post'
import { followRouter } from './routers/follow'
import { hashtagRouter } from './routers/hashtag'

export const appRouter = createTRPCRouter({
user: userRouter,
post: postRouter,
follow: followRouter,
hashtag: hashtagRouter
})

Expand Down
96 changes: 96 additions & 0 deletions server/api/routers/follow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { z } from 'zod'
import { TRPCError } from '@trpc/server'

import { protectedProcedure, createTRPCRouter } from './../trpc'

const UserRelation = z.object({
targetId: z.number(),
authorId: z.number()
})

export const followRouter = createTRPCRouter({
follow: protectedProcedure.input(UserRelation).query(async ({ ctx, input }) => {
if (input.authorId === input.targetId) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'You cannot follow yourself.'
})
}

const targetUserFound = await ctx.db.user.findUnique({
where: { id: input.targetId }
})

if (!targetUserFound) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Target user not found.'
})
}

return await ctx.db.follow.create({
data: {
follower: {
connect: {
id: input.targetId
}
},
following: {
connect: {
id: input.authorId
}
}
},
include: {
follower: true,
following: true
}
})
}),

unfollow: protectedProcedure.input(UserRelation).query(async ({ ctx, input }) => {
if (input.authorId === input.targetId) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'You cannot follow yourself.'
})
}

const targetUserFound = await ctx.db.user.findUnique({
where: { id: input.targetId }
})

if (!targetUserFound) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Target user not found.'
})
}

return await ctx.db.follow.delete({
where: {
followerId_followingId: {
followerId: input.targetId,
followingId: input.authorId
}
},
include: {
follower: true,
following: true
}
})
}),

checkUserFollowed: protectedProcedure.input(UserRelation).query(({ ctx, input }) => {
const followRelationship = ctx.db.follow.findUnique({
where: {
followerId_followingId: {
followerId: input.targetId,
followingId: input.authorId
}
}
})

return !!followRelationship
})
})

0 comments on commit 3eb0d1f

Please sign in to comment.