1 | type Gdrive = { |
2 | token: string; |
3 | }; |
4 |
|
5 | export async function main(gdrive_auth: Gdrive, fileName: string, fileContent: string, parentFolderId: string) { |
6 | const UPLOAD_FILE_URL = `https://www.googleapis.com/upload/drive/v3/files?uploadType=media`; |
7 |
|
8 | const token = gdrive_auth["token"]; |
9 |
|
10 | const response = await fetch(UPLOAD_FILE_URL, { |
11 | method: "POST", |
12 | headers: { |
13 | Authorization: "Bearer " + token, |
14 | "Content-Type": "application/octet-stream", |
15 | "Content-Length": fileContent.length.toString(), |
16 | }, |
17 | body: fileContent, |
18 | }); |
19 |
|
20 | if (!response.ok) { |
21 | throw new Error(`Failed to upload file: ${response.statusText}`); |
22 | } |
23 |
|
24 | const fileMetadata = { |
25 | name: fileName, |
26 | parents: [parentFolderId] |
27 | }; |
28 |
|
29 | const metadataResponse = await fetch(`https://www.googleapis.com/drive/v3/files`, { |
30 | method: "PATCH", |
31 | headers: { |
32 | Authorization: "Bearer " + token, |
33 | "Content-Type": "application/json", |
34 | }, |
35 | body: JSON.stringify(fileMetadata), |
36 | }); |
37 |
|
38 | if (!metadataResponse.ok) { |
39 | throw new Error(`Failed to update file metadata: ${metadataResponse.statusText}`); |
40 | } |
41 |
|
42 | return await metadataResponse.json(); |
43 | } |