Files
examjam-frontend/torpedo/app/api/fetchcsv/route.ts
2025-07-03 01:43:25 +06:00

43 lines
1.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { google } from 'googleapis';
import { getServerSession } from 'next-auth';
import { authOptions } from '../auth/[...nextauth]/route';
async function listCSVFileNames(accessToken: string): Promise<string[]> {
const auth = new google.auth.OAuth2();
console.log(accessToken)
auth.setCredentials({ access_token: accessToken });
const drive = google.drive({ version: 'v3', auth });
try {
const res = await drive.files.list({
q: "mimeType='text/csv'",
fields: 'files(name)',
});
const fileNames = res.data.files?.map(file => file.name) || [];
return fileNames
} catch (error) {
console.error('Error listing CSV files:', error);
throw new Error('Failed to list CSV files');
}
}
export async function GET(request: Request) {
try {
const session = await getServerSession({ req: request, authOptions });
if (!session || !session.accessToken) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const fileNames = await listCSVFileNames(session.accessToken);
return NextResponse.json({ fileNames });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}