From 525146401c92eb66f3ea87683bfae2335737a3e0 Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Mon, 15 Sep 2025 15:23:38 -0600 Subject: [PATCH 1/2] docs: update comments --- adminSDK/directory/index.js | 6 ++ adminSDK/reports/index.js | 7 +++ adminSDK/reseller/index.js | 6 ++ apps-script/execute/index.js | 26 ++++----- calendar/quickstart/index.js | 6 ++ chat/quickstart/index.js | 17 +++--- classroom/quickstart/index.js | 7 +++ docs/quickstart/index.js | 7 +++ drive/activity-v2/index.js | 11 +++- drive/quickstart/index.js | 8 ++- .../appdata_snippets/fetch_appdata_folder.js | 17 ++++-- .../drive_v2/appdata_snippets/list_appdata.js | 15 +++-- .../appdata_snippets/upload_appdata.js | 21 +++++-- .../drive_v2/change_snippets/fetch_changes.js | 20 +++++-- .../change_snippets/fetch_start_page_token.js | 15 +++-- .../drive_v2/drive_snippets/create_drive.js | 20 +++++-- .../drive_v2/drive_snippets/recover_drives.js | 16 +++-- .../drive_v2/file snippets/create_folder.js | 19 ++++-- .../drive_v2/file snippets/create_shortcut.js | 19 ++++-- .../drive_v2/file snippets/download_file.js | 17 ++++-- .../drive_v2/file snippets/export_pdf.js | 17 ++++-- .../file snippets/move_file_to_folder.js | 24 +++++--- .../drive_v2/file snippets/search_file.js | 16 +++-- .../drive_v2/file snippets/share_file.js | 27 +++++---- .../drive_v2/file snippets/touch_file.js | 19 +++--- .../drive_v2/file snippets/upload_basic.js | 21 +++++-- .../file snippets/upload_to_folder.js | 23 ++++++-- .../file snippets/upload_with_conversion.js | 22 +++++-- .../appdata_snippets/fetch_appdata_folder.js | 17 ++++-- .../drive_v3/appdata_snippets/list_appdata.js | 17 ++++-- .../appdata_snippets/upload_appdata.js | 21 +++++-- .../drive_v3/change_snippets/fetch_changes.js | 25 +++++--- .../change_snippets/fetch_start_page_token.js | 19 ++++-- .../drive_v3/drive_snippets/create_drive.js | 20 +++++-- .../drive_v3/drive_snippets/recover_drives.js | 20 ++++--- .../drive_v3/file_snippets/create_folder.js | 17 ++++-- .../drive_v3/file_snippets/create_shortcut.js | 17 ++++-- .../drive_v3/file_snippets/download_file.js | 16 +++-- .../drive_v3/file_snippets/export_pdf.js | 16 +++-- .../file_snippets/move_file_to_folder.js | 23 +++++--- .../drive_v3/file_snippets/search_file.js | 13 ++++- .../drive_v3/file_snippets/share_file.js | 23 +++++--- .../drive_v3/file_snippets/touch_file.js | 22 ++++--- .../drive_v3/file_snippets/upload_basic.js | 18 ++++-- .../file_snippets/upload_to_folder.js | 21 +++++-- .../file_snippets/upload_with_conversion.js | 19 ++++-- forms/snippets/add_item.js | 16 ++++- forms/snippets/add_responder.js | 11 +++- forms/snippets/anyone_with_link_responder.js | 17 ++++++ forms/snippets/convert_form.js | 15 ++++- forms/snippets/create_form.js | 11 ++++ forms/snippets/create_watch.js | 14 +++++ forms/snippets/delete_watch.js | 11 ++++ forms/snippets/get_all_responses.js | 10 ++++ forms/snippets/get_form.js | 10 ++++ forms/snippets/get_responders.js | 8 ++- forms/snippets/get_single_response.js | 11 ++++ forms/snippets/list_watches.js | 10 ++++ forms/snippets/publish_form.js | 4 ++ forms/snippets/remove_responders.js | 58 ++++++++++--------- forms/snippets/renew_watch.js | 11 ++++ forms/snippets/stop_accepting_responses.js | 10 +++- forms/snippets/supports_publishing.js | 9 ++- forms/snippets/unpublish_form.js | 4 ++ forms/snippets/update_form.js | 16 ++++- gmail/quickstart/index.js | 6 ++ meet/quickstart/index.js | 10 +++- people/quickstart/index.js | 8 ++- sheets/quickstart/index.js | 7 +++ sheets/snippets/sheets_append_values.js | 22 +++++-- sheets/snippets/sheets_batch_get_values.js | 17 ++++-- sheets/snippets/sheets_batch_update.js | 32 +++++++--- sheets/snippets/sheets_batch_update_values.js | 27 ++++++--- .../snippets/sheets_conditional_formatting.js | 16 ++++- sheets/snippets/sheets_create.js | 12 +++- sheets/snippets/sheets_get_values.js | 11 ++-- sheets/snippets/sheets_pivot_table.js | 21 +++++-- sheets/snippets/sheets_update_values.js | 22 +++++-- slides/quickstart/index.js | 11 +++- slides/snippets/slides_copy_presentation.js | 15 ++++- .../snippets/slides_create_bulleted_text.js | 13 +++-- slides/snippets/slides_create_image.js | 20 +++++-- slides/snippets/slides_create_presentation.js | 11 +++- slides/snippets/slides_create_sheets_chart.js | 24 +++++--- slides/snippets/slides_create_slide.js | 9 ++- .../slides_create_textbox_with_text.js | 19 ++++-- slides/snippets/slides_image_merging.js | 20 ++++--- .../snippets/slides_refresh_sheets_chart.js | 12 +++- slides/snippets/slides_simple_text_replace.js | 16 +++-- slides/snippets/slides_text_merging.js | 38 ++++++------ slides/snippets/slides_text_style_update.js | 18 ++++-- tasks/quickstart/index.js | 6 ++ 92 files changed, 1111 insertions(+), 381 deletions(-) diff --git a/adminSDK/directory/index.js b/adminSDK/directory/index.js index 5aaf7c36..58e11347 100644 --- a/adminSDK/directory/index.js +++ b/adminSDK/directory/index.js @@ -21,19 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for the Admin SDK Directory API. const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the first 10 users in the domain. */ async function listUsers() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Admin SDK Directory API client. const service = google.admin({version: 'directory_v1', auth}); + // Get the list of users. const result = await service.users.list({ customer: 'my_customer', maxResults: 10, @@ -46,6 +51,7 @@ async function listUsers() { return; } + // Print the primary email and full name of each user. console.log('Users:'); users.forEach((user) => { console.log(`${user.primaryEmail} (${user.name?.fullName})`); diff --git a/adminSDK/reports/index.js b/adminSDK/reports/index.js index 7d37fd5b..fcd73a40 100644 --- a/adminSDK/reports/index.js +++ b/adminSDK/reports/index.js @@ -21,18 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for the Admin SDK Reports API. const SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the last 10 login events for the domain. */ async function listLoginEvents() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + + // Create a new Admin SDK Reports API client. const service = google.admin({version: 'reports_v1', auth}); + // Get the list of login events. const result = await service.activities.list({ userKey: 'all', applicationName: 'login', @@ -44,6 +50,7 @@ async function listLoginEvents() { return; } + // Print the time, email, and event name of each login event. console.log('Logins:'); activities.forEach((activity) => { console.log( diff --git a/adminSDK/reseller/index.js b/adminSDK/reseller/index.js index cef5ed83..0674f6a4 100644 --- a/adminSDK/reseller/index.js +++ b/adminSDK/reseller/index.js @@ -21,19 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for the Admin SDK Reseller API. const SCOPES = ['https://www.googleapis.com/auth/apps.order']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the first 10 subscriptions you manage. */ async function listSubscriptions() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Admin SDK Reseller API client. const service = google.reseller({version: 'v1', auth}); + // Get the list of subscriptions. const result = await service.subscriptions.list({ maxResults: 10, }); @@ -43,6 +48,7 @@ async function listSubscriptions() { return; } + // Print the customer ID, SKU ID, and plan name of each subscription. console.log('Subscriptions:'); subscriptions.forEach(({customerId, skuId, plan}) => { console.log(`${customerId} (${skuId}, ${plan?.planName})`); diff --git a/apps-script/execute/index.js b/apps-script/execute/index.js index 60e0a451..e7dec52f 100644 --- a/apps-script/execute/index.js +++ b/apps-script/execute/index.js @@ -20,22 +20,25 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Call an Apps Script function to list the folders in the user's root Drive - * folder. + * Calls an Apps Script function to list the folders in the user's root Drive folder. */ async function callAppsScript() { + // The ID of the Apps Script project to call. const scriptId = '1xGOh6wCm7hlIVSVPKm0y_dL-YqetspS5DEVmMzaxd_6AAvI-_u8DSgBT'; - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Apps Script API client. const script = google.script({version: 'v1', auth}); - // Make the API request. The request object is included here as 'resource'. + const resp = await script.scripts.run({ auth, requestBody: { + // The name of the function to call in the Apps Script project. function: 'getFoldersUnderRoot', }, scriptId, @@ -43,26 +46,21 @@ async function callAppsScript() { if (resp.data.error?.details?.[0]) { // The API executed, but the script returned an error. - - // Extract the first (and only) set of error details. The values of this - // object are the script's 'errorMessage' and 'errorType', and an array of - // stack trace elements. + // Extract the error details. const error = resp.data.error.details[0]; - console.log(`Script error message: ${error.errorMessage}`); console.log('Script error stacktrace:'); if (error.scriptStackTraceElements) { - // There may not be a stacktrace if the script didn't start executing. + // Log the stack trace. for (let i = 0; i < error.scriptStackTraceElements.length; i++) { const trace = error.scriptStackTraceElements[i]; console.log('\t%s: %s', trace.function, trace.lineNumber); } } } else { - // The structure of the result depends on the Apps Script function's return value. - // Here, the function returns an object with string keys and values, which is - // treated as a Node.js object (folderSet). + // The script executed successfully. + // The structure of the response depends on the Apps Script function's return value. const folderSet = resp.data.response ?? {}; if (Object.keys(folderSet).length === 0) { console.log('No folders returned!'); diff --git a/calendar/quickstart/index.js b/calendar/quickstart/index.js index 249ba965..638694d7 100644 --- a/calendar/quickstart/index.js +++ b/calendar/quickstart/index.js @@ -21,19 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading calendar events. const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the next 10 events on the user's primary calendar. */ async function listEvents() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Calendar API client. const calendar = google.calendar({version: 'v3', auth}); + // Get the list of events. const result = await calendar.events.list({ calendarId: 'primary', timeMin: new Date().toISOString(), @@ -48,6 +53,7 @@ async function listEvents() { } console.log('Upcoming 10 events:'); + // Print the start time and summary of each event. for (const event of events) { const start = event.start?.dateTime ?? event.start?.date; console.log(`${start} - ${event.summary}`); diff --git a/chat/quickstart/index.js b/chat/quickstart/index.js index 6e11911a..9f0e601c 100644 --- a/chat/quickstart/index.js +++ b/chat/quickstart/index.js @@ -21,35 +21,38 @@ import process from 'node:process'; import {ChatServiceClient} from '@google-apps/chat'; import {authenticate} from '@google-cloud/local-auth'; +// The scope for reading Chat spaces. const SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Lists spaces with user credential. + * Lists the spaces that the user is a member of. */ async function listSpaces() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - // Create a client + // Create a new Chat API client. const chatClient = new ChatServiceClient({ authClient, scopes: SCOPES, }); - // Initialize request argument(s) + // The request to list spaces. const request = { - // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE) + // Filter spaces by type. In this case, we are only interested in "SPACE" type. filter: 'space_type = "SPACE"', }; - // Make the request + // Make the API request. const pageResult = chatClient.listSpacesAsync(request); - // Handle the response. Iterating over pageResult will yield results - // and resolve additional pages automatically. + // Process the response. + // The `pageResult` is an async iterable that will yield each space. for await (const response of pageResult) { console.log(response); } diff --git a/classroom/quickstart/index.js b/classroom/quickstart/index.js index b871287b..5c4e1b86 100644 --- a/classroom/quickstart/index.js +++ b/classroom/quickstart/index.js @@ -21,18 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading Classroom courses. const SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the first 10 courses the user has access to. */ async function listCourses() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + + // Create a new Classroom API client. const classroom = google.classroom({version: 'v1', auth}); + // Get the list of courses. const result = await classroom.courses.list({ pageSize: 10, }); @@ -42,6 +48,7 @@ async function listCourses() { return; } console.log('Courses:'); + // Print the name and ID of each course. courses.forEach((course) => { console.log(`${course.name} (${course.id})`); }); diff --git a/docs/quickstart/index.js b/docs/quickstart/index.js index de52c150..ce3592a0 100644 --- a/docs/quickstart/index.js +++ b/docs/quickstart/index.js @@ -21,7 +21,9 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading Google Docs. const SCOPES = ['https://www.googleapis.com/auth/documents.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** @@ -29,14 +31,19 @@ const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); * https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit */ async function printDocTitle() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + + // Create a new Docs API client. const docs = google.docs({version: 'v1', auth}); + // Get the document. const result = await docs.documents.get({ documentId: '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE', }); + // Print the title of the document. console.log(`The title of the document is: ${result.data.title}`); } diff --git a/drive/activity-v2/index.js b/drive/activity-v2/index.js index 6ab4ac03..de351ce7 100644 --- a/drive/activity-v2/index.js +++ b/drive/activity-v2/index.js @@ -21,21 +21,30 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading Drive activity. const SCOPES = ['https://www.googleapis.com/auth/drive.activity.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the recent activity in your Google Drive. */ async function listDriveActivity() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + + // Create a new Drive Activity API client. const service = google.driveactivity({version: 'v2', auth}); + + // The parameters for the activity query. const params = { pageSize: 10, }; + + // Query for recent activity. const result = await service.activity.query({requestBody: params}); const activities = result.data.activities; if (!activities || activities.length === 0) { @@ -43,7 +52,7 @@ async function listDriveActivity() { return; } console.log('Recent activity:'); - + // Print the recent activity. console.log(JSON.stringify(activities, null, 2)); } diff --git a/drive/quickstart/index.js b/drive/quickstart/index.js index 0338e777..03e00527 100644 --- a/drive/quickstart/index.js +++ b/drive/quickstart/index.js @@ -21,30 +21,36 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading file metadata. const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the names and IDs of up to 10 files. */ async function listFiles() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Drive API client. const drive = google.drive({version: 'v3', auth}); + // Get the list of files. const result = await drive.files.list({ pageSize: 10, fields: 'nextPageToken, files(id, name)', }); const files = result.data.files; - if (!files) { + if (!files || files.length === 0) { console.log('No files found.'); return; } console.log('Files:'); + // Print the name and ID of each file. files.forEach((file) => { console.log(`${file.name} (${file.id})`); }); diff --git a/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js b/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js index 2ded0f2d..d272bebb 100644 --- a/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js +++ b/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js @@ -20,21 +20,30 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * List out application data folder and prints folder ID + * Fetches the ID of the application data folder. + * @return {Promise} The ID of the application data folder. */ async function fetchAppdataFolder() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // Get the application data folder. const file = await service.files.get({ fileId: 'appDataFolder', fields: 'id', }); + + // Print the folder ID. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive_v2/appdata_snippets/list_appdata.js b/drive/snippets/drive_v2/appdata_snippets/list_appdata.js index 12c2cf54..393ad16a 100644 --- a/drive/snippets/drive_v2/appdata_snippets/list_appdata.js +++ b/drive/snippets/drive_v2/appdata_snippets/list_appdata.js @@ -20,27 +20,32 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * List all files inserted in the application data folder + * Lists all files in the application data folder. + * @return {Promise} A list of files. */ async function listAppdata() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // List the files in the application data folder. const result = await service.files.list({ spaces: 'appDataFolder', fields: 'nextPageToken, items(id, title)', maxResults: 100, }); + // Print the title and ID of each file. (result.data.items ?? []).forEach((file) => { console.log('Found file:', file.title, file.id); }); - return result.data.items; + return result.data.items ?? []; } // [END drive_list_appdata] diff --git a/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js b/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js index 33d706ef..6bad7d03 100644 --- a/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js +++ b/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js @@ -21,16 +21,20 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Insert a file in the application data folder and prints file Id. + * Uploads a file to the application data folder. + * @return {Promise} The ID of the uploaded file. */ async function uploadAppdata() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the file to be uploaded. const fileMetadata = { title: 'config.json', parents: [ @@ -39,16 +43,25 @@ async function uploadAppdata() { }, ], }; + + // The media content to be uploaded. const media = { mimeType: 'application/json', body: fs.createReadStream('files/config.json'), }; + + // Upload the file to the application data folder. const file = await service.files.insert({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_appdata] diff --git a/drive/snippets/drive_v2/change_snippets/fetch_changes.js b/drive/snippets/drive_v2/change_snippets/fetch_changes.js index 3418c107..2c9e6ab6 100644 --- a/drive/snippets/drive_v2/change_snippets/fetch_changes.js +++ b/drive/snippets/drive_v2/change_snippets/fetch_changes.js @@ -20,26 +20,34 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Retrieve the list of changes for the currently authenticated user + * Fetches the list of changes for the currently authenticated user. + * @return {Promise} A list of changes. */ async function fetchChanges() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The page token for the next page of changes. If not set, the first page is retrieved. let pageToken; + + // Fetch the list of changes. const result = await service.changes.list({ pageToken, fields: '*', }); - // Process changes + + // Process the changes. (result.data.items ?? []).forEach((change) => { console.log('Change found for file:', change.fileId); }); - return result.data.items; + + return result.data.items ?? []; } // [END drive_fetch_changes] diff --git a/drive/snippets/drive_v2/change_snippets/fetch_start_page_token.js b/drive/snippets/drive_v2/change_snippets/fetch_start_page_token.js index d39dda8e..03cc6fdd 100644 --- a/drive/snippets/drive_v2/change_snippets/fetch_start_page_token.js +++ b/drive/snippets/drive_v2/change_snippets/fetch_start_page_token.js @@ -20,18 +20,25 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Retrieve page token for the current state of the account + * Fetches the start page token for the current state of the user's account. + * @return {Promise} The start page token. */ async function fetchStartPageToken() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // Fetch the start page token. const result = await service.changes.getStartPageToken(); console.log('Start token:', result.data.startPageToken); + if (!result.data.startPageToken) { + throw new Error('Start page token not found.'); + } return result.data.startPageToken; } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v2/drive_snippets/create_drive.js b/drive/snippets/drive_v2/drive_snippets/create_drive.js index ab02adb8..8dd99717 100644 --- a/drive/snippets/drive_v2/drive_snippets/create_drive.js +++ b/drive/snippets/drive_v2/drive_snippets/create_drive.js @@ -21,27 +21,39 @@ import {google} from 'googleapis'; import {v4 as uuid} from 'uuid'; /** - * Create a drive. + * Creates a new shared drive. + * @return {Promise} The ID of the created shared drive. */ async function createDrive() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + // The metadata for the new shared drive. const driveMetadata = { name: 'Project resources', }; + + // A unique request ID to avoid creating duplicate shared drives. const requestId = uuid(); + + // Create the new shared drive. const Drive = await service.drives.insert({ requestBody: driveMetadata, requestId, fields: 'id', }); + + // Print the ID of the new shared drive. console.log('Drive Id:', Drive.data.id); + if (!Drive.data.id) { + throw new Error('Drive ID not found.'); + } return Drive.data.id; } // [END drive_create_drive] diff --git a/drive/snippets/drive_v2/drive_snippets/recover_drives.js b/drive/snippets/drive_v2/drive_snippets/recover_drives.js index b744f97c..24e26da9 100644 --- a/drive/snippets/drive_v2/drive_snippets/recover_drives.js +++ b/drive/snippets/drive_v2/drive_snippets/recover_drives.js @@ -20,30 +20,34 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Find all shared drives without an organizer and add one. - * @param{string} userEmail The email of the user to transfer ownership to. + * Finds all shared drives without an organizer and adds one. + * @param {string} userEmail The email of the user to make an organizer. */ async function recoverDrives(userEmail) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + // The permission to add to the shared drive. const newOrganizerPermission = { type: 'user', role: 'organizer', - value: userEmail, // Example: 'user@example.com' + value: userEmail, }; + // List all shared drives with no organizers. const result = await service.drives.list({ q: 'organizerCount = 0', fields: 'nextPageToken, items(id, name)', useDomainAdminAccess: true, }); + // Add the new organizer to each found shared drive. for (const drive of result.data.items ?? []) { if (!drive.id) { continue; diff --git a/drive/snippets/drive_v2/file snippets/create_folder.js b/drive/snippets/drive_v2/file snippets/create_folder.js index 776667f8..90db780c 100644 --- a/drive/snippets/drive_v2/file snippets/create_folder.js +++ b/drive/snippets/drive_v2/file snippets/create_folder.js @@ -20,25 +20,36 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Create a folder and prints the folder ID + * Creates a new folder in Google Drive. + * @return {Promise} The ID of the created folder. */ async function createFolder() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the new folder. const fileMetadata = { title: 'Invoices', mimeType: 'application/vnd.google-apps.folder', }; + + // Create the new folder. const file = await service.files.insert({ requestBody: fileMetadata, fields: 'id', }); + + // Print the ID of the new folder. console.log('Folder Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_create_folder] diff --git a/drive/snippets/drive_v2/file snippets/create_shortcut.js b/drive/snippets/drive_v2/file snippets/create_shortcut.js index 68bb495a..53659ba4 100644 --- a/drive/snippets/drive_v2/file snippets/create_shortcut.js +++ b/drive/snippets/drive_v2/file snippets/create_shortcut.js @@ -20,25 +20,36 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Create a third party shortcut + * Creates a shortcut to a third-party resource. + * @return {Promise} The ID of the created shortcut. */ async function createShortcut() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the new shortcut. const fileMetadata = { title: 'Project plan', mimeType: 'application/vnd.google-apps.drive-sdk', }; + + // Create the new shortcut. const file = await service.files.insert({ requestBody: fileMetadata, fields: 'id', }); + + // Print the ID of the new shortcut. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_create_shortcut] diff --git a/drive/snippets/drive_v2/file snippets/download_file.js b/drive/snippets/drive_v2/file snippets/download_file.js index 38640b8c..ab483c42 100644 --- a/drive/snippets/drive_v2/file snippets/download_file.js +++ b/drive/snippets/drive_v2/file snippets/download_file.js @@ -20,22 +20,27 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Downloads a file - * @param{string} fileId file ID - * @return{Promise} file status + * Downloads a file from Google Drive. + * @param {string} fileId The ID of the file to download. + * @return {Promise} The status of the download. */ async function downloadFile(fileId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // Download the file. const file = await service.files.get({ fileId, alt: 'media', }); + + // Print the status of the download. console.log(file.status); return file.status; } diff --git a/drive/snippets/drive_v2/file snippets/export_pdf.js b/drive/snippets/drive_v2/file snippets/export_pdf.js index 8694fcae..6aecbfef 100644 --- a/drive/snippets/drive_v2/file snippets/export_pdf.js +++ b/drive/snippets/drive_v2/file snippets/export_pdf.js @@ -20,22 +20,27 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Download a Document file in PDF format - * @param{string} fileId file ID - * @return {Promise} file status + * Exports a Google Doc as a PDF. + * @param {string} fileId The ID of the file to export. + * @return {Promise} The response from the export request. */ async function exportPdf(fileId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // Export the file as a PDF. const result = await service.files.export({ fileId, mimeType: 'application/pdf', }); + + // Print the status of the export. console.log(result.status); return result; } diff --git a/drive/snippets/drive_v2/file snippets/move_file_to_folder.js b/drive/snippets/drive_v2/file snippets/move_file_to_folder.js index a1c83c17..aba1ddc5 100644 --- a/drive/snippets/drive_v2/file snippets/move_file_to_folder.js +++ b/drive/snippets/drive_v2/file snippets/move_file_to_folder.js @@ -20,35 +20,41 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Moves a file to a folder. - * @param{string} fileId Id of the file to move - * @param{string} folderId Id of the folder to move - * @return{Promise} file status + * Moves a file to a new folder in Google Drive. + * @param {string} fileId The ID of the file to move. + * @param {string} folderId The ID of the folder to move the file to. + * @return {Promise} The status of the move operation. */ async function moveFileToFolder(fileId, folderId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); - // Retrieve the existing parents to remove + + // Get the file's metadata to retrieve its current parents. const file = await service.files.get({ fileId, fields: 'parents', }); - // Move the file to the new folder + // Get the current parents as a comma-separated string. const previousParents = (file.data.parents ?? []) .map((parent) => parent.id) .join(','); + + // Move the file to the new folder. const files = await service.files.update({ fileId, addParents: folderId, removeParents: previousParents, fields: 'id, parents', }); + + // Print the status of the move operation. console.log(files.status); return files.status; } diff --git a/drive/snippets/drive_v2/file snippets/search_file.js b/drive/snippets/drive_v2/file snippets/search_file.js index fcfb1fcc..ec25f1cc 100644 --- a/drive/snippets/drive_v2/file snippets/search_file.js +++ b/drive/snippets/drive_v2/file snippets/search_file.js @@ -21,27 +21,35 @@ import {google} from 'googleapis'; /** * Searches for files in Google Drive. + * @return {Promise} A list of files. */ async function searchFile() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + // The page token for the next page of results. If not set, the first page is retrieved. const pageToken = undefined; + + // Search for files with the specified query. const result = await service.files.list({ q: "mimeType='image/jpeg'", fields: 'nextPageToken, items(id, title)', spaces: 'drive', pageToken, }); + + // Print the title and ID of each found file. (result.data.items ?? []).forEach((file) => { console.log('Found file:', file.title, file.id); }); - return result.data.items; + + return result.data.items ?? []; } // [END drive_search_file] diff --git a/drive/snippets/drive_v2/file snippets/share_file.js b/drive/snippets/drive_v2/file snippets/share_file.js index 467324fa..094aee40 100644 --- a/drive/snippets/drive_v2/file snippets/share_file.js +++ b/drive/snippets/drive_v2/file snippets/share_file.js @@ -20,39 +20,42 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Share a file with a user and a domain. - * @param{string} fileId The ID of the file to share. - * @param{string} targetUser The email address of the user to share with. - * @param{string} targetDomain The domain to share with. + * Shares a file with a user and a domain. + * @param {string} fileId The ID of the file to share. + * @param {string} targetUser The email address of the user to share with. + * @param {string} targetDomain The domain to share with. + * @return {Promise} A list of the inserted permission IDs. */ async function shareFile(fileId, targetUser, targetDomain) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); const permissionIds = []; + // The permissions to insert. const permissions = [ { type: 'user', role: 'writer', - value: targetUser, // Example: 'user@example.com', + value: targetUser, // e.g., 'user@example.com' }, { type: 'domain', role: 'writer', - value: targetDomain, // Example: 'example.com', + value: targetDomain, // e.g., 'example.com' }, ]; - // Note: Client library does not currently support HTTP batch requests. When - // possible, use batched requests when inserting multiple permissions on the - // same item. For this sample, permissions are inserted serially. + // Note: The client library does not currently support batch requests for permissions. + // When possible, use batch requests to insert multiple permissions on the same item. for (const permission of permissions) { try { + // Insert the permission. const result = await service.permissions.insert({ requestBody: permission, fileId, diff --git a/drive/snippets/drive_v2/file snippets/touch_file.js b/drive/snippets/drive_v2/file snippets/touch_file.js index 61a039f7..f990ca10 100644 --- a/drive/snippets/drive_v2/file snippets/touch_file.js +++ b/drive/snippets/drive_v2/file snippets/touch_file.js @@ -20,31 +20,36 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Change the file's modification timestamp. - * @param{string} fileId ID of the file to change modified time. - * @param{string} timestamp Timestamp to override the modification timestamp of the file. - * @return{Promise} The modified timestamp. + * Updates the modification timestamp of a file. + * @param {string} fileId The ID of the file to update. + * @param {string} timestamp The new modification timestamp. + * @return {Promise} The updated modification timestamp. */ async function touchFile(fileId, timestamp) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + // The metadata to update. const fileMetadata = { modifiedDate: new Date().toISOString(), modifiedTime: timestamp, }; + // Update the file's modification timestamp. const file = await service.files.update({ fileId, setModifiedDate: true, requestBody: fileMetadata, fields: 'id, modifiedDate', }); + + // Print the new modification timestamp. console.log('Modified time:', file.data.modifiedDate); return file.data.modifiedDate; } diff --git a/drive/snippets/drive_v2/file snippets/upload_basic.js b/drive/snippets/drive_v2/file snippets/upload_basic.js index f47d0e7c..36bfa042 100644 --- a/drive/snippets/drive_v2/file snippets/upload_basic.js +++ b/drive/snippets/drive_v2/file snippets/upload_basic.js @@ -21,29 +21,42 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Insert new file. + * Uploads a file to Google Drive. + * @return {Promise} The ID of the uploaded file. */ async function uploadBasic() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the file to be uploaded. const fileMetadata = { title: 'photo.jpg', }; + + // The media content to be uploaded. const media = { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; + + // Upload the file. const file = await service.files.insert({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_basic] diff --git a/drive/snippets/drive_v2/file snippets/upload_to_folder.js b/drive/snippets/drive_v2/file snippets/upload_to_folder.js index aaf0a98c..b7b75e4f 100644 --- a/drive/snippets/drive_v2/file snippets/upload_to_folder.js +++ b/drive/snippets/drive_v2/file snippets/upload_to_folder.js @@ -21,31 +21,44 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Upload a file to the specified folder and prints file ID, folder ID - * @param{string} folderId folder ID + * Uploads a file to a specific folder in Google Drive. + * @param {string} folderId The ID of the folder to upload the file to. + * @return {Promise} The ID of the uploaded file. */ async function uploadToFolder(folderId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the file to be uploaded. const fileMetadata = { title: 'photo.jpg', parents: [{id: folderId}], }; + + // The media content to be uploaded. const media = { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; + + // Upload the file to the specified folder. const file = await service.files.insert({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_to_folder] diff --git a/drive/snippets/drive_v2/file snippets/upload_with_conversion.js b/drive/snippets/drive_v2/file snippets/upload_with_conversion.js index ef47eb74..2146f6f1 100644 --- a/drive/snippets/drive_v2/file snippets/upload_with_conversion.js +++ b/drive/snippets/drive_v2/file snippets/upload_with_conversion.js @@ -21,30 +21,44 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Upload file with conversion + * Uploads a file to Google Drive and converts it to a Google Sheet. + * @return {Promise} The ID of the uploaded file. */ async function uploadWithConversion() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The metadata for the file to be uploaded and converted. const fileMetadata = { title: 'My Report', + // The MIME type to convert the file to. mimeType: 'application/vnd.google-apps.spreadsheet', }; + + // The media content to be uploaded. const media = { mimeType: 'text/csv', body: fs.createReadStream('files/report.csv'), }; + + // Upload the file with conversion. const file = await service.files.insert({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_with_conversion] diff --git a/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js b/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js index 3110db9a..b346acd5 100644 --- a/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js +++ b/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js @@ -20,21 +20,30 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * List out application data folder and prints folder ID + * Fetches the ID of the application data folder. + * @return {Promise} The ID of the application data folder. */ async function fetchAppdataFolder() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // Get the application data folder. const file = await service.files.get({ fileId: 'appDataFolder', fields: 'id', }); + + // Print the folder ID. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive_v3/appdata_snippets/list_appdata.js b/drive/snippets/drive_v3/appdata_snippets/list_appdata.js index 079ab7d7..edc32282 100644 --- a/drive/snippets/drive_v3/appdata_snippets/list_appdata.js +++ b/drive/snippets/drive_v3/appdata_snippets/list_appdata.js @@ -20,25 +20,32 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * List all files inserted in the application data folder + * Lists all files in the application data folder. + * @return {Promise} A list of files. */ async function listAppdata() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // List the files in the application data folder. const result = await service.files.list({ spaces: 'appDataFolder', fields: 'nextPageToken, files(id, name)', pageSize: 100, }); + + // Print the name and ID of each file. (result.data.files ?? []).forEach((file) => { console.log('Found file:', file.name, file.id); }); - return result.data.files; + + return result.data.files ?? []; } // [END drive_list_appdata] diff --git a/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js b/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js index 58ff720d..5a457782 100644 --- a/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js +++ b/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js @@ -21,30 +21,43 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Insert a file in the application data folder and prints file Id + * Uploads a file to the application data folder. + * @return {Promise} The ID of the uploaded file. */ async function uploadAppdata() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The metadata for the file to be uploaded. const fileMetadata = { name: 'config.json', parents: ['appDataFolder'], }; + + // The media content to be uploaded. const media = { mimeType: 'application/json', body: fs.createReadStream('files/config.json'), }; + + // Upload the file to the application data folder. const file = await service.files.create({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_appdata] diff --git a/drive/snippets/drive_v3/change_snippets/fetch_changes.js b/drive/snippets/drive_v3/change_snippets/fetch_changes.js index b4cb2afd..5e9c90f1 100644 --- a/drive/snippets/drive_v3/change_snippets/fetch_changes.js +++ b/drive/snippets/drive_v3/change_snippets/fetch_changes.js @@ -20,29 +20,36 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Retrieve the list of changes for the currently authenticated user. - * @param {string} savedStartPageToken page token got after executing - * fetch_start_page_token.js file - **/ + * Fetches the list of changes for the currently authenticated user. + * @param {string} savedStartPageToken The page token obtained from `fetch_start_page_token.js`. + */ async function fetchChanges(savedStartPageToken) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.readonly', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); - /** @type {string|null|undefined} */ + + // The page token for the next page of changes. let pageToken = savedStartPageToken; + + // Loop to fetch all changes, handling pagination. do { const result = await service.changes.list({ pageToken: savedStartPageToken, fields: '*', }); + + // Process the changes. (result.data.changes ?? []).forEach((change) => { console.log('change found for file: ', change.fileId); }); - pageToken = result.data.newStartPageToken; + + // Update the page token for the next iteration. + pageToken = result.data.newStartPageToken ?? ''; } while (pageToken); } // [END drive_fetch_changes] diff --git a/drive/snippets/drive_v3/change_snippets/fetch_start_page_token.js b/drive/snippets/drive_v3/change_snippets/fetch_start_page_token.js index fc8f6240..1ee9f352 100644 --- a/drive/snippets/drive_v3/change_snippets/fetch_start_page_token.js +++ b/drive/snippets/drive_v3/change_snippets/fetch_start_page_token.js @@ -16,23 +16,30 @@ // [START drive_fetch_start_page_token] -/** - * Retrieve page token for the current state of the account. - **/ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Fetches the start page token for the current state of the account. + * @return {Promise} The start page token. + */ async function fetchStartPageToken() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive.appdata', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // Fetch the start page token. const res = await service.changes.getStartPageToken({}); const token = res.data.startPageToken; console.log('start token: ', token); + if (!token) { + throw new Error('Start page token not found.'); + } return token; } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v3/drive_snippets/create_drive.js b/drive/snippets/drive_v3/drive_snippets/create_drive.js index ce846e57..578e8b29 100644 --- a/drive/snippets/drive_v3/drive_snippets/create_drive.js +++ b/drive/snippets/drive_v3/drive_snippets/create_drive.js @@ -21,27 +21,39 @@ import {google} from 'googleapis'; import {v4 as uuid} from 'uuid'; /** - * Create a drive. + * Creates a new shared drive. + * @return {Promise} The ID of the created shared drive. */ async function createDrive() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + // The metadata for the new shared drive. const driveMetadata = { name: 'Project resources', }; + + // A unique request ID to avoid creating duplicate shared drives. const requestId = uuid(); + + // Create the new shared drive. const Drive = await service.drives.create({ requestBody: driveMetadata, requestId, fields: 'id', }); + + // Print the ID of the new shared drive. console.log('Drive Id:', Drive.data.id); + if (!Drive.data.id) { + throw new Error('Drive ID not found.'); + } return Drive.data.id; } // [END drive_create_drive] diff --git a/drive/snippets/drive_v3/drive_snippets/recover_drives.js b/drive/snippets/drive_v3/drive_snippets/recover_drives.js index 0e622c78..0bbb9a32 100644 --- a/drive/snippets/drive_v3/drive_snippets/recover_drives.js +++ b/drive/snippets/drive_v3/drive_snippets/recover_drives.js @@ -20,29 +20,35 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Find all shared drives without an organizer and add one. - * @param{string} userEmail user ID to assign ownership to + * Finds all shared drives without an organizer and adds one. + * @param {string} userEmail The email of the user to assign ownership to. + * @return {Promise} A list of the recovered drives. */ async function recoverDrives(userEmail) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The permission to add to the shared drive. const newOrganizerPermission = { type: 'user', role: 'organizer', - emailAddress: userEmail, // Example: 'user@example.com' + emailAddress: userEmail, // e.g., 'user@example.com' }; + // List all shared drives with no organizers. const result = await service.drives.list({ q: 'organizerCount = 0', fields: 'nextPageToken, drives(id, name)', useDomainAdminAccess: true, }); + // Add the new organizer to each found shared drive. for (const drive of result.data.drives ?? []) { if (!drive.id) { continue; @@ -57,7 +63,7 @@ async function recoverDrives(userEmail) { fields: 'id', }); } - return result.data.drives; + return result.data.drives ?? []; } // [END drive_recover_drives] diff --git a/drive/snippets/drive_v3/file_snippets/create_folder.js b/drive/snippets/drive_v3/file_snippets/create_folder.js index b28e494d..5fefd42b 100644 --- a/drive/snippets/drive_v3/file_snippets/create_folder.js +++ b/drive/snippets/drive_v3/file_snippets/create_folder.js @@ -20,25 +20,32 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Create a folder and return the folder ID. - * @return{Promise} The folder ID. + * Creates a new folder in Google Drive. + * @return {Promise} The ID of the created folder. */ async function createFolder() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The metadata for the new folder. const fileMetadata = { name: 'Invoices', mimeType: 'application/vnd.google-apps.folder', }; + + // Create the new folder. const file = await service.files.create({ requestBody: fileMetadata, fields: 'id', }); + + // Print the ID of the new folder. console.log('Folder Id:', file.data.id); return file.data.id; } diff --git a/drive/snippets/drive_v3/file_snippets/create_shortcut.js b/drive/snippets/drive_v3/file_snippets/create_shortcut.js index d438aa9d..1886c6fc 100644 --- a/drive/snippets/drive_v3/file_snippets/create_shortcut.js +++ b/drive/snippets/drive_v3/file_snippets/create_shortcut.js @@ -20,25 +20,32 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Create a shortcut. - * @return{Promise} The shortcut ID. + * Creates a shortcut to a third-party resource. + * @return {Promise} The shortcut ID. */ async function createShortcut() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The metadata for the new shortcut. const fileMetadata = { name: 'Project plan', mimeType: 'application/vnd.google-apps.drive-sdk', }; + + // Create the new shortcut. const file = await service.files.create({ requestBody: fileMetadata, fields: 'id', }); + + // Print the ID of the new shortcut. console.log('File Id:', file.data.id); return file.data.id; } diff --git a/drive/snippets/drive_v3/file_snippets/download_file.js b/drive/snippets/drive_v3/file_snippets/download_file.js index 94eb62c9..23f0a174 100644 --- a/drive/snippets/drive_v3/file_snippets/download_file.js +++ b/drive/snippets/drive_v3/file_snippets/download_file.js @@ -20,23 +20,27 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Downloads a file - * @param{string} fileId file ID - * @return{Promise} file status + * Downloads a file from Google Drive. + * @param {string} fileId The ID of the file to download. + * @return {Promise} The status of the download. */ async function downloadFile(fileId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app - + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + // Download the file. const file = await service.files.get({ fileId, alt: 'media', }); + + // Print the status of the download. console.log(file.status); return file.status; } diff --git a/drive/snippets/drive_v3/file_snippets/export_pdf.js b/drive/snippets/drive_v3/file_snippets/export_pdf.js index e8027e93..50ed7ce5 100644 --- a/drive/snippets/drive_v3/file_snippets/export_pdf.js +++ b/drive/snippets/drive_v3/file_snippets/export_pdf.js @@ -20,21 +20,27 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Download a Document file in PDF format - * @param{string} fileId file ID - * @return{Promise} The status of the export request. + * Exports a Google Doc as a PDF. + * @param {string} fileId The ID of the file to export. + * @return {Promise} The status of the export request. */ async function exportPdf(fileId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // Export the file as a PDF. const result = await service.files.export({ fileId, mimeType: 'application/pdf', }); + + // Print the status of the export. console.log(result.status); return result.status; } diff --git a/drive/snippets/drive_v3/file_snippets/move_file_to_folder.js b/drive/snippets/drive_v3/file_snippets/move_file_to_folder.js index 41bed697..94cd66e9 100644 --- a/drive/snippets/drive_v3/file_snippets/move_file_to_folder.js +++ b/drive/snippets/drive_v3/file_snippets/move_file_to_folder.js @@ -20,32 +20,39 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Change the file's modification timestamp. - * @param{string} fileId Id of the file to move - * @param{string} folderId Id of the folder to move - * @return{Promise} result status + * Moves a file to a new folder in Google Drive. + * @param {string} fileId The ID of the file to move. + * @param {string} folderId The ID of the folder to move the file to. + * @return {Promise} The status of the move operation. */ async function moveFileToFolder(fileId, folderId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); - // Retrieve the existing parents to remove + + // Get the file's metadata to retrieve its current parents. const file = await service.files.get({ fileId, fields: 'parents', }); - // Move the file to the new folder + // Get the current parents as a comma-separated string. const previousParents = (file.data.parents ?? []).join(','); + + // Move the file to the new folder. const result = await service.files.update({ fileId, addParents: folderId, removeParents: previousParents, fields: 'id, parents', }); + + // Print the status of the move operation. console.log(result.status); return result.status; } diff --git a/drive/snippets/drive_v3/file_snippets/search_file.js b/drive/snippets/drive_v3/file_snippets/search_file.js index 56935a87..47539289 100644 --- a/drive/snippets/drive_v3/file_snippets/search_file.js +++ b/drive/snippets/drive_v3/file_snippets/search_file.js @@ -21,24 +21,31 @@ import {google} from 'googleapis'; /** * Searches for files in Google Drive. + * @return {Promise} A list of files. */ async function searchFile() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + // Search for files with the specified query. const result = await service.files.list({ q: "mimeType='image/jpeg'", fields: 'nextPageToken, files(id, name)', spaces: 'drive', }); + + // Print the name and ID of each found file. (result.data.files ?? []).forEach((file) => { console.log('Found file:', file.name, file.id); }); - return result.data.files; + + return result.data.files ?? []; } // [END drive_search_file] diff --git a/drive/snippets/drive_v3/file_snippets/share_file.js b/drive/snippets/drive_v3/file_snippets/share_file.js index 53695a25..fa6b5023 100644 --- a/drive/snippets/drive_v3/file_snippets/share_file.js +++ b/drive/snippets/drive_v3/file_snippets/share_file.js @@ -20,35 +20,40 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Share a file with a user and a domain. - * @param{string} fileId The ID of the file to share. - * @param{string} targetUserEmail The email address of the user to share with. - * @param{string} targetDomainName The domain to share with. - * @return{Promise>} A promise that resolves to an array of permission IDs. + * Shares a file with a user and a domain. + * @param {string} fileId The ID of the file to share. + * @param {string} targetUserEmail The email address of the user to share with. + * @param {string} targetDomainName The domain to share with. + * @return {Promise>} A promise that resolves to an array of permission IDs. */ async function shareFile(fileId, targetUserEmail, targetDomainName) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + /** @type {Array} */ const permissionIds = []; + // The permissions to create. const permissions = [ { type: 'user', role: 'writer', - emailAddress: targetUserEmail, // 'user@partner.com', + emailAddress: targetUserEmail, // e.g., 'user@partner.com' }, { type: 'domain', role: 'writer', - domain: targetDomainName, // 'example.com', + domain: targetDomainName, // e.g., 'example.com' }, ]; + // Iterate through the permissions and create them one by one. for (const permission of permissions) { const result = await service.permissions.create({ requestBody: permission, diff --git a/drive/snippets/drive_v3/file_snippets/touch_file.js b/drive/snippets/drive_v3/file_snippets/touch_file.js index bc2850e3..df3a6035 100644 --- a/drive/snippets/drive_v3/file_snippets/touch_file.js +++ b/drive/snippets/drive_v3/file_snippets/touch_file.js @@ -20,27 +20,35 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Change the file's modification timestamp. - * @param{string} fileId ID of the file to change modified time. - * @param{string} timestamp Timestamp to override the modification timestamp of the file. - * @return{Promise} The modified timestamp. - **/ + * Updates the modification timestamp of a file. + * @param {string} fileId The ID of the file to update. + * @param {string} timestamp The new modification timestamp. + * @return {Promise} The modified timestamp. + */ async function touchFile(fileId, timestamp) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The metadata to update. const fileMetadata = { modifiedTime: new Date().toISOString(), }; fileMetadata.modifiedTime = timestamp; + + // Update the file's modification timestamp. const file = await service.files.update({ fileId, requestBody: fileMetadata, fields: 'id, modifiedTime', }); + + // Print the new modification timestamp. console.log('Modified time:', file.data.modifiedTime); return file.data.modifiedTime; } diff --git a/drive/snippets/drive_v3/file_snippets/upload_basic.js b/drive/snippets/drive_v3/file_snippets/upload_basic.js index 03d11b84..ae34d2a2 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_basic.js +++ b/drive/snippets/drive_v3/file_snippets/upload_basic.js @@ -21,28 +21,38 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Insert new file. - * @return{Promise} file Id + * Uploads a file to Google Drive. + * @return {Promise} The ID of the uploaded file. */ async function uploadBasic() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The request body for the file to be uploaded. const requestBody = { name: 'photo.jpg', fields: 'id', }; + + // The media content to be uploaded. const media = { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; + + // Upload the file. const file = await service.files.create({ requestBody, media, }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); return file.data.id; } diff --git a/drive/snippets/drive_v3/file_snippets/upload_to_folder.js b/drive/snippets/drive_v3/file_snippets/upload_to_folder.js index 6009e2b1..7063aaef 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_to_folder.js +++ b/drive/snippets/drive_v3/file_snippets/upload_to_folder.js @@ -21,35 +21,44 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Upload a file to the specified folder - * @param{string} folderId folder ID + * Uploads a file to the specified folder. + * @param {string} folderId The ID of the folder to upload the file to. + * @return {Promise} The ID of the uploaded file. */ async function uploadToFolder(folderId) { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); - // TODO(developer): set folder Id - // folderId = '1lWo8HghUBd-3mN4s98ArNFMdqmhqCXH7'; + // The request body for the file to be uploaded. const requestBody = { name: 'photo.jpg', parents: [folderId], }; + + // The media content to be uploaded. const media = { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; + // Upload the file to the specified folder. const file = await service.files.create({ requestBody, media, fields: 'id', }); + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); + if (!file.data.id) { + throw new Error('File ID not found.'); + } return file.data.id; } // [END drive_upload_to_folder] diff --git a/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js b/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js index 46090ede..e9425409 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js +++ b/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js @@ -21,29 +21,40 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Upload file with conversion - * @return{Promise} file Id + * Uploads a file to Google Drive and converts it to a Google Sheet. + * @return {Promise} The ID of the uploaded file. */ async function uploadWithConversion() { - // Get credentials and build service - // TODO (developer) - Use appropriate auth mechanism for your app + // Authenticate with Google and get an authorized client. + // TODO (developer): Use an appropriate auth mechanism for your app. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Drive API client (v3). const service = google.drive({version: 'v3', auth}); + + // The metadata for the file to be uploaded and converted. const fileMetadata = { name: 'My Report', + // The MIME type to convert the file to. mimeType: 'application/vnd.google-apps.spreadsheet', }; + + // The media content to be uploaded. const media = { mimeType: 'text/csv', body: fs.createReadStream('files/report.csv'), }; + + // Upload the file with conversion. const file = await service.files.create({ requestBody: fileMetadata, media, fields: 'id', }); + + // Print the ID of the uploaded file. console.log('File Id:', file.data.id); return file.data.id; } diff --git a/forms/snippets/add_item.js b/forms/snippets/add_item.js index ba51e065..d311ba84 100644 --- a/forms/snippets/add_item.js +++ b/forms/snippets/add_item.js @@ -17,20 +17,30 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +/** + * Creates a new form and adds a video item to it. + */ async function addItem() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // The initial form to be created. const newForm = { info: { title: 'Creating a new form for batchUpdate in Node', }, }; + + // Create the new form. const createResponse = await formsClient.forms.create({ requestBody: newForm, }); @@ -41,7 +51,7 @@ async function addItem() { console.log(`New formId was: ${createResponse.data.formId}`); - // Request body to add video item to a Form + // Request body to add a video item to the form. const update = { requests: [ { @@ -55,6 +65,7 @@ async function addItem() { }, }, }, + // The location to insert the new item. location: { index: 0, }, @@ -62,10 +73,13 @@ async function addItem() { }, ], }; + + // Send the batch update request to add the item to the form. const updateResponse = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: update, }); + console.log(updateResponse.data); return updateResponse.data; } diff --git a/forms/snippets/add_responder.js b/forms/snippets/add_responder.js index df3387bc..0d322ff5 100644 --- a/forms/snippets/add_responder.js +++ b/forms/snippets/add_responder.js @@ -21,19 +21,23 @@ const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.file']; /** - * Adds a responder to the form. + * Adds a responder to a form. + * This is done by adding a permission to the form in Google Drive. * * @param {string} formId The ID of the form. - * @param {string} email The email of the responder. + * @param {string} email The email of the responder to add. */ async function addResponder(formId, email) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); + // The permission body to add a responder. const permissionBody = { role: 'reader', type: 'user', @@ -42,11 +46,12 @@ async function addResponder(formId, email) { }; try { + // Create the permission. const result = await driveService.permissions.create({ fileId: formId, requestBody: permissionBody, fields: 'id,emailAddress,role,type,view', - sendNotificationEmail: false, // Optional + sendNotificationEmail: false, // Optional: whether to send a notification email. }); console.log('Responder added:', result.data); } catch (err) { diff --git a/forms/snippets/anyone_with_link_responder.js b/forms/snippets/anyone_with_link_responder.js index 03c5d2f1..59102219 100644 --- a/forms/snippets/anyone_with_link_responder.js +++ b/forms/snippets/anyone_with_link_responder.js @@ -22,19 +22,23 @@ const SCOPES = ['https://www.googleapis.com/auth/drive.file']; /** * Checks if anyone with the link is a responder for the form. + * This is determined by checking the form's permissions in Google Drive. * * @param {string} formId The ID of the Google Form. */ async function isAnyoneWithLinkResponder(formId) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); let anyoneWithLinkResponder = false; try { + // List the permissions for the form. const result = await driveService.permissions.list({ fileId: formId, fields: 'permissions(id,type,role,view)', @@ -45,6 +49,8 @@ async function isAnyoneWithLinkResponder(formId) { if (permissions.length === 0) { console.log(`No permissions found for form ID: ${formId}`); } else { + // Check if there is a permission that allows anyone with the link to respond. + // This is indicated by a permission with type 'anyone', view 'published', and role 'reader'. for (const permission of permissions) { if ( permission.type === 'anyone' && @@ -75,17 +81,21 @@ async function isAnyoneWithLinkResponder(formId) { // [START forms_set_anyone_with_link_responder_js] /** * Sets anyone with the link to be a responder for the form. + * This is done by adding a permission to the form in Google Drive. * * @param {string} formId The ID of the Google Form. */ async function setAnyoneWithLinkResponder(formId) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); + // The permission body to allow anyone with the link to respond. const permissionBody = { type: 'anyone', view: 'published', // Key for making it a responder setting @@ -93,6 +103,7 @@ async function setAnyoneWithLinkResponder(formId) { }; try { + // Create the permission for the form. const result = await driveService.permissions.create({ fileId: formId, requestBody: permissionBody, @@ -111,19 +122,23 @@ async function setAnyoneWithLinkResponder(formId) { // [START forms_remove_anyone_with_link_responder_js] /** * Removes anyone with the link as a responder for the form. + * This is done by removing the corresponding permission from the form in Google Drive. * * @param {string} formId The ID of the Google Form. */ async function removeAnyoneWithLinkResponder(formId) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); let permissionIdToDelete = null; try { + // List the permissions for the form to find the one to delete. const result = await driveService.permissions.list({ fileId: formId, fields: 'permissions(id,type,role,view)', @@ -131,6 +146,7 @@ async function removeAnyoneWithLinkResponder(formId) { }); const permissions = result.data.permissions || []; + // Find the permission that allows anyone with the link to respond. for (const permission of permissions) { if ( permission.type === 'anyone' && @@ -143,6 +159,7 @@ async function removeAnyoneWithLinkResponder(formId) { } if (permissionIdToDelete) { + // Delete the permission. await driveService.permissions.delete({ fileId: formId, permissionId: permissionIdToDelete, diff --git a/forms/snippets/convert_form.js b/forms/snippets/convert_form.js index bff3cd7c..a832f95a 100644 --- a/forms/snippets/convert_form.js +++ b/forms/snippets/convert_form.js @@ -17,20 +17,30 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +/** + * Creates a new form and then converts it into a quiz. + */ async function convertForm() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // The initial form to be created. const newForm = { info: { title: 'Creating a new form for batchUpdate in Node', }, }; + + // Create the new form. const createResponse = await formsClient.forms.create({ requestBody: newForm, }); @@ -41,7 +51,7 @@ async function convertForm() { console.log(`New formId was: ${createResponse.data.formId}`); - // Request body to convert form to a quiz + // Request body to convert the form to a quiz. const updateRequest = { requests: [ { @@ -51,16 +61,19 @@ async function convertForm() { isQuiz: true, }, }, + // The updateMask specifies which fields to update. updateMask: 'quizSettings.isQuiz', }, }, ], }; + // Send the batch update request to convert the form to a quiz. const result = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: updateRequest, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/create_form.js b/forms/snippets/create_form.js index e3cfa600..dfd66fd3 100644 --- a/forms/snippets/create_form.js +++ b/forms/snippets/create_form.js @@ -17,23 +17,34 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +/** + * Creates a new form. + */ async function createForm() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // The request body to create a new form. const newForm = { info: { title: 'Creating a new form in Node', }, }; + + // Send the request to create the form. const result = await formsClient.forms.create({ requestBody: newForm, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/create_watch.js b/forms/snippets/create_watch.js index d7b8babb..b4b83f83 100644 --- a/forms/snippets/create_watch.js +++ b/forms/snippets/create_watch.js @@ -17,31 +17,45 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +/** + * Creates a watch on a form to get notifications for new responses. + */ async function createWatch() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // The request body to create a watch. const watchRequest = { watch: { target: { topic: { + // TODO: Replace with a valid Cloud Pub/Sub topic name. topicName: 'projects/', }, }, + // The event type to watch for. 'RESPONSES' is the only supported type. eventType: 'RESPONSES', }, }; + + // Send the request to create the watch. const result = await formsClient.forms.watches.create({ formId: formID, requestBody: watchRequest, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/delete_watch.js b/forms/snippets/delete_watch.js index 0dc7a5b3..d7188df6 100644 --- a/forms/snippets/delete_watch.js +++ b/forms/snippets/delete_watch.js @@ -17,22 +17,33 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +// TODO: Replace with a valid watch ID. const watchID = ''; +/** + * Deletes a watch from a form. + */ async function deleteWatch() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // Send the request to delete the watch. const result = await formsClient.forms.watches.delete({ formId: formID, watchId: watchID, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/get_all_responses.js b/forms/snippets/get_all_responses.js index 5f535891..ea48fd05 100644 --- a/forms/snippets/get_all_responses.js +++ b/forms/snippets/get_all_responses.js @@ -17,20 +17,30 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +/** + * Retrieves all responses from a form. + */ async function getAllResponses() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.responses.readonly', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); + + // Get the list of responses for the form. const result = await formsClient.forms.responses.list({ formId: formID, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/get_form.js b/forms/snippets/get_form.js index e1c7f4ee..5cc08a83 100644 --- a/forms/snippets/get_form.js +++ b/forms/snippets/get_form.js @@ -17,18 +17,28 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +/** + * Retrieves the content of a form. + */ async function getForm() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.body.readonly', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); + + // Get the form content. const result = await formsClient.forms.get({formId: formID}); + console.log(result.data); return result.data; } diff --git a/forms/snippets/get_responders.js b/forms/snippets/get_responders.js index a1268428..121c86e0 100644 --- a/forms/snippets/get_responders.js +++ b/forms/snippets/get_responders.js @@ -21,29 +21,35 @@ const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; /** - * Gets the responders to the form. + * Gets the responders of a form. + * This is done by listing the permissions of the form in Google Drive. * * @param {string} formId The ID of the form. */ async function getResponders(formId) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); try { + // List the permissions for the form. const result = await driveService.permissions.list({ fileId: formId, includePermissionsForView: 'published', fields: 'permissions(id,emailAddress,type,role,view)', }); + const permissions = result.data.permissions || []; if (permissions.length === 0) { console.log(`No permissions found for form ID: ${formId}`); } else { console.log('Responders for this form:'); + // A responder is a permission with view='published' and role='reader'. for (const permission of permissions) { if (permission.view === 'published' && permission.role === 'reader') { console.log(`Responder:`, permission); diff --git a/forms/snippets/get_single_response.js b/forms/snippets/get_single_response.js index 451b7199..f59fb848 100644 --- a/forms/snippets/get_single_response.js +++ b/forms/snippets/get_single_response.js @@ -17,22 +17,33 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +// TODO: Replace with a valid response ID. const responseID = ''; +/** + * Retrieves a single response from a form. + */ async function getSingleResponse() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.responses.readonly', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); + + // Get the specified response from the form. const result = await formsClient.forms.responses.get({ formId: formID, responseId: responseID, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/list_watches.js b/forms/snippets/list_watches.js index c4723bd0..bf67fc5f 100644 --- a/forms/snippets/list_watches.js +++ b/forms/snippets/list_watches.js @@ -17,20 +17,30 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +/** + * Lists the watches for a given form. + */ async function listWatches() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.responses.readonly', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); + + // Get the list of watches for the form. const result = await formsClient.forms.watches.list({ formId: formID, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/publish_form.js b/forms/snippets/publish_form.js index 475091c2..f576062a 100644 --- a/forms/snippets/publish_form.js +++ b/forms/snippets/publish_form.js @@ -26,16 +26,19 @@ const SCOPES = 'https://www.googleapis.com/auth/forms.body'; * @param {string} formIdToPublish The ID of the form to publish. */ async function publishForm(formIdToPublish) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + // The request body to publish the form and start accepting responses. const setPublishSettingsRequest = { publishSettings: { publishState: { @@ -46,6 +49,7 @@ async function publishForm(formIdToPublish) { }; try { + // Send the request to update the form's publish settings. const result = await formsClient.forms.setPublishSettings({ formId: formIdToPublish, requestBody: setPublishSettingsRequest, diff --git a/forms/snippets/remove_responders.js b/forms/snippets/remove_responders.js index ff70ea46..bc5de087 100644 --- a/forms/snippets/remove_responders.js +++ b/forms/snippets/remove_responders.js @@ -21,48 +21,50 @@ const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.file']; /** - * Remove a responder to the form. + * Remove a responder from a form. + * This is done by removing the corresponding permission from the form in Google Drive. * * @param {string} formId The ID of the form. - * @param {string} email The email of the responder. + * @param {string} email The email of the responder to remove. */ async function removeResponders(formId, email) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); - try { - const result = await driveService.permissions.list({ + // List the permissions for the form. + const result = await driveService.permissions.list({ + fileId: formId, + includePermissionsForView: 'published', + fields: 'permissions(id,emailAddress,type,role,view)', + }); + + const permissions = result.data.permissions || []; + // Find the permission that corresponds to the responder to be removed. + const responderToRemove = permissions.find( + (permission) => + permission.view === 'published' && + permission.role === 'reader' && + permission.emailAddress === email, + ); + + if (responderToRemove?.id) { + const permissionId = responderToRemove.id; + // Delete the permission. + await driveService.permissions.delete({ fileId: formId, - includePermissionsForView: 'published', - fields: 'permissions(id,emailAddress,type,role,view)', + permissionId: responderToRemove.id, }); - - const permissions = result.data.permissions || []; - const responderToRemove = permissions.find( - (permission) => - permission.view === 'published' && - permission.role === 'reader' && - permission.emailAddress === email, + console.log( + `Responder with permission ID '${permissionId}' removed successfully.`, ); - - if (responderToRemove?.id) { - const permissionId = responderToRemove.id; - await driveService.permissions.delete({ - fileId: formId, - permissionId: responderToRemove.id, - }); - console.log( - `Responder with permission ID '${permissionId}' removed successfully.`, - ); - } else { - console.log('Responder not found for the specified form'); - } - } catch (err) { - console.error('Error removing responder:', err); + } else { + console.log('Responder not found for the specified form'); } } diff --git a/forms/snippets/renew_watch.js b/forms/snippets/renew_watch.js index 95f539d3..2c1660a0 100644 --- a/forms/snippets/renew_watch.js +++ b/forms/snippets/renew_watch.js @@ -17,22 +17,33 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +// TODO: Replace with a valid form ID. const formID = ''; +// TODO: Replace with a valid watch ID. const watchID = ''; +/** + * Renews a watch on a form. + */ async function renewWatch() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // Send the request to renew the watch. const result = await formsClient.forms.watches.renew({ formId: formID, watchId: watchID, }); + console.log(result.data); return result.data; } diff --git a/forms/snippets/stop_accepting_responses.js b/forms/snippets/stop_accepting_responses.js index 9643db65..c21ec172 100644 --- a/forms/snippets/stop_accepting_responses.js +++ b/forms/snippets/stop_accepting_responses.js @@ -21,31 +21,35 @@ const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; /** - * Stops accepting responses to the form. + * Stops a form from accepting new responses. * * @param {string} formId The ID of the form. */ async function stopAcceptingResponses(formId) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + // The request body to stop accepting responses. const setPublishSettingsRequest = { publishSettings: { publishState: { - isPublished: true, // Keep it published (or ensure it is if it wasn't) - isAcceptingResponses: false, // Stop accepting responses + isPublished: true, // Keep the form published. + isAcceptingResponses: false, // Stop accepting new responses. }, }, }; try { + // Send the request to update the form's settings. const res = await formsClient.forms.setPublishSettings({ formId, requestBody: setPublishSettingsRequest, diff --git a/forms/snippets/supports_publishing.js b/forms/snippets/supports_publishing.js index 97652ac0..0024d8bb 100644 --- a/forms/snippets/supports_publishing.js +++ b/forms/snippets/supports_publishing.js @@ -21,30 +21,33 @@ const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; /** - * Checks if the form supports publishing. + * Checks if a form supports the `publishSettings` field, which indicates it is not a legacy form. * * @param {string} formIdToCheck The ID of the form to check. */ async function supportsPublishing(formIdToCheck) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); try { + // Get the form metadata. const result = await formsClient.forms.get({ formId: formIdToCheck, }); const formTitle = result.data.info?.title; - // If 'publishSettings' field exists (even if empty), it supports the new - // publishing model. + // If the 'publishSettings' field exists (even if empty), the form supports the new + // publishing model and is not a legacy form. if (result.data && result.data.publishSettings !== undefined) { console.log( `Form '${formIdToCheck}' (Title: ${ diff --git a/forms/snippets/unpublish_form.js b/forms/snippets/unpublish_form.js index 675ced9e..53a38180 100644 --- a/forms/snippets/unpublish_form.js +++ b/forms/snippets/unpublish_form.js @@ -26,16 +26,19 @@ const SCOPES = 'https://www.googleapis.com/auth/forms.body'; * @param {string} formIdToUnpublish The ID of the form to unpublish. */ async function unpublishForm(formIdToUnpublish) { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + // The request body to unpublish the form. const setPublishSettingsRequest = { publishSettings: { publishState: { @@ -45,6 +48,7 @@ async function unpublishForm(formIdToUnpublish) { }; try { + // Send the request to unpublish the form. const res = await formsClient.forms.setPublishSettings({ formId: formIdToUnpublish, requestBody: setPublishSettingsRequest, diff --git a/forms/snippets/update_form.js b/forms/snippets/update_form.js index 9244dede..b2330db8 100644 --- a/forms/snippets/update_form.js +++ b/forms/snippets/update_form.js @@ -17,20 +17,30 @@ import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; +/** + * Creates a new form and then updates it to add a description. + */ async function updateForm() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); + + // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); + + // The initial form to be created. const newForm = { info: { title: 'Creating a new form for batchUpdate in Node', }, }; + + // Create the new form. const createResponse = await formsClient.forms.create({ requestBody: newForm, }); @@ -39,7 +49,7 @@ async function updateForm() { console.log(`New formId was: ${createResponse.data.formId}`); - // Request body to add description to a Form + // Request body to add a description to the form. const update = { requests: [ { @@ -48,15 +58,19 @@ async function updateForm() { description: "Please complete this quiz based on this week's readings for class.", }, + // The updateMask specifies which fields to update. updateMask: 'description', }, }, ], }; + + // Send the batch update request to update the form. const result = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: update, }); + console.log(result.data); return result.data; } diff --git a/gmail/quickstart/index.js b/gmail/quickstart/index.js index a8acd54d..655b3521 100644 --- a/gmail/quickstart/index.js +++ b/gmail/quickstart/index.js @@ -21,19 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading Gmail labels. const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the labels in the user's account. */ async function listLabels() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Gmail API client. const gmail = google.gmail({version: 'v1', auth}); + // Get the list of labels. const result = await gmail.users.labels.list({ userId: 'me', }); @@ -43,6 +48,7 @@ async function listLabels() { return; } console.log('Labels:'); + // Print the name of each label. labels.forEach((label) => { console.log(`- ${label.name}`); }); diff --git a/meet/quickstart/index.js b/meet/quickstart/index.js index 50c57346..70aaa63b 100644 --- a/meet/quickstart/index.js +++ b/meet/quickstart/index.js @@ -21,26 +21,32 @@ import process from 'node:process'; import {SpacesServiceClient} from '@google-apps/meet'; import {authenticate} from '@google-cloud/local-auth'; +// The scope for creating a new meeting space. const SCOPES = ['https://www.googleapis.com/auth/meetings.space.created']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Creates a new meeting space. */ async function createSpace() { + // Authenticate with Google and get an authorized client. const authClient = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Meet API client. const meetClient = new SpacesServiceClient({ authClient, }); - // Construct request + + // Construct the request to create a new space. The request body is empty. const request = {}; - // Run request + // Run the request to create the space. const response = await meetClient.createSpace(request); + // Print the URL of the new meeting. console.log(`Meet URL: ${response[0].meetingUri}`); } diff --git a/people/quickstart/index.js b/people/quickstart/index.js index 3b3f0b9d..9a23806f 100644 --- a/people/quickstart/index.js +++ b/people/quickstart/index.js @@ -21,19 +21,24 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading contacts. const SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Print the display name if available for 10 connections. + * Prints the display names of the first 10 connections. */ async function listConnectionNames() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new People API client. const service = google.people({version: 'v1', auth}); + // Get the list of connections. const result = await service.people.connections.list({ resourceName: 'people/me', pageSize: 10, @@ -45,6 +50,7 @@ async function listConnectionNames() { return; } console.log('Connections:'); + // Print the display name of each connection. connections.forEach((person) => { if (person.names && person.names.length > 0) { console.log(person.names[0].displayName); diff --git a/sheets/quickstart/index.js b/sheets/quickstart/index.js index 302f2e20..0ac5b133 100644 --- a/sheets/quickstart/index.js +++ b/sheets/quickstart/index.js @@ -21,7 +21,9 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading spreadsheets. const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** @@ -29,11 +31,15 @@ const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit */ async function listMajors() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + + // Create a new Sheets API client. const sheets = google.sheets({version: 'v4', auth}); + // Get the values from the spreadsheet. const result = await sheets.spreadsheets.values.get({ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', range: 'Class Data!A2:E', @@ -44,6 +50,7 @@ async function listMajors() { return; } console.log('Name, Major:'); + // Print the name and major of each student. rows.forEach((row) => { // Print columns A and E, which correspond to indices 0 and 4. console.log(`${row[0]}, ${row[4]}`); diff --git a/sheets/snippets/sheets_append_values.js b/sheets/snippets/sheets_append_values.js index 24143157..a29fbd9d 100644 --- a/sheets/snippets/sheets_append_values.js +++ b/sheets/snippets/sheets_append_values.js @@ -19,19 +19,23 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Appends values in a Spreadsheet. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} range The range of values to append. - * @param {object} valueInputOption Value input options. - * @param {(string[])[]} _values A 2d array of values to append. - * @return {obj} spreadsheet information + * Appends values to a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet to update. + * @param {string} range The range of cells to append to. + * @param {string} valueInputOption How the input data should be interpreted. + * @param {(string[])[]} _values A 2D array of values to append. + * @return {Promise} The response from the append request. */ async function appendValues(spreadsheetId, range, valueInputOption, _values) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The values to append to the spreadsheet. let values = [ [ // Cell values ... @@ -41,15 +45,21 @@ async function appendValues(spreadsheetId, range, valueInputOption, _values) { // [START_EXCLUDE silent] values = _values; // [END_EXCLUDE] + + // Create the request body. const resource = { values, }; + + // Append the values to the spreadsheet. const result = await service.spreadsheets.values.append({ spreadsheetId, range, valueInputOption, resource, }); + + // Log the number of appended cells. console.log(`${result.data.updates.updatedCells} cells appended.`); return result; } diff --git a/sheets/snippets/sheets_batch_get_values.js b/sheets/snippets/sheets_batch_get_values.js index e1c585ed..6dba9506 100644 --- a/sheets/snippets/sheets_batch_get_values.js +++ b/sheets/snippets/sheets_batch_get_values.js @@ -19,22 +19,29 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Batch gets cell values from a Spreadsheet. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} _ranges The mock sheet range. - * @return {obj} spreadsheet information + * Batch gets cell values from a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet. + * @param {string} _ranges The ranges of cells to retrieve. + * @return {obj} The spreadsheet information. */ async function batchGetValues(spreadsheetId, _ranges) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The ranges to retrieve from the spreadsheet. let ranges = [ - // Range names ... + // e.g., 'Sheet1!A1:C5', + // 'Sheet2!A1:B3' ]; // [START_EXCLUDE silent] ranges = _ranges; + // [END_EXCLUDE silent] + // Get the values from the specified ranges. const result = await service.spreadsheets.values.batchGet({ spreadsheetId, ranges, diff --git a/sheets/snippets/sheets_batch_update.js b/sheets/snippets/sheets_batch_update.js index 3f1bec9d..c51077ca 100644 --- a/sheets/snippets/sheets_batch_update.js +++ b/sheets/snippets/sheets_batch_update.js @@ -19,21 +19,27 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Updates the Spreadsheet title. Finds and replaces a string in the sheets. - * @param {string} spreadsheetId The Spreadsheet to update - * @param {string} title The new Spreadsheet title - * @param {string} find The text to find - * @param {string} replacement The text to replace - * @return {Promise} A promise that resolves to the response from the batch update. + * Performs a batch update on a spreadsheet. + * Updates the spreadsheet title and finds and replaces a string. + * @param {string} spreadsheetId The ID of the spreadsheet to update. + * @param {string} title The new title for the spreadsheet. + * @param {string} find The string to find. + * @param {string} replacement The string to replace the found string with. + * @return {Promise} The response from the batch update. */ async function batchUpdate(spreadsheetId, title, find, replacement) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // Create a list of requests to be executed in the batch update. const requests = []; - // Change the spreadsheet's title. + + // Request to change the spreadsheet's title. requests.push({ updateSpreadsheetProperties: { properties: { @@ -42,7 +48,8 @@ async function batchUpdate(spreadsheetId, title, find, replacement) { fields: 'title', }, }); - // Find and replace text. + + // Request to find and replace text. requests.push({ findReplace: { find, @@ -50,12 +57,19 @@ async function batchUpdate(spreadsheetId, title, find, replacement) { allSheets: true, }, }); - // Add additional requests (operations) ... + + // Add more requests here if needed. + + // Create the batch update request. const batchUpdateRequest = {requests}; + + // Execute the batch update request. const response = await service.spreadsheets.batchUpdate({ spreadsheetId, requestBody: batchUpdateRequest, }); + + // Get the response from the find and replace request and log the number of occurrences. const findReplaceResponse = response.data.replies[1].findReplace; console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`); return response; diff --git a/sheets/snippets/sheets_batch_update_values.js b/sheets/snippets/sheets_batch_update_values.js index 412f5df0..d4f87a43 100644 --- a/sheets/snippets/sheets_batch_update_values.js +++ b/sheets/snippets/sheets_batch_update_values.js @@ -19,12 +19,12 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Batch Updates values in a Spreadsheet. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} range The range of values to update. - * @param {object} valueInputOption Value update options. - * @param {(string[])[]} _values A 2d array of values to update. - * @return {obj} spreadsheet information + * Batch updates values in a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet to update. + * @param {string} range The range of cells to update. + * @param {string} valueInputOption How the input data should be interpreted. + * @param {(string[])[]} _values A 2D array of values to update. + * @return {Promise} The response from the batch update. */ async function batchUpdateValues( spreadsheetId, @@ -32,11 +32,15 @@ async function batchUpdateValues( valueInputOption, _values, ) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The values to update in the spreadsheet. let values = [ [ // Cell values ... @@ -46,21 +50,30 @@ async function batchUpdateValues( // [START_EXCLUDE silent] values = _values; // [END_EXCLUDE] + + // The data to be updated. const data = [ { range, values, }, ]; - // Additional ranges to update ... + + // Additional ranges to update can be added here. + + // Create the batch update request. const resource = { data, valueInputOption, }; + + // Execute the batch update request. const result = await service.spreadsheets.values.batchUpdate({ spreadsheetId, resource, }); + + // Log the number of updated cells. console.log('%d cells updated.', result.data.totalUpdatedCells); return result; } diff --git a/sheets/snippets/sheets_conditional_formatting.js b/sheets/snippets/sheets_conditional_formatting.js index ff21fc67..07fdf4d8 100644 --- a/sheets/snippets/sheets_conditional_formatting.js +++ b/sheets/snippets/sheets_conditional_formatting.js @@ -19,16 +19,20 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Conditionally formats a Spreadsheet. - * @param {string} spreadsheetId A Spreadsheet ID. - * @return {obj} spreadsheet information + * Applies conditional formatting to a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet. + * @return {Promise} The response from the batch update. */ async function conditionalFormatting(spreadsheetId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The range to apply the conditional formatting to. const myRange = { sheetId: 0, startRowIndex: 1, @@ -36,6 +40,8 @@ async function conditionalFormatting(spreadsheetId) { startColumnIndex: 0, endColumnIndex: 4, }; + + // The requests to apply conditional formatting. const requests = [ { addConditionalFormatRule: { @@ -72,9 +78,13 @@ async function conditionalFormatting(spreadsheetId) { }, }, ]; + + // Create the batch update request. const resource = { requests, }; + + // Execute the batch update request. const response = await service.spreadsheets.batchUpdate({ spreadsheetId, resource, diff --git a/sheets/snippets/sheets_create.js b/sheets/snippets/sheets_create.js index 14ea3695..d8f5285b 100644 --- a/sheets/snippets/sheets_create.js +++ b/sheets/snippets/sheets_create.js @@ -19,25 +19,33 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Creates a Google Spreadsheet. - * @param {string} title The spreadsheet's title. + * Creates a new Google Spreadsheet. + * @param {string} title The title of the new spreadsheet. * @return {string} The ID of the created spreadsheet. */ async function create(title) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The resource body for creating a new spreadsheet. const resource = { properties: { title, }, }; + + // Create the new spreadsheet. const spreadsheet = await service.spreadsheets.create({ resource, fields: 'spreadsheetId', }); + + // Log the ID of the new spreadsheet. console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`); return spreadsheet.data.spreadsheetId; } diff --git a/sheets/snippets/sheets_get_values.js b/sheets/snippets/sheets_get_values.js index 2539afc7..d50170ea 100644 --- a/sheets/snippets/sheets_get_values.js +++ b/sheets/snippets/sheets_get_values.js @@ -19,17 +19,20 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Gets cell values from a Spreadsheet. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} range The sheet range. - * @return {Promise} A promise that resolves to the response from the get. + * Gets cell values from a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet. + * @param {string} range The range of cells to retrieve. + * @return {Promise} The response from the get request. */ async function getValues(spreadsheetId, range) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + // Get the values from the specified range. const result = await service.spreadsheets.values.get({ spreadsheetId, range, diff --git a/sheets/snippets/sheets_pivot_table.js b/sheets/snippets/sheets_pivot_table.js index 6b3da1d9..05fb7a56 100644 --- a/sheets/snippets/sheets_pivot_table.js +++ b/sheets/snippets/sheets_pivot_table.js @@ -19,17 +19,20 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Adds a pivot table to a spreadsheet. - * @param {string} spreadsheetId The Spreadsheet to add the pivot table to. - * @return {Promise} A promise that resolves to the response from the batch update. + * Creates a pivot table in a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet. + * @return {Promise} The response from the batch update. */ async function pivotTable(spreadsheetId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); const service = google.sheets({version: 'v4', auth}); - // Create two sheets for our pivot table + + // Create two new sheets for the pivot table. + // One for the source data and one for the pivot table itself. let requests = [ { addSheet: {}, @@ -43,9 +46,12 @@ async function pivotTable(spreadsheetId) { spreadsheetId, resource, }); + + // Get the IDs of the newly created sheets. const sourceSheetId = response.data.replies[0].addSheet.properties.sheetId; const targetSheetId = response.data.replies[1].addSheet.properties.sheetId; + // Add a pivot table to the new sheet. requests = [ { updateCells: { @@ -53,6 +59,7 @@ async function pivotTable(spreadsheetId) { values: [ { pivotTable: { + // The source data for the pivot table. source: { sheetId: sourceSheetId, startRowIndex: 0, @@ -60,6 +67,7 @@ async function pivotTable(spreadsheetId) { endRowIndex: 20, endColumnIndex: 7, }, + // The rows of the pivot table. rows: [ { sourceColumnOffset: 1, @@ -67,6 +75,7 @@ async function pivotTable(spreadsheetId) { sortOrder: 'ASCENDING', }, ], + // The columns of the pivot table. columns: [ { sourceColumnOffset: 4, @@ -74,6 +83,7 @@ async function pivotTable(spreadsheetId) { showTotals: true, }, ], + // The values to display in the pivot table. values: [ { summarizeFunction: 'COUNTA', @@ -85,6 +95,7 @@ async function pivotTable(spreadsheetId) { }, ], }, + // The location to place the pivot table. start: { sheetId: targetSheetId, rowIndex: 0, @@ -97,6 +108,8 @@ async function pivotTable(spreadsheetId) { resource = { requests, }; + + // Send the batch update request to create the pivot table. response = service.spreadsheets.batchUpdate({ spreadsheetId, resource, diff --git a/sheets/snippets/sheets_update_values.js b/sheets/snippets/sheets_update_values.js index 62a79d7a..6456e7ec 100644 --- a/sheets/snippets/sheets_update_values.js +++ b/sheets/snippets/sheets_update_values.js @@ -19,19 +19,23 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Updates values in a Spreadsheet. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} range The range of values to update. - * @param {object} valueInputOption Value update options. - * @param {(string[])[]} _values A 2d array of values to update. - * @return {obj} spreadsheet information + * Updates values in a spreadsheet. + * @param {string} spreadsheetId The ID of the spreadsheet to update. + * @param {string} range The range of cells to update. + * @param {string} valueInputOption How the input data should be interpreted. + * @param {(string[])[]} _values A 2D array of values to update. + * @return {Promise} The response from the update request. */ async function updateValues(spreadsheetId, range, valueInputOption, _values) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); + // Create a new Sheets API client. const service = google.sheets({version: 'v4', auth}); + + // The values to update in the spreadsheet. let values = [ [ // Cell values ... @@ -41,15 +45,21 @@ async function updateValues(spreadsheetId, range, valueInputOption, _values) { // [START_EXCLUDE silent] values = _values; // [END_EXCLUDE] + + // Create the request body. const resource = { values, }; + + // Update the values in the spreadsheet. const result = await service.spreadsheets.values.update({ spreadsheetId, range, valueInputOption, resource, }); + + // Log the number of updated cells. console.log('%d cells updated.', result.data.updatedCells); return result; } diff --git a/slides/quickstart/index.js b/slides/quickstart/index.js index 53c842a7..62168a4b 100644 --- a/slides/quickstart/index.js +++ b/slides/quickstart/index.js @@ -21,20 +21,25 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading presentations. const SCOPES = ['https://www.googleapis.com/auth/presentations.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Prints the number of slides and elements in a sample presentation: - * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit + * Prints the number of slides and elements in a sample presentation. + * @see https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit */ async function listSlides() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Slides API client. const slidesApi = google.slides({version: 'v1', auth}); + // Get the presentation data. const result = await slidesApi.presentations.get({ presentationId: '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc', }); @@ -43,7 +48,9 @@ async function listSlides() { console.log('No slides found.'); return; } + // Print the number of slides. console.log('The presentation contains %s slides:', slides.length); + // Print the number of elements in each slide. (result.data.slides ?? []).forEach((slide, i) => { console.log( `- Slide #${i + 1} contains ${ diff --git a/slides/snippets/slides_copy_presentation.js b/slides/snippets/slides_copy_presentation.js index f5dcf1bd..a05f4b2c 100644 --- a/slides/snippets/slides_copy_presentation.js +++ b/slides/snippets/slides_copy_presentation.js @@ -19,23 +19,32 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Copies a Google Slide presentation. - * @param {string} presentationId The presentation to copy. - * @param {string} copyTitle The new title. + * Copies a presentation. + * @param {string} presentationId The ID of the presentation to copy. + * @param {string} copyTitle The title for the copied presentation. + * @return {Promise} The response from the copy request. */ async function copyPresentation(presentationId, copyTitle) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); + // Create a new Drive API client. const service = google.drive({version: 'v2', auth}); + + // The request to copy the presentation. const request = { name: copyTitle, }; + + // Copy the presentation. const driveResponse = await service.files.copy({ fileId: presentationId, requestBody: request, }); + + // Log the ID of the copied presentation. const presentationCopyId = driveResponse.data.id; console.log(`Created copied presentation with ID: ${presentationCopyId}`); return driveResponse; diff --git a/slides/snippets/slides_create_bulleted_text.js b/slides/snippets/slides_create_bulleted_text.js index aa7e7abf..628633f1 100644 --- a/slides/snippets/slides_create_bulleted_text.js +++ b/slides/snippets/slides_create_bulleted_text.js @@ -19,18 +19,21 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Creates bulleted text for a presentation. - * @param {string} presentationId The presentation ID. - * @param {string} shapeId The shape ID to add bulleted text to. + * Adds bullet points to text in a shape. + * @param {string} presentationId The ID of the presentation. + * @param {string} shapeId The ID of the shape to add bullets to. + * @return {Promise} The response from the batch update. */ async function createBulletedText(presentationId, shapeId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); - // Add arrow-diamond-disc bullets to all text in the shape. + // The request to add bullet points to the text. const requests = [ { createParagraphBullets: { @@ -42,6 +45,8 @@ async function createBulletedText(presentationId, shapeId) { }, }, ]; + + // Execute the batch update request. const batchUpdateResponse = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/slides/snippets/slides_create_image.js b/slides/snippets/slides_create_image.js index 355a1bc9..28b4d52e 100644 --- a/slides/snippets/slides_create_image.js +++ b/slides/snippets/slides_create_image.js @@ -19,26 +19,34 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Adds an image to a presentation. - * @param {string} presentationId The presentation ID. - * @param {string} pageId The presentation page ID. + * Adds an image to a slide in a presentation. + * @param {string} presentationId The ID of the presentation. + * @param {string} pageId The ID of the page to add the image to. + * @return {Promise} The response from the batch update. */ async function createImage(presentationId, pageId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + // The URL of the image to add. const imageUrl = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'; - // Create a new image, using the supplied object ID, with content - // downloaded from imageUrl. + + // The ID to use for the new image. const imageId = 'MyImage_01'; + + // The size of the new image in English Metric Units (EMUs). const emu4M = { magnitude: 4000000, unit: 'EMU', }; + + // The request to create a new image. const requests = [ { createImage: { @@ -61,6 +69,8 @@ async function createImage(presentationId, pageId) { }, }, ]; + + // Execute the batch update request to create the image. const response = await service.presentations.batchUpdate({ presentationId, requestBody: {requests}, diff --git a/slides/snippets/slides_create_presentation.js b/slides/snippets/slides_create_presentation.js index 9837b566..29da99ab 100644 --- a/slides/snippets/slides_create_presentation.js +++ b/slides/snippets/slides_create_presentation.js @@ -19,18 +19,25 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Creates a Google Slide presentation. - * @param {string} title The presentation title. + * Creates a new Google Slides presentation. + * @param {string} title The title for the new presentation. + * @return {Promise} The created presentation. */ async function createPresentation(title) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + + // Create a new presentation with the specified title. const presentation = await service.presentations.create({ title, }); + + // Log the ID of the new presentation. console.log( `Created presentation with ID: ${presentation.data.presentationId}`, ); diff --git a/slides/snippets/slides_create_sheets_chart.js b/slides/snippets/slides_create_sheets_chart.js index daa42841..101861dd 100644 --- a/slides/snippets/slides_create_sheets_chart.js +++ b/slides/snippets/slides_create_sheets_chart.js @@ -19,11 +19,12 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Embeds a Sheets chart onto a page in a presentation. - * @param {string} presentationId The presentation ID. - * @param {string} pageId The page ID. - * @param {string} spreadsheetId The spreadsheet ID. - * @param {string} sheetChartId The sheet's chart ID. + * Embeds a Sheets chart into a presentation. + * @param {string} presentationId The ID of the presentation. + * @param {string} pageId The ID of the page to embed the chart on. + * @param {string} spreadsheetId The ID of the spreadsheet containing the chart. + * @param {string} sheetChartId The ID of the chart in the spreadsheet. + * @return {Promise} The response from the batch update. */ async function createSheetsChart( presentationId, @@ -31,26 +32,31 @@ async function createSheetsChart( spreadsheetId, sheetChartId, ) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); - // Embed a Sheets chart (indicated by the spreadsheetId and sheetChartId) - // onto a page in the presentation. Setting the linking mode as "LINKED" - // allows the chart to be refreshed if the Sheets version is updated. + // The size of the embedded chart, in English Metric Units (EMUs). const emu4M = { magnitude: 4000000, unit: 'EMU', }; + + // The ID to use for the embedded chart. const presentationChartId = 'MyEmbeddedChart'; + + // The request to create a new chart. const requests = [ { createSheetsChart: { objectId: presentationChartId, spreadsheetId, chartId: sheetChartId, + // Linking mode allows the chart to be updated if the source sheet changes. linkingMode: 'LINKED', elementProperties: { pageObjectId: pageId, @@ -69,6 +75,8 @@ async function createSheetsChart( }, }, ]; + + // Execute the batch update request to create the chart. const batchUpdateResponse = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/slides/snippets/slides_create_slide.js b/slides/snippets/slides_create_slide.js index fc3e2d21..553ddb91 100644 --- a/slides/snippets/slides_create_slide.js +++ b/slides/snippets/slides_create_slide.js @@ -20,15 +20,20 @@ import {google} from 'googleapis'; /** * Creates a new slide in a presentation. - * @param {string} presentationId The presentation ID. + * @param {string} presentationId The ID of the presentation. * @param {string} pageId The object ID for the new slide. + * @return {Promise} The response from the batch update. */ async function createSlide(presentationId, pageId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + + // The request to create a new slide. const requests = [ { createSlide: { @@ -40,6 +45,8 @@ async function createSlide(presentationId, pageId) { }, }, ]; + + // Execute the batch update request to create the slide. const result = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/slides/snippets/slides_create_textbox_with_text.js b/slides/snippets/slides_create_textbox_with_text.js index d2130dfe..2388c30b 100644 --- a/slides/snippets/slides_create_textbox_with_text.js +++ b/slides/snippets/slides_create_textbox_with_text.js @@ -19,21 +19,30 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Adds a textbox with text to a slide. - * @param {string} presentationId The presentation ID. - * @param {string} pageId The page to add the textbox to. + * Creates a textbox with text on a slide. + * @param {string} presentationId The ID of the presentation. + * @param {string} pageId The ID of the page to add the textbox to. + * @return {Promise} The response from the batch update. */ async function createTextboxWithText(presentationId, pageId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + + // The ID to use for the new textbox. const elementId = 'MyTextBox_01'; + + // The size of the new textbox, in points. const pt350 = { magnitude: 350, unit: 'PT', }; + + // The requests to create a textbox and add text to it. const requests = [ { createShape: { @@ -55,7 +64,7 @@ async function createTextboxWithText(presentationId, pageId) { }, }, }, - // Insert text into the box, using the supplied element ID. + // Insert text into the new textbox. { insertText: { objectId: elementId, @@ -64,6 +73,8 @@ async function createTextboxWithText(presentationId, pageId) { }, }, ]; + + // Execute the batch update request. const createTextboxWithTextResponse = await service.presentations.batchUpdate( { presentationId, diff --git a/slides/snippets/slides_image_merging.js b/slides/snippets/slides_image_merging.js index 3f1d349a..87b7675e 100644 --- a/slides/snippets/slides_image_merging.js +++ b/slides/snippets/slides_image_merging.js @@ -19,12 +19,14 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Add an image to a template presentation. - * @param {string} templatePresentationId The template presentation ID. - * @param {string} imageUrl The image URL - * @param {string} customerName A customer name used for the title + * Replaces shapes in a presentation with images. + * @param {string} templatePresentationId The ID of the template presentation. + * @param {string} imageUrl The URL of the image to use. + * @param {string} customerName The name of the customer for the new presentation title. + * @return {Promise} The response from the batch update. */ async function imageMerging(templatePresentationId, imageUrl, customerName) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: [ 'https://www.googleapis.com/auth/presentations', @@ -32,12 +34,14 @@ async function imageMerging(templatePresentationId, imageUrl, customerName) { ], }); + // Create new clients for Slides and Drive APIs. const slidesService = google.slides({version: 'v1', auth}); const driveService = google.drive({version: 'v2', auth}); + const logoUrl = imageUrl; const customerGraphicUrl = imageUrl; - // Duplicate the template presentation using the Drive API. + // Duplicate the template presentation. const copyTitle = `${customerName} presentation`; const driveResponse = await driveService.files.copy({ fileId: templatePresentationId, @@ -47,7 +51,7 @@ async function imageMerging(templatePresentationId, imageUrl, customerName) { }); const presentationCopyId = driveResponse.data.id; - // Create the image merge (replaceAllShapesWithImage) requests. + // Create the image merge requests. const requests = [ { replaceAllShapesWithImage: { @@ -71,13 +75,15 @@ async function imageMerging(templatePresentationId, imageUrl, customerName) { }, ]; - // Execute the requests for this presentation. + // Execute the requests to replace the shapes with images. const batchUpdateResponse = await slidesService.presentations.batchUpdate({ presentationId: presentationCopyId, requestBody: { requests, }, }); + + // Count the total number of replacements made. let numReplacements = 0; for (let i = 0; i < batchUpdateResponse.data.replies.length; ++i) { numReplacements += diff --git a/slides/snippets/slides_refresh_sheets_chart.js b/slides/snippets/slides_refresh_sheets_chart.js index b0644268..24a67807 100644 --- a/slides/snippets/slides_refresh_sheets_chart.js +++ b/slides/snippets/slides_refresh_sheets_chart.js @@ -19,17 +19,21 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Refreshes an embedded sheet chart. - * @param {string} presentationId The presentation ID. - * @param {string} presentationChartId The presentation's chart ID. + * Refreshes an embedded Sheets chart in a presentation. + * @param {string} presentationId The ID of the presentation. + * @param {string} presentationChartId The ID of the chart to refresh. + * @return {Promise} The response from the batch update. */ async function refreshSheetsChart(presentationId, presentationChartId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + // The request to refresh the chart. const requests = [ { refreshSheetsChart: { @@ -37,6 +41,8 @@ async function refreshSheetsChart(presentationId, presentationChartId) { }, }, ]; + + // Execute the batch update request to refresh the chart. const batchUpdateResponse = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/slides/snippets/slides_simple_text_replace.js b/slides/snippets/slides_simple_text_replace.js index dd523143..2a333255 100644 --- a/slides/snippets/slides_simple_text_replace.js +++ b/slides/snippets/slides_simple_text_replace.js @@ -19,18 +19,22 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Replaces text in the provided shape ID. - * @param {string} presentationId The presentation ID. - * @param {string} shapeId The shape ID to delete existing text and insert new text into. - * @param {string} replacementText The new replacement text. + * Replaces all text in a shape with new text. + * @param {string} presentationId The ID of the presentation. + * @param {string} shapeId The ID of the shape to update. + * @param {string} replacementText The text to replace with. + * @return {Promise} The response from the batch update. */ async function simpleTextReplace(presentationId, shapeId, replacementText) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); - // Remove existing text in the shape, then insert new text. + + // The requests to delete the existing text and insert the new text. const requests = [ { deleteText: { @@ -48,6 +52,8 @@ async function simpleTextReplace(presentationId, shapeId, replacementText) { }, }, ]; + + // Execute the batch update request. const batchUpdateResponse = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/slides/snippets/slides_text_merging.js b/slides/snippets/slides_text_merging.js index 392704f7..53a158c0 100644 --- a/slides/snippets/slides_text_merging.js +++ b/slides/snippets/slides_text_merging.js @@ -19,11 +19,12 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Adds data from a spreadsheet to a template presentation. - * @param {string} templatePresentationId The template presentation ID. - * @param {string} dataSpreadsheetId The data spreadsheet ID. + * Merges text from a spreadsheet into a template presentation. + * @param {string} templatePresentationId The ID of the template presentation. + * @param {string} dataSpreadsheetId The ID of the spreadsheet containing the data. */ async function textMerging(templatePresentationId, dataSpreadsheetId) { + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: [ 'https://www.googleapis.com/auth/presentations', @@ -32,12 +33,12 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { ], }); + // Create new clients for Slides, Sheets, and Drive APIs. const slidesService = google.slides({version: 'v1', auth}); const sheetsService = google.sheets({version: 'v4', auth}); const driveService = google.drive({version: 'v2', auth}); - // Use the Sheets API to load data, one record per row. - const responses = []; + // Use the Sheets API to load data from the spreadsheet. const dataRangeNotation = 'A2:M6'; const sheetsResponse = await sheetsService.spreadsheets.values.get({ spreadsheetId: dataSpreadsheetId, @@ -45,26 +46,26 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { }); const values = sheetsResponse.data.values; - // For each record, create a new merged presentation. + // For each row of data, create a new presentation by copying the template + // and replacing the placeholder text with the data. for (let i = 0; i < values.length; ++i) { const row = values[i]; - const customerName = row[2]; // name in column 3 - const caseDescription = row[5]; // case description in column 6 - const totalPortfolio = row[11]; // total portfolio in column 12 + const customerName = row[2]; // Column 3 + const caseDescription = row[5]; // Column 6 + const totalPortfolio = row[11]; // Column 12 - // Duplicate the template presentation using the Drive API. + // Duplicate the template presentation. const title = `${customerName} presentation`; - const driveResponse = await driveService.files.copy({ fileId: templatePresentationId, requestBody: { title, }, }); - const presentationCopyId = driveResponse.data.id; - // Create the text merge (replaceAllText) requests for this presentation. - requests = [ + + // Create the text merge requests for this presentation. + const requests = [ { replaceAllText: { containsText: { @@ -93,7 +94,8 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { }, }, ]; - // Execute the requests for this presentation. + + // Execute the requests to replace the placeholder text. const batchUpdateResponse = await slidesService.presentations.batchUpdate({ presentationId: presentationCopyId, requestBody: { @@ -101,9 +103,7 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { }, }); const result = batchUpdateResponse.data; - // [START_EXCLUDE silent] - responses.push(result.replies); - // [END_EXCLUDE] + // Count the total number of replacements made. let numReplacements = 0; for (let i = 0; i < result.replies.length; ++i) { @@ -112,7 +112,7 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { console.log( `Created presentation for ${customerName} with ID: ${presentationCopyId}`, ); - console.log(`Replaced ${numReplacements} text instances`); + console.log(`Replaced ${numReplacements} text instances.`); } } // [END slides_text_merging] diff --git a/slides/snippets/slides_text_style_update.js b/slides/snippets/slides_text_style_update.js index 6b92c7c7..47d4c519 100644 --- a/slides/snippets/slides_text_style_update.js +++ b/slides/snippets/slides_text_style_update.js @@ -19,21 +19,23 @@ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; /** - * Updates text style for a specific presentation's shape ID. - * @param {string} presentationId The presentation ID. - * @param {string} shapeId The shape ID. + * Updates the text style of a shape in a presentation. + * @param {string} presentationId The ID of the presentation. + * @param {string} shapeId The ID of the shape to update. + * @return {Promise} The response from the batch update. */ async function textStyleUpdate(presentationId, shapeId) { - // Update the text style so that the first 5 characters are bolded - // and italicized, the next 5 are displayed in blue 14 pt Times - // New Roman font, and the next 5 are hyperlinked. + // Authenticate with Google and get an authorized client. const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/presentations', }); + // Create a new Slides API client. const service = google.slides({version: 'v1', auth}); + // The requests to update the text style. const requests = [ + // Bold and italicize the first 5 characters. { updateTextStyle: { objectId: shapeId, @@ -49,6 +51,7 @@ async function textStyleUpdate(presentationId, shapeId) { fields: 'bold,italic', }, }, + // Set the next 5 characters to 14pt Times New Roman, and blue. { updateTextStyle: { objectId: shapeId, @@ -76,6 +79,7 @@ async function textStyleUpdate(presentationId, shapeId) { fields: 'foregroundColor,fontFamily,fontSize', }, }, + // Hyperlink the next 5 characters. { updateTextStyle: { objectId: shapeId, @@ -93,6 +97,8 @@ async function textStyleUpdate(presentationId, shapeId) { }, }, ]; + + // Execute the batch update request. const batchUpdateResponse = await service.presentations.batchUpdate({ presentationId, requestBody: { diff --git a/tasks/quickstart/index.js b/tasks/quickstart/index.js index 6cac8f83..d4824c4a 100644 --- a/tasks/quickstart/index.js +++ b/tasks/quickstart/index.js @@ -21,25 +21,31 @@ import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; +// The scope for reading tasks. const SCOPES = ['https://www.googleapis.com/auth/tasks.readonly']; +// The path to the credentials file. const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** * Lists the user's first 10 task lists. */ async function listTaskLists() { + // Authenticate with Google and get an authorized client. const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); + // Create a new Tasks API client. const service = google.tasks({version: 'v1', auth}); + // Get the list of task lists. const result = await service.tasklists.list({ maxResults: 10, }); const taskLists = result.data.items; if (taskLists?.length) { console.log('Task lists:'); + // Print the title and ID of each task list. taskLists.forEach((taskList) => { console.log(`${taskList.title} (${taskList.id})`); }); From ef23ca1027e633d4fd7417f0a5c97a0b803ab64c Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Mon, 15 Sep 2025 15:39:22 -0600 Subject: [PATCH 2/2] fix: improve permission insertion error handling in shareFile function --- .../drive_v2/file snippets/share_file.js | 19 +++++++++---------- .../drive_v3/file_snippets/share_file.js | 8 ++++---- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/drive/snippets/drive_v2/file snippets/share_file.js b/drive/snippets/drive_v2/file snippets/share_file.js index 094aee40..8cf8f8c5 100644 --- a/drive/snippets/drive_v2/file snippets/share_file.js +++ b/drive/snippets/drive_v2/file snippets/share_file.js @@ -54,18 +54,17 @@ async function shareFile(fileId, targetUser, targetDomain) { // Note: The client library does not currently support batch requests for permissions. // When possible, use batch requests to insert multiple permissions on the same item. for (const permission of permissions) { - try { - // Insert the permission. - const result = await service.permissions.insert({ - requestBody: permission, - fileId, - fields: 'id', - }); + // Insert the permission. + const result = await service.permissions.insert({ + requestBody: permission, + fileId, + fields: 'id', + }); + if (result.data.id) { permissionIds.push(result.data.id); console.log(`Inserted permission id: ${result.data.id}`); - } catch (err) { - // TODO(developer): Handle failed permissions - console.error(err); + } else { + throw new Error('Failed to create permission'); } } return permissionIds; diff --git a/drive/snippets/drive_v3/file_snippets/share_file.js b/drive/snippets/drive_v3/file_snippets/share_file.js index fa6b5023..a4bfffc2 100644 --- a/drive/snippets/drive_v3/file_snippets/share_file.js +++ b/drive/snippets/drive_v3/file_snippets/share_file.js @@ -61,12 +61,12 @@ async function shareFile(fileId, targetUserEmail, targetDomainName) { fields: 'id', }); - if (!result.data.id) { + if (result.data.id) { + permissionIds.push(result.data.id); + console.log(`Inserted permission id: ${result.data.id}`); + } else { throw new Error('Failed to create permission'); } - - permissionIds.push(result.data.id); - console.log(`Inserted permission id: ${result.data.id}`); } return permissionIds; }