Edits history of script submission #13999 for ' Create File (gdrive)'

  • bun
    type Gdrive = {
      token: string;
    };
    
    export async function main(gdrive_auth: Gdrive, fileName: string, fileContent: string, parentFolderId: string) {
      const UPLOAD_FILE_URL = `https://www.googleapis.com/upload/drive/v3/files?uploadType=media`;
    
      const token = gdrive_auth["token"];
    
      const response = await fetch(UPLOAD_FILE_URL, {
        method: "POST",
        headers: {
          Authorization: "Bearer " + token,
          "Content-Type": "application/octet-stream",
          "Content-Length": fileContent.length.toString(),
        },
        body: fileContent,
      });
    
      if (!response.ok) {
        throw new Error(`Failed to upload file: ${response.statusText}`);
      }
    
      const fileMetadata = {
        name: fileName,
        parents: [parentFolderId] // Set the parent folder ID here
      };
    
      const metadataResponse = await fetch(`https://www.googleapis.com/drive/v3/files`, {
        method: "PATCH",
        headers: {
          Authorization: "Bearer " + token,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(fileMetadata),
      });
    
      if (!metadataResponse.ok) {
        throw new Error(`Failed to update file metadata: ${metadataResponse.statusText}`);
      }
    
      return await metadataResponse.json();
    }

    Submitted by julian.rath348 273 days ago