When I use DriveApp.getFolderById(someId) where someId
belongs to a file and not a folder, the method returns the file instead of erring out. How can I ensure that the returned object is indeed a folder?
Right now, the only solution I can think of is with try/catch:
try {
const testFile = someFile.makeCopy('test', folder);
testFile.setTrashed(true);
} catch (err) {
return 'The folder is not really a folder';
}
Is there a cleaner solution?
CodePudding user response:
In your situation, for example, how about checking the mimeType as follows?
Sample script:
const id = "###"; // Please set the file ID and folder ID.
const file = DriveApp.getFileById(id);
if (file.getMimeType() == MimeType.FOLDER) {
console.log(`This ID (${id}) is a folder.`);
const folder = DriveApp.getFolderById(id);
// Do something.
} else {
console.log(`This ID (${id}) is not a folder.`);
}
- When this script is run, by checking the mimeType of
id
, you can see whether the ID is the folder.
Reference:
Added:
From your following reply,
A folder doesn't have a getMimeType function to call, so I guess a check like if (!folder.getMimeType) that a returns true indicates that it's a folder.
If you want to check using const folder = DriveApp.getFolderById(id)
, how about the following sample script?
Sample script:
const id = "###"; // Please set the file ID and folder ID.
const folder = DriveApp.getFolderById(id);
if (folder.getUrl().split("/")[4] == "folders") {
console.log(`This ID (${id}) is a folder.`);
// In this case, you can directly use the variable of "folder".
// Do something.
} else {
console.log(`This ID (${id}) is not a folder.`);
}
- In this sample script, by checking the URL of the object, it is checked whether
id
is the folder. For example, whenid
is Spreadsheet, the retrieved URL is likehttps://docs.google.com/spreadsheets/d/###/edit?usp=drivesdk
. This script uses this situation.