70 lines
2.1 KiB
TypeScript
70 lines
2.1 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { createClient } 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;
|
|
|
|
// Helper function to create WebDAV client
|
|
const createWebDAVClient = async (userId: string) => {
|
|
const credentials = await prisma.webDAVCredentials.findUnique({
|
|
where: { userId },
|
|
});
|
|
|
|
if (!credentials) {
|
|
throw new Error('No WebDAV credentials found');
|
|
}
|
|
|
|
const baseURL = process.env.NEXTCLOUD_URL;
|
|
if (!baseURL) {
|
|
throw new Error('NEXTCLOUD_URL environment variable is not set');
|
|
}
|
|
|
|
const normalizedBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
|
|
const webdavURL = `${normalizedBaseURL}/remote.php/dav`;
|
|
|
|
return {
|
|
client: createClient(webdavURL, {
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
authType: 'password',
|
|
}),
|
|
username: credentials.username
|
|
};
|
|
};
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const id = searchParams.get('id');
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ error: 'Note ID is required' }, { status: 400 });
|
|
}
|
|
|
|
const { client } = await createWebDAVClient(session.user.id);
|
|
|
|
try {
|
|
const content = await client.getFileContents(id, { format: 'text' });
|
|
return NextResponse.json({ content });
|
|
} catch (error) {
|
|
console.error('Error fetching note content:', error);
|
|
return NextResponse.json({ error: 'Failed to fetch note content' }, { status: 500 });
|
|
}
|
|
} catch (error) {
|
|
console.error('Error in GET request:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|