Skip to content

Commit

Permalink
David/file upload (#13)
Browse files Browse the repository at this point in the history
* first commit

* Created google drive upload feature

* Update route.ts

* Merged with changes in main and updated folder location to sistema email

* Updated package-lock

* Fixed ESLint issues

* Fixed ESLint issues

* fixed type errors

* Fixed type errors

* Updated .env.sample

* Testing API Failure

* implemented type safety with env variables

* Updated secret names to preserve functionality

* Added Firebase Files

* Added Github Actions

* Testing preview

* Testing cache control

* Testing cache control after lint :(

* We love Cache Control

* update package lock

* Resolved all Issues in Code Review, awaiting approval

* deleted env d ts

* Testing with env d ts

* fixed lint issues

* Update .env.sample

Co-authored-by: Chinemerem <[email protected]>

* Resolved issues

* Deleted lines

* reverted files to main

* reverted files to main

* Removed client id because apparently it wasn't necessary, might bite us in the rear end later

* Getting rid of unnecessary changes to main

---------

Co-authored-by: Chinemerem <[email protected]>
  • Loading branch information
ludavidca and ChinemeremChigbo authored Oct 6, 2024
1 parent c676837 commit b88f409
Show file tree
Hide file tree
Showing 9 changed files with 659 additions and 27 deletions.
1 change: 0 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ EMAIL_PASS=
EMAIL_SERVICE=
EMAIL_USER=
GDRIVE_CLIENT_EMAIL=
GDRIVE_CLIENT_ID=
GDRIVE_PRIVATE_KEY=
GDRIVE_PROJECT_ID=
POSTGRES_DATABASE=
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,4 @@ git push -f
```

- Commit messages and PR names are descriptive and written in **imperative tense**. The first word should be capitalized. E.g. "Create user REST endpoints", not "Created user REST endpoints"
- PRs can contain multiple commits, they do not need to be squashed together before merging as long as each commit is atomic. Our repo is configured to only allow squash commits to `main` so the entire PR will appear as 1 commit on `main`, but the individual commits are preserved when viewing the PR.
- PRs can contain multiple commits, they do not need to be squashed together before merging as long as each commit is atomic. Our repo is configured to only allow squash commits to `main` so the entire PR will appear as 1 commit on `main`, but the individual commits are preserved when viewing the PR.
52 changes: 52 additions & 0 deletions app/api/deleteFile/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { google } from 'googleapis';
import { NextRequest, NextResponse } from 'next/server';

export async function DELETE(req: NextRequest) {
const { searchParams } = new URL(req.url);
const fileId = searchParams.get('fileId');

if (!fileId) {
return NextResponse.json(
{ message: 'File ID is required' },
{ status: 400 }
);
}
try {
const private_key = process.env.GDRIVE_PRIVATE_KEY?.replace(/\\n/g, '\n');

if (!private_key) {
return NextResponse.json(
{ error: 'Missing Google Drive private key' },
{ status: 500 }
);
}

const auth = new google.auth.GoogleAuth({
projectId: process.env.GDRIVE_PROJECT_ID,
scopes: 'https://www.googleapis.com/auth/drive',
credentials: {
type: 'service_account',
client_email: process.env.GDRIVE_CLIENT_EMAIL,
private_key: private_key,
},
});

const drive = google.drive({ version: 'v3', auth });

// Delete the file
await drive.files.delete({
fileId: fileId,
});

return NextResponse.json(
{ message: 'File deleted successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error deleting file:', error);
return NextResponse.json(
{ message: 'Error deleting file', error: (error as Error).message },
{ status: 500 }
);
}
}
53 changes: 53 additions & 0 deletions app/api/searchDrive/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from 'next/server';
import { google } from 'googleapis';

export async function GET(req: NextRequest) {
const newHeaders = new Headers(req.headers);
newHeaders.set(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
);

const private_key = process.env.GDRIVE_PRIVATE_KEY?.replace(/\\n/g, '\n');

if (!private_key) {
return NextResponse.json(
{ error: 'Missing Google Drive private key' },
{ status: 500 }
);
}

const auth = new google.auth.GoogleAuth({
projectId: process.env.GDRIVE_PROJECTID,
scopes: 'https://www.googleapis.com/auth/drive',
credentials: {
type: 'service_account',
client_email: process.env.GDRIVE_CLIENT_EMAIL,
private_key: private_key,
},
});
const drive = google.drive({ version: 'v3', auth });

try {
const res = await drive.files.list({
q: "'1schkzvm_b46UGovHpQ2uH-X-nJtlm32_' in parents",
fields: 'nextPageToken, files(id, name)',
spaces: 'drive',
});

const files = res.data.files;
return NextResponse.json(
{ results: { files } },
{
status: 200,
headers: newHeaders,
}
);
} catch (err) {
console.error('Error querying Google Drive:', err);
return NextResponse.json(
{ error: 'Internal Server Error' },
{ status: 500 }
);
}
}
79 changes: 79 additions & 0 deletions app/api/uploadFile/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { google } from 'googleapis';
import { NextRequest, NextResponse } from 'next/server';
import { Readable } from 'node:stream';

export async function POST(req: NextRequest) {
const formData = await req.formData();

const file: File | null = formData.get('file') as File | null;
let fileBuffer: Buffer;

if (file instanceof File) {
const arrayBuffer = await file.arrayBuffer();
fileBuffer = Buffer.from(arrayBuffer);
} else {
console.error('No file was provided in the form data');
return NextResponse.json(
{ error: 'No file was provided' },
{ status: 400 }
);
}

const filename: string | null = formData.get('fileName') as string | null;

if (!filename) {
console.error('No filename was provided in the form data');
return NextResponse.json(
{ error: 'No filename was provided' },
{ status: 400 }
);
}

const private_key = process.env.GDRIVE_PRIVATE_KEY?.replace(/\\n/g, '\n');

if (!private_key) {
return NextResponse.json(
{ error: 'Missing Google Drive private key' },
{ status: 500 }
);
}

const auth = new google.auth.GoogleAuth({
projectId: process.env.GDRIVE_PROJECTID,
scopes: 'https://www.googleapis.com/auth/drive',
credentials: {
type: 'service_account',
client_email: process.env.GDRIVE_CLIENT_EMAIL,
private_key: private_key,
},
});

const drive = google.drive({ version: 'v3', auth });

try {
await drive.files.create({
requestBody: {
name: filename,
mimeType: 'application/pdf',
parents: ['1schkzvm_b46UGovHpQ2uH-X-nJtlm32_'],
driveId: '1schkzvm_b46UGovHpQ2uH-X-nJtlm32_',
},
media: {
mimeType: 'application/pdf',
body: Readable.from(fileBuffer),
},
supportsAllDrives: true,
});

return NextResponse.json(
{ message: 'File uploaded successfully' },
{ status: 200 }
);
} catch (error) {
console.error('Error uploading file:', error);
return NextResponse.json(
{ message: 'Error uploading file', error: (error as Error).message },
{ status: 500 }
);
}
}
Loading

0 comments on commit b88f409

Please sign in to comment.