Suitescript function for fetching the web-view link of a file in a Shared Drive inside Google Drive using the file name. Please note that this only works when filenames are unique.
/**
* Function to get Google Drive link for a file
* @param {string} accessToken Access token string
* @param {string} rootFolderId Folder ID to be added in Drive storage
* @param {string} fileName Name of the file to be added in Drive storage
* @returns {string} linkValue
*/
const getFileLink = (accessToken, sharedDriveId, fileName) => {
try {
log.debug("Inside the getFileLink() function", { 'accessToken': accessToken, 'sharedDriveId': sharedDriveId, 'fileName': fileName });
let encodedFileNameValue = encodeURIComponent(fileName);
log.debug("encodedFileNameValue", encodedFileNameValue);
// Fetch File ID
let response = https.get({
url: `https://www.googleapis.com/drive/v3/files?supportsAllDrives=true&includeItemsFromAllDrives=true&corpora=drive&driveId=${sharedDriveId}&q=name='${encodedFileNameValue}'+and+mimeType+!='application/vnd.google-apps.folder'+and+trashed=false`,
headers: {
"Authorization": `Bearer ${accessToken}`,
},
});
let responseBody = JSON.parse(response.body);
log.debug("responseBody", responseBody);
let fileId = responseBody.files[0]['id'];
// Get file view link using the ID
if(jj_library.checkForParameter(fileId)){
let linkResponse = https.get({
url: `https://www.googleapis.com/drive/v3/files/${fileId}?fields=webViewLink&supportsAllDrives=true&includeItemsFromAllDrives=true`,
headers: {
"Authorization": `Bearer ${accessToken}`,
},
});
let linkResponseBody = JSON.parse(linkResponse.body);
log.debug("linkResponseBody", linkResponseBody);
let linkValue = linkResponseBody['webViewLink'];
return linkValue;
} else{
log.debug("Unable to fetch link");
return "";
}
} catch (error) {
log.debug("Error in getFileLink:", error);
}
}