Skip to content

Commit

Permalink
Merge pull request #11 from git-init-priyanshu/nextjs
Browse files Browse the repository at this point in the history
User ID for API calls instead of user email.
  • Loading branch information
git-init-priyanshu authored Aug 8, 2024
2 parents beaec52 + d199a36 commit 7b204f7
Show file tree
Hide file tree
Showing 13 changed files with 95 additions and 96 deletions.
3 changes: 2 additions & 1 deletion app/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 2 additions & 5 deletions app/components/Card/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
31 changes: 9 additions & 22 deletions app/components/Card/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,17 @@
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,
error: "Document does not exist",
};
}

await prisma.document.delete({ where: { id: docId } })
await prisma.document.delete({ where: { id: docId, userId } })
revalidatePath("/");

return { success: true, data: "Document successfully deleted" };
Expand All @@ -31,25 +23,20 @@ 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,
error: "Document does not exist",
};
}

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" };
Expand Down
16 changes: 11 additions & 5 deletions app/components/Card/components/Options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 (
<Button id={item.title} variant="ghost" className="gap-2 justify-start" onClick={item.onClick}>
<Button
key={index}
id={item.title}
variant="ghost"
className="gap-2 justify-start"
onClick={item.onClick}
>
<item.icon size={20} color={item.color} strokeWidth={1.5} />
<p className="text-neutral-600">{item.title}</p>
</Button>
Expand Down
8 changes: 3 additions & 5 deletions app/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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)
}
Expand Down
15 changes: 4 additions & 11 deletions app/components/Header/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
},
Expand All @@ -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 };
Expand Down
4 changes: 2 additions & 2 deletions app/loading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ export default function Loading() {
<>
<Header />
<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">
{[1, 2, 3, 4].map(() => {
{[1, 2, 3, 4].map((i) => {
return (
<Card className="overflow-hidden">
<Card key={i} className="overflow-hidden">
<div className="h-52 w-full bg-neutral-100 animate-pulse"></div>
<CardFooter className=" flex flex-col items-start gap-4 border-t bg-slate-50 p-4">
<div className="flex items-center gap-1">
Expand Down
33 changes: 20 additions & 13 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
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 (
<main>
<Header />
<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"
>
{data && data.map((doc, index) => {
return (
<DocCard
key={index}
docId={doc.id}
thumbnail={doc.thumbnail}
title={doc.name}
updatedAt={doc.updatedAt}
users={doc.users}
/>
)
})}
{data
&& data.length > 0
? data.map((doc, index) => {
return (
<DocCard
key={index}
docId={doc.id}
thumbnail={doc.thumbnail}
title={doc.name}
updatedAt={doc.updatedAt}
users={doc.users}
/>
)
})
: <></>}
</div>
</main>
);
Expand Down
18 changes: 10 additions & 8 deletions app/writer/[id]/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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(),
Expand All @@ -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) {
Expand Down
20 changes: 14 additions & 6 deletions app/writer/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | JSX.Element | JSX.Element[] | undefined>(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));
Expand All @@ -38,6 +41,8 @@ export default function Dashboard() {
return null;
}
},
retry: 5,
retryDelay: 100,
})

const createDocThumbnail = async () => {
Expand All @@ -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,/, '');

Expand All @@ -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) {
Expand All @@ -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({
Expand Down
25 changes: 13 additions & 12 deletions lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Loading

0 comments on commit 7b204f7

Please sign in to comment.