From 2e5600db86644f0647d5071e6af6e44da573c0da Mon Sep 17 00:00:00 2001 From: DevMirza Date: Mon, 18 Dec 2023 10:42:33 +0000 Subject: [PATCH] add more functions to block service --- lib/block-service.ts | 96 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/lib/block-service.ts b/lib/block-service.ts index 9288267..b126c9a 100644 --- a/lib/block-service.ts +++ b/lib/block-service.ts @@ -33,3 +33,99 @@ export const isBlockedByUser = async (id: string) => { return false; } }; + +export const blockUser = async (id: string) => { + const self = await getSelf(); + + if (self.id === id) { + throw new Error("Cannot block yourself"); + } + + const otherUser = await db.user.findUnique({ + where: { id }, + }); + + if (!otherUser) { + throw new Error("User not found"); + } + + const existingBlock = await db.block.findUnique({ + where: { + blockerId_blockedId: { + blockerId: self.id, + blockedId: otherUser.id, + }, + }, + }); + + if (existingBlock) { + throw new Error("Already blocked"); + } + + const block = await db.block.create({ + data: { + blockerId: self.id, + blockedId: otherUser.id, + }, + include: { + blocked: true, + }, + }); + + return block; +}; + +export const unblockUser = async (id: string) => { + const self = await getSelf(); + + if (self.id === id) { + throw new Error("Cannot unblock yourself"); + } + + const otherUser = await db.user.findUnique({ + where: { id }, + }); + + if (!otherUser) { + throw new Error("User not found"); + } + + const existingBlock = await db.block.findUnique({ + where: { + blockerId_blockedId: { + blockerId: self.id, + blockedId: otherUser.id, + }, + }, + }); + + if (!existingBlock) { + throw new Error("Not blocked"); + } + + const unblock = await db.block.delete({ + where: { + id: existingBlock.id, + }, + include: { + blocked: true, + }, + }); + + return unblock; +}; + +export const getBlockedUsers = async () => { + const self = await getSelf(); + + const blockedUsers = await db.block.findMany({ + where: { + blockerId: self.id, + }, + include: { + blocked: true, + }, + }); + + return blockedUsers; +};