59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { authOptions } from '@/lib/auth';
|
|
import { WebDAVClient } from 'webdav';
|
|
|
|
// Use a single PrismaClient instance
|
|
declare global {
|
|
var prisma: PrismaClient | undefined;
|
|
}
|
|
|
|
const prisma = global.prisma || new PrismaClient();
|
|
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.email) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const folder = searchParams.get('folder') || 'Notes';
|
|
|
|
// Get WebDAV credentials
|
|
const credentials = await prisma.webDAVCredentials.findUnique({
|
|
where: { userId: session.user.email },
|
|
});
|
|
|
|
if (!credentials) {
|
|
return NextResponse.json({ error: 'No WebDAV credentials found' }, { status: 404 });
|
|
}
|
|
|
|
// Initialize WebDAV client
|
|
const client = new WebDAVClient({
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
baseURL: process.env.NEXTCLOUD_URL,
|
|
});
|
|
|
|
// List files in the specified folder
|
|
const files = await client.getDirectoryContents(`/remote.php/dav/files/${credentials.username}/Private/${folder}`);
|
|
|
|
// Filter for .md files and format the response
|
|
const markdownFiles = files
|
|
.filter((file: any) => file.basename.endsWith('.md'))
|
|
.map((file: any) => ({
|
|
id: file.filename,
|
|
title: file.basename.replace('.md', ''),
|
|
lastModified: new Date(file.lastmod).toISOString(),
|
|
size: file.size,
|
|
}));
|
|
|
|
return NextResponse.json(markdownFiles);
|
|
} catch (error) {
|
|
console.error('Error fetching files:', error);
|
|
return NextResponse.json({ error: 'Failed to fetch files' }, { status: 500 });
|
|
}
|
|
}
|