I have a use case with the google drive API where I need to replace an existing file (A) with another file (B), based on ID. I need to keep the ID file to be replaced (A) (so a call to drive.copy will not work as it creates a new ID).
Is the best method to download the file (B) using a get call and then an update call on file (A) passing the data stream from B?
Or is there an API endpoint that can accomplish this already?
There is not such a function because you would have to generate a copy of file (B) and therefore create a file with a brand new ID
.
A workaround would be to delete the content of file (A) and copy the content of file (B) to file (A) so that both files are identical. In case of a Spreadsheet
scenario, I have a code snippet to show you the logic you can follow.
function myFunction() {
// Get Spreadsheet A and B
const ssA = SpreadsheetApp.openById('ID of Spreadsheet A');
const ssB = SpreadsheetApp.openById('ID of Spreadsheet B');
// Get all sheets for both Spreadsheet A and B
const a_sheets = ssA.getSheets();
const b_sheets = ssB.getSheets();
// Create a temporary sheet so we can delete all the old sheets from Spreadsheet A
const temp_sheet = ssA.insertSheet('temporary_sheet')
// Delete all old sheets from Spreadsheet A
a_sheets.forEach(shA=>ssA.deleteSheet(shA));
// Copy all Spreadsheet B sheets to Spreadsheet A
b_sheets.forEach(shB=>shB.copyTo(ssA).setName(shB.getSheetName()));
// Delete temporary sheet
ssA.deleteSheet(temp_sheet);
}
A very similar approach would work for Folders
. Namely, delete contents of Folder A, copy the contents of folders to Folder B. Folder A and B have the same content but A keeps its original ID. Of course you can do that with Slides
, Docs
etc.