From d199a36fd2aa4a398f027749ab3745526f10836c Mon Sep 17 00:00:00 2001 From: Priyanshu Date: Thu, 8 Aug 2024 15:17:59 +0530 Subject: [PATCH] user id for data fetching --- app/actions.ts | 3 +- app/components/Card/Card.tsx | 7 ++--- app/components/Card/actions.ts | 31 ++++++-------------- app/components/Card/components/Options.tsx | 16 +++++++---- app/components/Header/Header.tsx | 8 ++---- app/components/Header/actions.ts | 15 +++------- app/loading.tsx | 4 +-- app/page.tsx | 33 +++++++++++++--------- app/writer/[id]/actions.ts | 18 ++++++------ app/writer/[id]/page.tsx | 20 +++++++++---- lib/auth.ts | 25 ++++++++-------- lib/customHooks/getServerSession.ts | 6 ++-- lib/customHooks/useClientSession.tsx | 5 ++-- 13 files changed, 95 insertions(+), 96 deletions(-) diff --git a/app/actions.ts b/app/actions.ts index 0663b01..740d153 100644 --- a/app/actions.ts +++ b/app/actions.ts @@ -2,10 +2,11 @@ import prisma from "@/prisma/prismaClient" -export const GetAllDocs = async () => { +export const GetAllDocs = async (userId: string) => { try { const response = await prisma.document.findMany( { + where: { userId }, select: { id: true, thumbnail: true, diff --git a/app/components/Card/Card.tsx b/app/components/Card/Card.tsx index 96bd4a5..bbec467 100644 --- a/app/components/Card/Card.tsx +++ b/app/components/Card/Card.tsx @@ -40,11 +40,8 @@ export default function DocCard({ docId, thumbnail, title, updatedAt, users }: D const [name, setName] = useState(title) const saveName = useCallback(async () => { - if (!inputRef.current) return; - const email = session.email; - if (!email) return; - - await RenameDocument(docId, email, inputRef.current.value); + if (!inputRef.current || !session?.id) return; + await RenameDocument(docId, session.id, inputRef.current.value); }, []) const debounceSaveName = useMemo(() => debounce(saveName, 2000), [saveName]) diff --git a/app/components/Card/actions.ts b/app/components/Card/actions.ts index 7b4ddb0..299e54a 100644 --- a/app/components/Card/actions.ts +++ b/app/components/Card/actions.ts @@ -3,17 +3,9 @@ import prisma from "@/prisma/prismaClient"; import { revalidatePath } from "next/cache"; -export const DeleteDocument = async (email: string, docId: any) => { +export const DeleteDocument = async (docId: any, userId: string) => { try { - const user = await prisma.user.findFirst({ where: { email } }); - if (!user) { - return { - success: false, - error: "Looks like you don't have an account", - }; - } - - const doc = await prisma.document.findFirst({ where: { id: docId } }); + const doc = await prisma.document.findFirst({ where: { id: docId, userId } }); if (!doc) { return { success: false, @@ -21,7 +13,7 @@ export const DeleteDocument = async (email: string, docId: any) => { }; } - await prisma.document.delete({ where: { id: docId } }) + await prisma.document.delete({ where: { id: docId, userId } }) revalidatePath("/"); return { success: true, data: "Document successfully deleted" }; @@ -31,17 +23,9 @@ export const DeleteDocument = async (email: string, docId: any) => { } } -export const RenameDocument = async (docId: any, email: string, newName: string) => { +export const RenameDocument = async (docId: any, userId: string, newName: string) => { try { - const user = await prisma.user.findFirst({ where: { email } }); - if (!user) { - return { - success: false, - error: "Looks like you don't have an account", - }; - } - - const doc = await prisma.document.findFirst({ where: { id: docId } }); + const doc = await prisma.document.findFirst({ where: { id: docId, userId } }); if (!doc) { return { success: false, @@ -49,7 +33,10 @@ export const RenameDocument = async (docId: any, email: string, newName: string) }; } - await prisma.document.update({ where: { id: docId }, data: { name: newName } }) + await prisma.document.update({ + where: { id: docId, userId }, + data: { name: newName } + }) revalidatePath("/"); return { success: true, data: "Document successfully renamed" }; diff --git a/app/components/Card/components/Options.tsx b/app/components/Card/components/Options.tsx index 917384a..d09c645 100644 --- a/app/components/Card/components/Options.tsx +++ b/app/components/Card/components/Options.tsx @@ -62,9 +62,9 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) { } const confirmDeleteDocument = async () => { - const email = session.email; - if (!email) return; - const response = await DeleteDocument(email, docId); + if (!session.id) return; + + const response = await DeleteDocument(docId, session.id); if (response.success) { toast.success(response.data) } else { @@ -81,9 +81,15 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) { onPointerDownOutside={() => setIsOptionsOpen(false)} className="flex flex-col p-0 py-2 text-left w-min" > - {docOptions.map((item) => { + {docOptions.map((item, index) => { return ( - diff --git a/app/components/Header/Header.tsx b/app/components/Header/Header.tsx index 2edd739..df6dc72 100644 --- a/app/components/Header/Header.tsx +++ b/app/components/Header/Header.tsx @@ -27,10 +27,8 @@ export default function Header() { const createDocument = async () => { setIsLoading(true); - const email = session.email; - if(!email) return; - - const response = await CreateNewDocument(email) + if (!session?.id) return; + const response = await CreateNewDocument(session.id); if (response.success) { setIsLoading(false); toast.success("Successfully created new document") @@ -45,7 +43,7 @@ export default function Header() { const response = await LogoutAction(); if (response.success) { toast.success("Successfully logged out") - router.push('/signup') + router.push('/api/auth/signin') } else { toast.error(response.error) } diff --git a/app/components/Header/actions.ts b/app/components/Header/actions.ts index a432e52..f6fd198 100644 --- a/app/components/Header/actions.ts +++ b/app/components/Header/actions.ts @@ -5,25 +5,17 @@ import { cookies } from "next/headers"; import prisma from "@/prisma/prismaClient"; import { signOut } from "next-auth/react"; -export const CreateNewDocument = async (email: string) => { +export const CreateNewDocument = async (userId: string) => { try { - const user = await prisma.user.findFirst({ where: { email } }); - if (!user) { - return { - success: false, - error: "Looks like you don't have an account", - }; - } - const doc = await prisma.document.create({ data: { data: "", - userId: user.id, + userId, users: { create: { user: { connect: { - id: user.id + id: userId } } }, @@ -41,6 +33,7 @@ export const CreateNewDocument = async (email: string) => { export const LogoutAction = async () => { try { cookies().delete('token'); + cookies().delete('next-auth.session-token'); signOut(); return { success: true, data: null }; diff --git a/app/loading.tsx b/app/loading.tsx index 26a4f44..e93eeef 100644 --- a/app/loading.tsx +++ b/app/loading.tsx @@ -6,9 +6,9 @@ export default function Loading() { <>
- {[1, 2, 3, 4].map(() => { + {[1, 2, 3, 4].map((i) => { return ( - +
diff --git a/app/page.tsx b/app/page.tsx index 32346bb..5f143c4 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,9 +1,13 @@ import DocCard from "./components/Card/Card"; import Header from "./components/Header/Header" import { GetAllDocs } from "./actions"; +import getServerSession from "@/lib/customHooks/getServerSession"; export default async function Home() { - const data = await GetAllDocs(); + const session = await getServerSession(); + if (!session?.id) return; + + const data = await GetAllDocs(session?.id); return (
@@ -11,18 +15,21 @@ export default async function Home() {
- {data && data.map((doc, index) => { - return ( - - ) - })} + {data + && data.length > 0 + ? data.map((doc, index) => { + return ( + + ) + }) + : <>}
); diff --git a/app/writer/[id]/actions.ts b/app/writer/[id]/actions.ts index 31221f7..abc378c 100644 --- a/app/writer/[id]/actions.ts +++ b/app/writer/[id]/actions.ts @@ -2,9 +2,9 @@ import prisma from "@/prisma/prismaClient" -export const GetDocDetails = async (id: any) => { +export const GetDocDetails = async (id: any, userId: string) => { try { - const doc = await prisma.document.findFirst({ where: { id } }) + const doc = await prisma.document.findFirst({ where: { id, userId } }) if (!doc) return { success: false, error: "Document does not exist", @@ -17,17 +17,19 @@ export const GetDocDetails = async (id: any) => { } } -export const UpdateDocData = async (id: any, data: string) => { +export const UpdateDocData = async (id: any, userId: string, data: string) => { + console.log("here3") try { - const doc = await prisma.document.findFirst({ where: { id } }) + const doc = await prisma.document.findFirst({ where: { id, userId } }) if (!doc) return { success: false, error: "Document does not exist", } + console.log("here4") await prisma.document.update( { - where: { id }, + where: { id, userId }, data: { data: data, updatedAt: Date(), @@ -41,15 +43,15 @@ export const UpdateDocData = async (id: any, data: string) => { } } -export const UpdateThumbnail = async (id: any, thumbnail: string) => { +export const UpdateThumbnail = async (id: any, userId: string, thumbnail: string) => { try { - const doc = await prisma.document.findFirst({ where: { id } }) + const doc = await prisma.document.findFirst({ where: { id, userId } }) if (!doc) return { success: false, error: "Document does not exist", } - await prisma.document.update({ where: { id }, data: { thumbnail } }) + await prisma.document.update({ where: { id, userId }, data: { thumbnail } }) return { success: true, data: "Internal server error" } } catch (e) { diff --git a/app/writer/[id]/page.tsx b/app/writer/[id]/page.tsx index 64e31cd..d6357eb 100644 --- a/app/writer/[id]/page.tsx +++ b/app/writer/[id]/page.tsx @@ -18,17 +18,20 @@ import Loading from './components/EditorLoading' import { extensions, props } from './editor/editorConfig' import { GetDocDetails, UpdateDocData, UpdateThumbnail } from './actions' import { toast } from 'sonner' +import useClientSession from '@/lib/customHooks/useClientSession' export default function Dashboard() { const params = useParams() + const session = useClientSession(); + const [isSaving, setIsSaving] = useState(false); const [docData, setDocData] = useState(undefined); const { data } = useQuery({ queryKey: ["doc-details", params.id], queryFn: async () => { - const response = await GetDocDetails(params.id); + const response = await GetDocDetails(params.id, session.id!); if (response.success) { if (response.data?.data) { setDocData(JSON.parse(response.data?.data)); @@ -38,6 +41,8 @@ export default function Dashboard() { return null; } }, + retry: 5, + retryDelay: 100, }) const createDocThumbnail = async () => { @@ -46,7 +51,7 @@ export default function Dashboard() { if (!page) return; // @ts-ignore - const canvas = await html2canvas(page, { scale: 0.5 }) + const canvas = await html2canvas(page, { scale: 1 }) const thumbnail = canvas.toDataURL(`${data?.id}thumbnail/png`).replace(/^data:image\/\w+;base64,/, ''); @@ -62,7 +67,8 @@ export default function Dashboard() { const res = await upload.json(); const url = res.data.display_url; - await UpdateThumbnail(params.id, url) + if (!session?.id) return; + await UpdateThumbnail(params.id, session.id, url) setIsSaving(false); } catch (e) { @@ -74,13 +80,15 @@ export default function Dashboard() { const saveDoc = useCallback((editor: any) => { setIsSaving(true); - UpdateDocData(params.id, JSON.stringify(editor.getJSON())); + if (!session?.id) return; + + UpdateDocData(params.id, session.id, JSON.stringify(editor.getJSON())); createDocThumbnail(); - }, []); + }, [session]); const debouncedSaveDoc = useMemo( () => debounce((editor: any) => saveDoc(editor), 1000), - [saveDoc] + [saveDoc, session] ); const editor = useEditor({ diff --git a/lib/auth.ts b/lib/auth.ts index e87ef29..950e9cd 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -59,21 +59,22 @@ export const authOptions: NextAuthOptions = { } return true; }, + // jwt: ({ token }) => { + // return token; + // }, + session: async ({ session }: any) => { + if (session.user) { + const user = await prisma.user.findFirst( + { + where: { email: session.user.email } + }); + session.user.id = user?.id; + } + return session; + }, redirect({ baseUrl }) { return baseUrl; }, - jwt: ({ user, token }: any) => { - if (user) { - token.uid = user.id; - } - return token; - }, - session: ({ session, token }: any) => { - if (session.user) { - session.user.id = token.uid - } - return session - } }, cookies: { sessionToken: { diff --git a/lib/customHooks/getServerSession.ts b/lib/customHooks/getServerSession.ts index 3f8d08b..1f7e405 100644 --- a/lib/customHooks/getServerSession.ts +++ b/lib/customHooks/getServerSession.ts @@ -3,18 +3,18 @@ import { getServerSession as nextAuthSession } from "next-auth"; import { ReturnType } from "./useClientSession"; import { GetUserDetails } from "./action"; +import { authOptions } from "../auth"; export default async function getServerSession(): Promise { - const session = await nextAuthSession(); + const session = await nextAuthSession(authOptions); if (session) return { - id: "", + id: session.user?.id, name: session.user?.name, email: session.user?.email, image: session.user?.image }; - console.log("........................here...............................................") const userDetails = await GetUserDetails(); return { id: userDetails?.id, diff --git a/lib/customHooks/useClientSession.tsx b/lib/customHooks/useClientSession.tsx index 706350b..4c4eb5a 100644 --- a/lib/customHooks/useClientSession.tsx +++ b/lib/customHooks/useClientSession.tsx @@ -19,7 +19,7 @@ export default function useClientSession(): ReturnType { useEffect(() => { (async () => { - if (!session) { + if (session === null) { const userDetails = await GetUserDetails(); setUser({ id: userDetails?.id, @@ -32,12 +32,11 @@ export default function useClientSession(): ReturnType { }, [session]) if (session) return { - id: "", + id: session.user?.id, name: session.user?.name, email: session.user?.email, image: session.user?.image }; - console.log("Credentials") return { id: user?.id,