Skip to content

Commit 7b204f7

Browse files
Merge pull request #11 from git-init-priyanshu/nextjs
User ID for API calls instead of user email.
2 parents beaec52 + d199a36 commit 7b204f7

File tree

13 files changed

+95
-96
lines changed

13 files changed

+95
-96
lines changed

app/actions.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
import prisma from "@/prisma/prismaClient"
44

5-
export const GetAllDocs = async () => {
5+
export const GetAllDocs = async (userId: string) => {
66
try {
77
const response = await prisma.document.findMany(
88
{
9+
where: { userId },
910
select: {
1011
id: true,
1112
thumbnail: true,

app/components/Card/Card.tsx

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,8 @@ export default function DocCard({ docId, thumbnail, title, updatedAt, users }: D
4040
const [name, setName] = useState(title)
4141

4242
const saveName = useCallback(async () => {
43-
if (!inputRef.current) return;
44-
const email = session.email;
45-
if (!email) return;
46-
47-
await RenameDocument(docId, email, inputRef.current.value);
43+
if (!inputRef.current || !session?.id) return;
44+
await RenameDocument(docId, session.id, inputRef.current.value);
4845
}, [])
4946

5047
const debounceSaveName = useMemo(() => debounce(saveName, 2000), [saveName])

app/components/Card/actions.ts

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,17 @@
33
import prisma from "@/prisma/prismaClient";
44
import { revalidatePath } from "next/cache";
55

6-
export const DeleteDocument = async (email: string, docId: any) => {
6+
export const DeleteDocument = async (docId: any, userId: string) => {
77
try {
8-
const user = await prisma.user.findFirst({ where: { email } });
9-
if (!user) {
10-
return {
11-
success: false,
12-
error: "Looks like you don't have an account",
13-
};
14-
}
15-
16-
const doc = await prisma.document.findFirst({ where: { id: docId } });
8+
const doc = await prisma.document.findFirst({ where: { id: docId, userId } });
179
if (!doc) {
1810
return {
1911
success: false,
2012
error: "Document does not exist",
2113
};
2214
}
2315

24-
await prisma.document.delete({ where: { id: docId } })
16+
await prisma.document.delete({ where: { id: docId, userId } })
2517
revalidatePath("/");
2618

2719
return { success: true, data: "Document successfully deleted" };
@@ -31,25 +23,20 @@ export const DeleteDocument = async (email: string, docId: any) => {
3123
}
3224
}
3325

34-
export const RenameDocument = async (docId: any, email: string, newName: string) => {
26+
export const RenameDocument = async (docId: any, userId: string, newName: string) => {
3527
try {
36-
const user = await prisma.user.findFirst({ where: { email } });
37-
if (!user) {
38-
return {
39-
success: false,
40-
error: "Looks like you don't have an account",
41-
};
42-
}
43-
44-
const doc = await prisma.document.findFirst({ where: { id: docId } });
28+
const doc = await prisma.document.findFirst({ where: { id: docId, userId } });
4529
if (!doc) {
4630
return {
4731
success: false,
4832
error: "Document does not exist",
4933
};
5034
}
5135

52-
await prisma.document.update({ where: { id: docId }, data: { name: newName } })
36+
await prisma.document.update({
37+
where: { id: docId, userId },
38+
data: { name: newName }
39+
})
5340
revalidatePath("/");
5441

5542
return { success: true, data: "Document successfully renamed" };

app/components/Card/components/Options.tsx

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
6262
}
6363

6464
const confirmDeleteDocument = async () => {
65-
const email = session.email;
66-
if (!email) return;
67-
const response = await DeleteDocument(email, docId);
65+
if (!session.id) return;
66+
67+
const response = await DeleteDocument(docId, session.id);
6868
if (response.success) {
6969
toast.success(response.data)
7070
} else {
@@ -81,9 +81,15 @@ export default function CardOptions({ docId, inputRef }: CardOptionsPropType) {
8181
onPointerDownOutside={() => setIsOptionsOpen(false)}
8282
className="flex flex-col p-0 py-2 text-left w-min"
8383
>
84-
{docOptions.map((item) => {
84+
{docOptions.map((item, index) => {
8585
return (
86-
<Button id={item.title} variant="ghost" className="gap-2 justify-start" onClick={item.onClick}>
86+
<Button
87+
key={index}
88+
id={item.title}
89+
variant="ghost"
90+
className="gap-2 justify-start"
91+
onClick={item.onClick}
92+
>
8793
<item.icon size={20} color={item.color} strokeWidth={1.5} />
8894
<p className="text-neutral-600">{item.title}</p>
8995
</Button>

app/components/Header/Header.tsx

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,8 @@ export default function Header() {
2727
const createDocument = async () => {
2828
setIsLoading(true);
2929

30-
const email = session.email;
31-
if(!email) return;
32-
33-
const response = await CreateNewDocument(email)
30+
if (!session?.id) return;
31+
const response = await CreateNewDocument(session.id);
3432
if (response.success) {
3533
setIsLoading(false);
3634
toast.success("Successfully created new document")
@@ -45,7 +43,7 @@ export default function Header() {
4543
const response = await LogoutAction();
4644
if (response.success) {
4745
toast.success("Successfully logged out")
48-
router.push('/signup')
46+
router.push('/api/auth/signin')
4947
} else {
5048
toast.error(response.error)
5149
}

app/components/Header/actions.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,17 @@ import { cookies } from "next/headers";
55
import prisma from "@/prisma/prismaClient";
66
import { signOut } from "next-auth/react";
77

8-
export const CreateNewDocument = async (email: string) => {
8+
export const CreateNewDocument = async (userId: string) => {
99
try {
10-
const user = await prisma.user.findFirst({ where: { email } });
11-
if (!user) {
12-
return {
13-
success: false,
14-
error: "Looks like you don't have an account",
15-
};
16-
}
17-
1810
const doc = await prisma.document.create({
1911
data: {
2012
data: "",
21-
userId: user.id,
13+
userId,
2214
users: {
2315
create: {
2416
user: {
2517
connect: {
26-
id: user.id
18+
id: userId
2719
}
2820
}
2921
},
@@ -41,6 +33,7 @@ export const CreateNewDocument = async (email: string) => {
4133
export const LogoutAction = async () => {
4234
try {
4335
cookies().delete('token');
36+
cookies().delete('next-auth.session-token');
4437
signOut();
4538

4639
return { success: true, data: null };

app/loading.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ export default function Loading() {
66
<>
77
<Header />
88
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 my-8 max-w-[80vw] mx-auto">
9-
{[1, 2, 3, 4].map(() => {
9+
{[1, 2, 3, 4].map((i) => {
1010
return (
11-
<Card className="overflow-hidden">
11+
<Card key={i} className="overflow-hidden">
1212
<div className="h-52 w-full bg-neutral-100 animate-pulse"></div>
1313
<CardFooter className=" flex flex-col items-start gap-4 border-t bg-slate-50 p-4">
1414
<div className="flex items-center gap-1">

app/page.tsx

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
11
import DocCard from "./components/Card/Card";
22
import Header from "./components/Header/Header"
33
import { GetAllDocs } from "./actions";
4+
import getServerSession from "@/lib/customHooks/getServerSession";
45

56
export default async function Home() {
6-
const data = await GetAllDocs();
7+
const session = await getServerSession();
8+
if (!session?.id) return;
9+
10+
const data = await GetAllDocs(session?.id);
711

812
return (
913
<main>
1014
<Header />
1115
<div
1216
className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 my-8 max-w-[80vw] mx-auto"
1317
>
14-
{data && data.map((doc, index) => {
15-
return (
16-
<DocCard
17-
key={index}
18-
docId={doc.id}
19-
thumbnail={doc.thumbnail}
20-
title={doc.name}
21-
updatedAt={doc.updatedAt}
22-
users={doc.users}
23-
/>
24-
)
25-
})}
18+
{data
19+
&& data.length > 0
20+
? data.map((doc, index) => {
21+
return (
22+
<DocCard
23+
key={index}
24+
docId={doc.id}
25+
thumbnail={doc.thumbnail}
26+
title={doc.name}
27+
updatedAt={doc.updatedAt}
28+
users={doc.users}
29+
/>
30+
)
31+
})
32+
: <></>}
2633
</div>
2734
</main>
2835
);

app/writer/[id]/actions.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import prisma from "@/prisma/prismaClient"
44

5-
export const GetDocDetails = async (id: any) => {
5+
export const GetDocDetails = async (id: any, userId: string) => {
66
try {
7-
const doc = await prisma.document.findFirst({ where: { id } })
7+
const doc = await prisma.document.findFirst({ where: { id, userId } })
88
if (!doc) return {
99
success: false,
1010
error: "Document does not exist",
@@ -17,17 +17,19 @@ export const GetDocDetails = async (id: any) => {
1717
}
1818
}
1919

20-
export const UpdateDocData = async (id: any, data: string) => {
20+
export const UpdateDocData = async (id: any, userId: string, data: string) => {
21+
console.log("here3")
2122
try {
22-
const doc = await prisma.document.findFirst({ where: { id } })
23+
const doc = await prisma.document.findFirst({ where: { id, userId } })
2324
if (!doc) return {
2425
success: false,
2526
error: "Document does not exist",
2627
}
2728

29+
console.log("here4")
2830
await prisma.document.update(
2931
{
30-
where: { id },
32+
where: { id, userId },
3133
data: {
3234
data: data,
3335
updatedAt: Date(),
@@ -41,15 +43,15 @@ export const UpdateDocData = async (id: any, data: string) => {
4143
}
4244
}
4345

44-
export const UpdateThumbnail = async (id: any, thumbnail: string) => {
46+
export const UpdateThumbnail = async (id: any, userId: string, thumbnail: string) => {
4547
try {
46-
const doc = await prisma.document.findFirst({ where: { id } })
48+
const doc = await prisma.document.findFirst({ where: { id, userId } })
4749
if (!doc) return {
4850
success: false,
4951
error: "Document does not exist",
5052
}
5153

52-
await prisma.document.update({ where: { id }, data: { thumbnail } })
54+
await prisma.document.update({ where: { id, userId }, data: { thumbnail } })
5355

5456
return { success: true, data: "Internal server error" }
5557
} catch (e) {

app/writer/[id]/page.tsx

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,20 @@ import Loading from './components/EditorLoading'
1818
import { extensions, props } from './editor/editorConfig'
1919
import { GetDocDetails, UpdateDocData, UpdateThumbnail } from './actions'
2020
import { toast } from 'sonner'
21+
import useClientSession from '@/lib/customHooks/useClientSession'
2122

2223
export default function Dashboard() {
2324
const params = useParams()
2425

26+
const session = useClientSession();
27+
2528
const [isSaving, setIsSaving] = useState(false);
2629
const [docData, setDocData] = useState<string | JSX.Element | JSX.Element[] | undefined>(undefined);
2730

2831
const { data } = useQuery({
2932
queryKey: ["doc-details", params.id],
3033
queryFn: async () => {
31-
const response = await GetDocDetails(params.id);
34+
const response = await GetDocDetails(params.id, session.id!);
3235
if (response.success) {
3336
if (response.data?.data) {
3437
setDocData(JSON.parse(response.data?.data));
@@ -38,6 +41,8 @@ export default function Dashboard() {
3841
return null;
3942
}
4043
},
44+
retry: 5,
45+
retryDelay: 100,
4146
})
4247

4348
const createDocThumbnail = async () => {
@@ -46,7 +51,7 @@ export default function Dashboard() {
4651
if (!page) return;
4752

4853
// @ts-ignore
49-
const canvas = await html2canvas(page, { scale: 0.5 })
54+
const canvas = await html2canvas(page, { scale: 1 })
5055

5156
const thumbnail = canvas.toDataURL(`${data?.id}thumbnail/png`).replace(/^data:image\/\w+;base64,/, '');
5257

@@ -62,7 +67,8 @@ export default function Dashboard() {
6267
const res = await upload.json();
6368
const url = res.data.display_url;
6469

65-
await UpdateThumbnail(params.id, url)
70+
if (!session?.id) return;
71+
await UpdateThumbnail(params.id, session.id, url)
6672

6773
setIsSaving(false);
6874
} catch (e) {
@@ -74,13 +80,15 @@ export default function Dashboard() {
7480

7581
const saveDoc = useCallback((editor: any) => {
7682
setIsSaving(true);
77-
UpdateDocData(params.id, JSON.stringify(editor.getJSON()));
83+
if (!session?.id) return;
84+
85+
UpdateDocData(params.id, session.id, JSON.stringify(editor.getJSON()));
7886
createDocThumbnail();
79-
}, []);
87+
}, [session]);
8088

8189
const debouncedSaveDoc = useMemo(
8290
() => debounce((editor: any) => saveDoc(editor), 1000),
83-
[saveDoc]
91+
[saveDoc, session]
8492
);
8593

8694
const editor = useEditor({

lib/auth.ts

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,21 +59,22 @@ export const authOptions: NextAuthOptions = {
5959
}
6060
return true;
6161
},
62+
// jwt: ({ token }) => {
63+
// return token;
64+
// },
65+
session: async ({ session }: any) => {
66+
if (session.user) {
67+
const user = await prisma.user.findFirst(
68+
{
69+
where: { email: session.user.email }
70+
});
71+
session.user.id = user?.id;
72+
}
73+
return session;
74+
},
6275
redirect({ baseUrl }) {
6376
return baseUrl;
6477
},
65-
jwt: ({ user, token }: any) => {
66-
if (user) {
67-
token.uid = user.id;
68-
}
69-
return token;
70-
},
71-
session: ({ session, token }: any) => {
72-
if (session.user) {
73-
session.user.id = token.uid
74-
}
75-
return session
76-
}
7778
},
7879
cookies: {
7980
sessionToken: {

0 commit comments

Comments
 (0)