Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions app/api/deleteDocument/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { NextResponse } from 'next/server';
import prisma from '@/utils/prisma';
import { getAuth } from '@clerk/nextjs/server';
import { Pinecone } from '@pinecone-database/pinecone';

interface DeleteFileParams {
accountId: string;
apiKey: string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to be a parameter?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I followed the docs of bytescale to implement functionality so I just added this to resolve typescript errors. The Api key is taken from the env variables and then passed to this. Can be removed but i though of keeping the same syntax as docs.

querystring: {
filePath: string;
};
}

const PINECONE_INDEX_NAME = process.env.PINECONE_INDEX_NAME ?? '';

const pinecone = new Pinecone({
apiKey: process.env.PINECONE_API_KEY ?? '',
environment: process.env.PINECONE_ENVIRONMENT ?? '',
});

if (!process.env.PINECONE_INDEX_NAME) {
throw new Error('Missing Pinecone index name in .env file');
}

async function deleteFile(params: DeleteFileParams) {
const baseUrl = 'https://api.bytescale.com';
const path = `/v2/accounts/${params.accountId}/files`;
const entries = (obj: Record<string, unknown>) =>
Object.entries(obj).filter(([, val]) => (val ?? null) !== null) as [
string,
string,
][];
const query = entries(params.querystring ?? {})
.flatMap(([k, v]) => (Array.isArray(v) ? v.map((v2) => [k, v2]) : [[k, v]]))
.map((kv) => kv.join('='))
.join('&');
const response = await fetch(
`${baseUrl}${path}${query.length > 0 ? '?' : ''}${query}`,
{
method: 'DELETE',
headers: Object.fromEntries(
entries({
Authorization: `Bearer ${params.apiKey}`,
}) as [string, string][],
),
},
);
if (Math.floor(response.status / 100) !== 2) {
const result = await response.json();
throw new Error(`Bytescale API Error: ${JSON.stringify(result)}`);
}
}

export async function DELETE(request: Request) {
const { id, fileUrl } = await request.json();

const { userId } = getAuth(request as any);

if (!userId) {
return NextResponse.json({ error: 'You must be logged in to delete data' });
}

try {
const document = await prisma.document.findFirst({
where: {
id,
userId,
},
});

if (!document) {
return NextResponse.json({ error: 'Document not found' });
}

const pathWithAccId = fileUrl.replace('https://upcdn.io/', '');
const accId = pathWithAccId.split('/')[0];
const path = pathWithAccId.replace(`${accId}/raw`, '');

deleteFile({
accountId: accId,
apiKey: !!process.env.NEXT_SECRET_BYTESCALE_API_KEY
? process.env.NEXT_SECRET_BYTESCALE_API_KEY
: 'no api key found',
querystring: {
filePath: path,
},
}).then(
() => console.log('Success.'),
(error) => {
console.error(error);
return NextResponse.json({
error: 'Could not delete document from cloud',
});
},
);

const index = pinecone.Index(PINECONE_INDEX_NAME);

try {
await index.namespace(id).deleteAll();
} catch (error) {
console.log(error);
}

await prisma.document.delete({
where: {
id,
},
});

return NextResponse.json({ text: 'Document deleted successfully', id });
} catch (error) {
console.log('error', error);
return NextResponse.json({ error: 'Failed to delete your data' });
}
}
53 changes: 50 additions & 3 deletions app/dashboard/dashboard-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ import { useRouter } from 'next/navigation';
import DocIcon from '@/components/ui/DocIcon';
import { formatDistanceToNow } from 'date-fns';
import { useState } from 'react';
import TrashIcon from '@/components/ui/Trash';

interface Document {
id: string;
fileName: string;
fileUrl: string;
createdAt: Date;
}

// Configuration for the uploader
const uploader = Uploader({
Expand All @@ -14,10 +22,15 @@ const uploader = Uploader({
: 'no api key found',
});

export default function DashboardClient({ docsList }: { docsList: any }) {
export default function DashboardClient({
initialDocsList,
}: {
initialDocsList: Document[];
}) {
const router = useRouter();

const [loading, setLoading] = useState(false);
const [docsList, setDocsList] = useState(initialDocsList);

const options = {
maxFileCount: 1,
Expand Down Expand Up @@ -70,6 +83,35 @@ export default function DashboardClient({ docsList }: { docsList: any }) {
router.push(`/document/${data.id}`);
}

async function deleteDocument(id: string, fileUrl: string) {
try {
const res = await fetch('/api/deleteDocument', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id,
fileUrl,
}),
});

if (!res.ok) {
throw new Error('Failed to delete document');
}

const data = await res.json();
if (data.error) {
console.log(data.error);
} else {
console.log('Document deleted successfully');
setDocsList(docsList.filter((doc) => doc.id !== id));
}
} catch (error) {
console.log('Error deleting document', error);
}
}

return (
<div className="mx-auto flex flex-col gap-4 container mt-10">
<h1 className="text-4xl leading-[1.1] tracking-tighter font-medium text-center">
Expand All @@ -81,7 +123,7 @@ export default function DashboardClient({ docsList }: { docsList: any }) {
{docsList.map((doc: any) => (
<div
key={doc.id}
className="flex justify-between p-3 hover:bg-gray-100 transition sm:flex-row flex-col sm:gap-0 gap-3"
className="flex justify-between p-3 items-center hover:bg-gray-100 transition sm:flex-row flex-col sm:gap-0 gap-3"
>
<button
onClick={() => router.push(`/document/${doc.id}`)}
Expand All @@ -90,7 +132,12 @@ export default function DashboardClient({ docsList }: { docsList: any }) {
<DocIcon />
<span>{doc.fileName}</span>
</button>
<span>{formatDistanceToNow(doc.createdAt)} ago</span>
<span className="flex items-center gap-3">
{formatDistanceToNow(doc.createdAt)} ago
<TrashIcon
onClick={() => deleteDocument(doc.id, doc.fileUrl)}
/>
</span>
</div>
))}
</div>
Expand Down
8 changes: 2 additions & 6 deletions app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Footer from '@/components/home/Footer';
import Header from '@/components/ui/Header';

export default function RootLayout({
Expand All @@ -7,12 +6,9 @@ export default function RootLayout({
children: React.ReactNode;
}) {
return (
<div className="min-h-screen flex flex-col ">
<div className="min-h-screen flex flex-col">
<Header />
<div className="flex-grow">{children}</div>
<div className="sm:p-7 sm:pb-0">
<Footer />
</div>
{children}
</div>
);
}
2 changes: 1 addition & 1 deletion app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default async function Page() {

return (
<div>
<DashboardClient docsList={docsList} />
<DashboardClient initialDocsList={docsList} />
</div>
);
}
27 changes: 27 additions & 0 deletions components/ui/Trash.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import React from 'react';

interface TrashIconProps {
onClick: () => void;
}

const TrashIcon: React.FC<TrashIconProps> = ({ onClick }) => {
return (
<>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
className="bi bi-trash hover:cursor-pointer m-2"
viewBox="0 0 16 16"
color="red"
onClick={onClick}
>
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z" />
<path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z" />
</svg>
</>
);
};

export default TrashIcon;