103 lines
3.1 KiB
TypeScript
103 lines
3.1 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { getEmails } from '@/lib/services/email-service';
|
|
|
|
// Simple in-memory cache (will be removed in a future update)
|
|
interface EmailCacheEntry {
|
|
data: any;
|
|
timestamp: number;
|
|
}
|
|
|
|
// Cache for 1 minute only
|
|
const CACHE_TTL = 60 * 1000;
|
|
const emailListCache: Record<string, EmailCacheEntry> = {};
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
// Authenticate user
|
|
const session = await getServerSession(authOptions);
|
|
if (!session || !session.user?.id) {
|
|
return NextResponse.json(
|
|
{ error: "Not authenticated" },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// Extract query parameters
|
|
const { searchParams } = new URL(request.url);
|
|
const page = parseInt(searchParams.get("page") || "1");
|
|
const perPage = parseInt(searchParams.get("perPage") || "20");
|
|
const folder = searchParams.get("folder") || "INBOX";
|
|
const searchQuery = searchParams.get("search") || "";
|
|
|
|
// Check cache - temporary until we implement a proper server-side cache
|
|
const cacheKey = `${session.user.id}:${folder}:${page}:${perPage}:${searchQuery}`;
|
|
const now = Date.now();
|
|
const cachedEmails = emailListCache[cacheKey];
|
|
|
|
if (cachedEmails && now - cachedEmails.timestamp < CACHE_TTL) {
|
|
console.log(`Using cached emails for ${cacheKey}`);
|
|
return NextResponse.json(cachedEmails.data);
|
|
}
|
|
|
|
console.log(`Cache miss for ${cacheKey}, fetching emails`);
|
|
|
|
// Use the email service to fetch emails
|
|
const emailsResult = await getEmails(
|
|
session.user.id,
|
|
folder,
|
|
page,
|
|
perPage,
|
|
searchQuery
|
|
);
|
|
|
|
// Cache the results
|
|
emailListCache[cacheKey] = {
|
|
data: emailsResult,
|
|
timestamp: now
|
|
};
|
|
|
|
return NextResponse.json(emailsResult);
|
|
} catch (error: any) {
|
|
console.error("Error fetching emails:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to fetch emails", message: error.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { emailId, folderName } = await request.json();
|
|
|
|
if (!emailId) {
|
|
return NextResponse.json({ error: 'Missing emailId parameter' }, { status: 400 });
|
|
}
|
|
|
|
// Invalidate cache entries for this folder or all folders if none specified
|
|
const userId = session.user.id;
|
|
Object.keys(emailListCache).forEach(key => {
|
|
if (folderName) {
|
|
if (key.includes(`${userId}:${folderName}`)) {
|
|
delete emailListCache[key];
|
|
}
|
|
} else {
|
|
if (key.startsWith(`${userId}:`)) {
|
|
delete emailListCache[key];
|
|
}
|
|
}
|
|
});
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error('Error in POST handler:', error);
|
|
return NextResponse.json({ error: 'An unexpected error occurred' }, { status: 500 });
|
|
}
|
|
}
|