diff --git a/adminSDK/directory/index.js b/adminSDK/directory/index.js index d140a83b..5aaf7c36 100644 --- a/adminSDK/directory/index.js +++ b/adminSDK/directory/index.js @@ -13,89 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START admin_sdk_directory_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the first 10 users in the domain. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listUsers() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the first 10 users in the domain. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listUsers(auth) { const service = google.admin({version: 'directory_v1', auth}); - const res = await service.users.list({ + const result = await service.users.list({ customer: 'my_customer', maxResults: 10, orderBy: 'email', }); - const users = res.data.users; + const users = result.data.users; if (!users || users.length === 0) { console.log('No users found.'); return; @@ -103,9 +48,10 @@ async function listUsers(auth) { console.log('Users:'); users.forEach((user) => { - console.log(`${user.primaryEmail} (${user.name.fullName})`); + console.log(`${user.primaryEmail} (${user.name?.fullName})`); }); } -authorize().then(listUsers).catch(console.error); +await listUsers(); + // [END admin_sdk_directory_quickstart] diff --git a/adminSDK/directory/package.json b/adminSDK/directory/package.json index 1f291193..ead564bd 100644 --- a/adminSDK/directory/package.json +++ b/adminSDK/directory/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/adminSDK/directory/tsconfig.json b/adminSDK/directory/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/adminSDK/directory/tsconfig.json +++ b/adminSDK/directory/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/adminSDK/reports/index.js b/adminSDK/reports/index.js index fcceb8e1..62e42d3b 100644 --- a/adminSDK/reports/index.js +++ b/adminSDK/reports/index.js @@ -13,88 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START admin_sdk_reports_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the last 10 login events for the domain. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listLoginEvents() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} - -/** - * Lists the last 10 login events for the domain. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listLoginEvents(auth) { const service = google.admin({version: 'reports_v1', auth}); - const res = await service.activities.list({ + const result = await service.activities.list({ userKey: 'all', applicationName: 'login', maxResults: 10, }); - const activities = res.data.items; + const activities = result.data.items; if (!activities || activities.length === 0) { console.log('No logins found.'); return; @@ -103,10 +47,10 @@ async function listLoginEvents(auth) { console.log('Logins:'); activities.forEach((activity) => { console.log( - `${activity.id.time}: ${activity.actor.email} (${activity.events[0].name})`, + `${activity.id?.time}: ${activity.actor?.email} (${activity.events?.[0]?.name})`, ); }); } -authorize().then(listLoginEvents).catch(console.error); +await listLoginEvents(); // [END admin_sdk_reports_quickstart] diff --git a/adminSDK/reports/package.json b/adminSDK/reports/package.json index a5b72785..4f29fd9f 100644 --- a/adminSDK/reports/package.json +++ b/adminSDK/reports/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/adminSDK/reports/tsconfig.json b/adminSDK/reports/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/adminSDK/reports/tsconfig.json +++ b/adminSDK/reports/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/adminSDK/reseller/index.js b/adminSDK/reseller/index.js index 2abc4e80..cef5ed83 100644 --- a/adminSDK/reseller/index.js +++ b/adminSDK/reseller/index.js @@ -13,86 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START admin_sdk_reseller_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/apps.order']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the first 10 subscriptions you manage. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listSubscriptions() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the first 10 subscriptions you manage. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listSubscriptions(auth) { const service = google.reseller({version: 'v1', auth}); - const res = await service.subscriptions.list({ + const result = await service.subscriptions.list({ maxResults: 10, }); - const subscriptions = res.data.subscriptions; + const subscriptions = result.data.subscriptions; if (!subscriptions || subscriptions.length === 0) { console.log('No subscriptions found.'); return; @@ -100,8 +45,10 @@ async function listSubscriptions(auth) { console.log('Subscriptions:'); subscriptions.forEach(({customerId, skuId, plan}) => { - console.log(`${customerId} (${skuId}, ${plan.planName})`); + console.log(`${customerId} (${skuId}, ${plan?.planName})`); }); } -authorize().then(listSubscriptions).catch(console.error); + +await listSubscriptions(); + // [END admin_sdk_reseller_quickstart] diff --git a/adminSDK/reseller/package.json b/adminSDK/reseller/package.json index f89a751b..8a273b2a 100644 --- a/adminSDK/reseller/package.json +++ b/adminSDK/reseller/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/adminSDK/reseller/tsconfig.json b/adminSDK/reseller/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/adminSDK/reseller/tsconfig.json +++ b/adminSDK/reseller/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/apps-script/execute/index.js b/apps-script/execute/index.js index 07a8ad8d..7fb5fb3a 100644 --- a/apps-script/execute/index.js +++ b/apps-script/execute/index.js @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START apps_script_api_execute] + +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. - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; async function callAppsScript() { const scriptId = '1xGOh6wCm7hlIVSVPKm0y_dL-YqetspS5DEVmMzaxd_6AAvI-_u8DSgBT'; @@ -30,51 +32,47 @@ async function callAppsScript() { scopes: 'https://www.googleapis.com/auth/drive', }); 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: { + function: 'getFoldersUnderRoot', + }, + scriptId, + }); - try { - // Make the API request. The request object is included here as 'resource'. - const resp = await script.scripts.run({ - auth: auth, - resource: { - function: 'getFoldersUnderRoot', - }, - scriptId: scriptId, - }); - if (resp.error) { - // The API executed, but the script returned an error. + 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. - const error = resp.error.details[0]; - console.log('Script error message: ' + error.errorMessage); - console.log('Script error stacktrace:'); + // 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. + const error = resp.data.error.details[0]; - if (error.scriptStackTraceElements) { - // There may not be a stacktrace if the script didn't start executing. - for (let i = 0; i < error.scriptStackTraceElements.length; i++) { - const trace = error.scriptStackTraceElements[i]; - console.log('\t%s: %s', trace.function, trace.lineNumber); - } + 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. + 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 will depend upon what the Apps Script + // function returns. Here, the function returns an Apps Script Object + // with String keys and values, and so the result is treated as a + // Node.js object (folderSet). + const folderSet = resp.data.response ?? {}; + if (Object.keys(folderSet).length === 0) { + console.log('No folders returned!'); } else { - // The structure of the result will depend upon what the Apps Script - // function returns. Here, the function returns an Apps Script Object - // with String keys and values, and so the result is treated as a - // Node.js object (folderSet). - const folderSet = resp.response.result; - if (Object.keys(folderSet).length == 0) { - console.log('No folders returned!'); - } else { - console.log('Folders under your root folder:'); - Object.keys(folderSet).forEach(function(id) { - console.log('\t%s (%s)', folderSet[id], id); - }); - } + console.log('Folders under your root folder:'); + Object.keys(folderSet).forEach((id) => { + console.log('\t%s (%s)', folderSet[id], id); + }); } - } catch (err) { - // TODO(developer) - Handle error - throw err; } } // [END apps_script_api_execute] diff --git a/apps-script/execute/package.json b/apps-script/execute/package.json index bfeb0a1a..15397bb7 100644 --- a/apps-script/execute/package.json +++ b/apps-script/execute/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/apps-script/execute/tsconfig.json b/apps-script/execute/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/apps-script/execute/tsconfig.json +++ b/apps-script/execute/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/apps-script/quickstart/index.js b/apps-script/quickstart/index.js index 215614ac..bc7126d3 100644 --- a/apps-script/quickstart/index.js +++ b/apps-script/quickstart/index.js @@ -13,90 +13,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START apps_script_api_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/script.projects']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Creates a new script project, upload a file, and log the script's URL. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function callAppsScript() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Creates a new script project, upload a file, and log the script's URL. - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function callAppsScript(auth) { const script = google.script({version: 'v1', auth}); - let res = await script.projects.create({ - resource: { + const project = await script.projects.create({ + requestBody: { title: 'My Script', }, }); - res = await script.projects.updateContent({ - scriptId: res.data.scriptId, + + if (!project.data.scriptId) { + throw new Error('Failed to create project'); + } + + await script.projects.updateContent({ + scriptId: project.data.scriptId, auth, - resource: { + requestBody: { files: [ { name: 'hello', @@ -112,8 +63,8 @@ async function callAppsScript(auth) { ], }, }); - console.log(`https://script.google.com/d/${res.data.scriptId}/edit`); + console.log(`https://script.google.com/d/${project.data.scriptId}/edit`); } -authorize().then(callAppsScript).catch(console.error); +await callAppsScript(); // [END apps_script_api_quickstart] diff --git a/apps-script/quickstart/package.json b/apps-script/quickstart/package.json index fe1de2aa..d724b6b7 100644 --- a/apps-script/quickstart/package.json +++ b/apps-script/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/apps-script/quickstart/tsconfig.json b/apps-script/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/apps-script/quickstart/tsconfig.json +++ b/apps-script/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/calendar/quickstart/index.js b/calendar/quickstart/index.js index 403e4493..249ba965 100644 --- a/calendar/quickstart/index.js +++ b/calendar/quickstart/index.js @@ -13,99 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START calendar_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the next 10 events on the user's primary calendar. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listEvents() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the next 10 events on the user's primary calendar. - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listEvents(auth) { const calendar = google.calendar({version: 'v3', auth}); - const res = await calendar.events.list({ + const result = await calendar.events.list({ calendarId: 'primary', timeMin: new Date().toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime', }); - const events = res.data.items; + const events = result.data.items; if (!events || events.length === 0) { console.log('No upcoming events found.'); return; } console.log('Upcoming 10 events:'); - events.map((event, i) => { - const start = event.start.dateTime || event.start.date; + + for (const event of events) { + const start = event.start?.dateTime ?? event.start?.date; console.log(`${start} - ${event.summary}`); - }); + } } -authorize().then(listEvents).catch(console.error); +await listEvents(); // [END calendar_quickstart] diff --git a/calendar/quickstart/package.json b/calendar/quickstart/package.json index e58c1ecd..3200610e 100644 --- a/calendar/quickstart/package.json +++ b/calendar/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/calendar/quickstart/tsconfig.json b/calendar/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/calendar/quickstart/tsconfig.json +++ b/calendar/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/chat/client-libraries/cloud/authentication-utils.js b/chat/client-libraries/cloud/authentication-utils.js index c32c910f..c496b840 100644 --- a/chat/client-libraries/cloud/authentication-utils.js +++ b/chat/client-libraries/cloud/authentication-utils.js @@ -16,13 +16,13 @@ // [START chat_authentication_utils] -import http from 'http'; -import url from 'url'; +import {readFile} from 'node:fs/promises'; +import http from 'node:http'; +import url from 'node:url'; +import {ChatServiceClient} from '@google-apps/chat'; +import {OAuth2Client} from 'google-auth-library'; import open from 'open'; import destroyer from 'server-destroy'; -import {readFile} from 'fs/promises'; -import {OAuth2Client} from 'google-auth-library'; -import {ChatServiceClient} from '@google-apps/chat'; // Application authentication const SERVICE_ACCOUNT_FILE = './service_account.json'; @@ -31,7 +31,7 @@ const APP_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.bot']; // User authentication const CLIENT_SECRETS_FILE = './credentials.json'; const CLIENT_SECRETS = JSON.parse( - await readFile(new URL(CLIENT_SECRETS_FILE, import.meta.url)), + await readFile(new URL(CLIENT_SECRETS_FILE, import.meta.url), 'utf8'), ).web; /** @@ -59,7 +59,7 @@ export async function createClientWithUserCredentials(scopes) { // https://developers.google.com/workspace/chat/authenticate-authorize-chat-user return new ChatServiceClient({ authClient: await getAuthenticatedUserOAuth2Client(scopes), - scopes: scopes, + scopes, }); } diff --git a/chat/client-libraries/cloud/create-custom-emoji-user-cred.js b/chat/client-libraries/cloud/create-custom-emoji-user-cred.js index 35b2d480..78dc77b0 100644 --- a/chat/client-libraries/cloud/create-custom-emoji-user-cred.js +++ b/chat/client-libraries/cloud/create-custom-emoji-user-cred.js @@ -13,19 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// It may require modifications to work in your environment. // [START chat_create_custom_emoji_user_cred] +import fs from 'node:fs'; import {createClientWithUserCredentials} from './authentication-utils.js'; -import fs from 'fs'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.customemojis']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.customemojis', +]; // This sample shows how to create custom emoji with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // TODO(developer) Replace FILENAME here. const filename = 'FILENAME'; @@ -39,7 +42,7 @@ async function main() { emoji_name: 'EMOJI_NAME', payload: { file_content: fileContent, - filename: filename, + filename, }, }, }; @@ -51,6 +54,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_custom_emoji_user_cred] diff --git a/chat/client-libraries/cloud/create-membership-user-cred-for-app.js b/chat/client-libraries/cloud/create-membership-user-cred-for-app.js index 6388f54f..5f47992e 100644 --- a/chat/client-libraries/cloud/create-membership-user-cred-for-app.js +++ b/chat/client-libraries/cloud/create-membership-user-cred-for-app.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.app']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships.app', +]; // This sample shows how to create membership with app credential for an app async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -47,6 +51,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_membership_user_cred_for_app] diff --git a/chat/client-libraries/cloud/create-membership-user-cred-for-group.js b/chat/client-libraries/cloud/create-membership-user-cred-for-group.js index a3a85751..1e80d41e 100644 --- a/chat/client-libraries/cloud/create-membership-user-cred-for-group.js +++ b/chat/client-libraries/cloud/create-membership-user-cred-for-group.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships', +]; // This sample shows how to create membership with user credential for a group async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -45,6 +49,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_membership_user_cred_for_group] diff --git a/chat/client-libraries/cloud/create-membership-user-cred.js b/chat/client-libraries/cloud/create-membership-user-cred.js index f978a9c9..199ffaa0 100644 --- a/chat/client-libraries/cloud/create-membership-user-cred.js +++ b/chat/client-libraries/cloud/create-membership-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships', +]; // This sample shows how to create membership with user credential for a human user async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -47,6 +51,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_membership_user_cred] diff --git a/chat/client-libraries/cloud/create-message-app-cred.js b/chat/client-libraries/cloud/create-message-app-cred.js index 03451fda..85ebc019 100644 --- a/chat/client-libraries/cloud/create-message-app-cred.js +++ b/chat/client-libraries/cloud/create-message-app-cred.js @@ -29,47 +29,85 @@ async function main() { // Replace SPACE_NAME here. parent: 'spaces/SPACE_NAME', message: { - text: '👋🌎 Hello world! I created this message by calling ' + - 'the Chat API\'s `messages.create()` method.', - cardsV2: [{card: { - header: { - title: 'About this message', - imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg', + text: + '👋🌎 Hello world! I created this message by calling ' + + 'the Chat API\'s `messages.create()` method.', + cardsV2: [ + { + card: { + header: { + title: 'About this message', + imageUrl: + 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg', + }, + sections: [ + { + header: 'Contents', + widgets: [ + { + textParagraph: { + text: + '🔡 Text which can include ' + + 'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.', + }, + }, + { + textParagraph: { + text: + '🖼️ A card to display visual elements' + + 'and request information such as text 🔤, ' + + 'dates and times 📅, and selections ☑️.', + }, + }, + { + textParagraph: { + text: + '👉🔘 An accessory widget which adds ' + + 'a button to the bottom of a message.', + }, + }, + ], + }, + { + header: 'What\'s next', + collapsible: true, + widgets: [ + { + textParagraph: { + text: '❤️ Add a reaction.', + }, + }, + { + textParagraph: { + text: + '🔄 Update ' + + 'or ❌ delete ' + + 'the message.', + }, + }, + ], + }, + ], + }, }, - sections: [{ - header: 'Contents', - widgets: [{textParagraph: { - text: '🔡 Text which can include ' + - 'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.', - }}, {textParagraph: { - text: '🖼️ A card to display visual elements' + - 'and request information such as text 🔤, ' + - 'dates and times 📅, and selections ☑️.', - }}, {textParagraph: { - text: '👉🔘 An accessory widget which adds ' + - 'a button to the bottom of a message.', - }}, - ]}, { - header: 'What\'s next', - collapsible: true, - widgets: [{textParagraph: { - text: '❤️ Add a reaction.', - }}, {textParagraph: { - text: '🔄 Update ' + - 'or ❌ delete ' + - 'the message.', + ], + accessoryWidgets: [ + { + buttonList: { + buttons: [ + { + text: 'View documentation', + icon: {materialIcon: {name: 'link'}}, + onClick: { + openLink: { + url: 'https://developers.google.com/workspace/chat/create-messages', + }, + }, + }, + ], }, - }], }, - ], - }}], - accessoryWidgets: [{buttonList: {buttons: [{ - text: 'View documentation', - icon: {materialIcon: {name: 'link'}}, - onClick: {openLink: { - url: 'https://developers.google.com/workspace/chat/create-messages', - }}, - }]}}], + ], }, }; @@ -80,6 +118,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_app_cred] diff --git a/chat/client-libraries/cloud/create-message-user-cred-at-mention.js b/chat/client-libraries/cloud/create-message-user-cred-at-mention.js index b23887a9..f52f8997 100644 --- a/chat/client-libraries/cloud/create-message-user-cred-at-mention.js +++ b/chat/client-libraries/cloud/create-message-user-cred-at-mention.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential with a user mention async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -44,6 +48,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred_at_mention] diff --git a/chat/client-libraries/cloud/create-message-user-cred-message-id.js b/chat/client-libraries/cloud/create-message-user-cred-message-id.js index 53792ce2..5eadba80 100644 --- a/chat/client-libraries/cloud/create-message-user-cred-message-id.js +++ b/chat/client-libraries/cloud/create-message-user-cred-message-id.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential with message id async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -43,6 +47,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred_message_id] diff --git a/chat/client-libraries/cloud/create-message-user-cred-request-id.js b/chat/client-libraries/cloud/create-message-user-cred-request-id.js index 67565990..d139a6a4 100644 --- a/chat/client-libraries/cloud/create-message-user-cred-request-id.js +++ b/chat/client-libraries/cloud/create-message-user-cred-request-id.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential with request id async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -43,6 +47,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred_request_id] diff --git a/chat/client-libraries/cloud/create-message-user-cred-thread-key.js b/chat/client-libraries/cloud/create-message-user-cred-thread-key.js index 0d82de19..77cd3630 100644 --- a/chat/client-libraries/cloud/create-message-user-cred-thread-key.js +++ b/chat/client-libraries/cloud/create-message-user-cred-thread-key.js @@ -17,15 +17,19 @@ // [START chat_create_message_user_cred_thread_key] -import {createClientWithUserCredentials} from './authentication-utils.js'; import {protos} from '@google-apps/chat'; +import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential with thread key async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -33,7 +37,9 @@ async function main() { parent: 'spaces/SPACE_NAME', // Creates the message as a reply to the thread specified by thread_key // If it fails, the message starts a new thread instead - messageReplyOption: protos.google.chat.v1.CreateMessageRequest.MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD, + messageReplyOption: + protos.google.chat.v1.CreateMessageRequest.MessageReplyOption + .REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD, message: { text: 'Hello with user credential!', thread: { @@ -51,6 +57,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred_thread_key] diff --git a/chat/client-libraries/cloud/create-message-user-cred-thread-name.js b/chat/client-libraries/cloud/create-message-user-cred-thread-name.js index 9e86c297..bd9d27d2 100644 --- a/chat/client-libraries/cloud/create-message-user-cred-thread-name.js +++ b/chat/client-libraries/cloud/create-message-user-cred-thread-name.js @@ -17,15 +17,19 @@ // [START chat_create_message_user_cred_thread_name] -import {createClientWithUserCredentials} from './authentication-utils.js'; import {protos} from '@google-apps/chat'; +import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential with thread name async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -33,7 +37,9 @@ async function main() { parent: 'spaces/SPACE_NAME', // Creates the message as a reply to the thread specified by thread.name // If it fails, the message starts a new thread instead - messageReplyOption: protos.google.chat.v1.CreateMessageRequest.MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD, + messageReplyOption: + protos.google.chat.v1.CreateMessageRequest.MessageReplyOption + .REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD, message: { text: 'Hello with user credential!', thread: { @@ -51,6 +57,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred_thread_name] diff --git a/chat/client-libraries/cloud/create-message-user-cred.js b/chat/client-libraries/cloud/create-message-user-cred.js index 08083472..1a56479d 100644 --- a/chat/client-libraries/cloud/create-message-user-cred.js +++ b/chat/client-libraries/cloud/create-message-user-cred.js @@ -19,26 +19,31 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.create', +]; // This sample shows how to create message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { // Replace SPACE_NAME here. parent: 'spaces/SPACE_NAME', message: { - text: '👋🌎 Hello world!' + - 'Text messages can contain things like:\n\n' + - '* Hyperlinks 🔗\n' + - '* Emojis 😄🎉\n' + - '* Mentions of other Chat users `@` \n\n' + - 'For details, see the ' + - '.', + text: + '👋🌎 Hello world!' + + 'Text messages can contain things like:\n\n' + + '* Hyperlinks 🔗\n' + + '* Emojis 😄🎉\n' + + '* Mentions of other Chat users `@` \n\n' + + 'For details, see the ' + + '.', }, }; @@ -49,6 +54,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_message_user_cred] diff --git a/chat/client-libraries/cloud/create-reaction-user-cred.js b/chat/client-libraries/cloud/create-reaction-user-cred.js index 557adc82..7a5da922 100644 --- a/chat/client-libraries/cloud/create-reaction-user-cred.js +++ b/chat/client-libraries/cloud/create-reaction-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.reactions.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.reactions.create', +]; // This sample shows how to create reaction to a message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -43,6 +47,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_reaction_user_cred] diff --git a/chat/client-libraries/cloud/create-space-user-cred.js b/chat/client-libraries/cloud/create-space-user-cred.js index fd4404b7..d820bce6 100644 --- a/chat/client-libraries/cloud/create-space-user-cred.js +++ b/chat/client-libraries/cloud/create-space-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.spaces.create', +]; // This sample shows how to create a named space with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -42,6 +46,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_create_space_user_cred] diff --git a/chat/client-libraries/cloud/delete-custom-emoji-user-cred.js b/chat/client-libraries/cloud/delete-custom-emoji-user-cred.js index c64396cf..dac9303f 100644 --- a/chat/client-libraries/cloud/delete-custom-emoji-user-cred.js +++ b/chat/client-libraries/cloud/delete-custom-emoji-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.customemojis']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.customemojis', +]; // This sample shows how to delete a custom emoji with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_custom_emoji_user_cred] diff --git a/chat/client-libraries/cloud/delete-membership-user-cred.js b/chat/client-libraries/cloud/delete-membership-user-cred.js index 45a3195d..456ad254 100644 --- a/chat/client-libraries/cloud/delete-membership-user-cred.js +++ b/chat/client-libraries/cloud/delete-membership-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships', +]; // This sample shows how to delete a membership of type HUMAN with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_membership_user_cred] diff --git a/chat/client-libraries/cloud/delete-message-app-cred.js b/chat/client-libraries/cloud/delete-message-app-cred.js index 7dc6d707..6461f606 100644 --- a/chat/client-libraries/cloud/delete-message-app-cred.js +++ b/chat/client-libraries/cloud/delete-message-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_message_app_cred] diff --git a/chat/client-libraries/cloud/delete-message-user-cred.js b/chat/client-libraries/cloud/delete-message-user-cred.js index 74a8f7d9..de10c80f 100644 --- a/chat/client-libraries/cloud/delete-message-user-cred.js +++ b/chat/client-libraries/cloud/delete-message-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages', +]; // This sample shows how to delete a message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_message_user_cred] diff --git a/chat/client-libraries/cloud/delete-reaction-user-cred.js b/chat/client-libraries/cloud/delete-reaction-user-cred.js index 6de2421d..43784853 100644 --- a/chat/client-libraries/cloud/delete-reaction-user-cred.js +++ b/chat/client-libraries/cloud/delete-reaction-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.reactions']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.reactions', +]; // This sample shows how to delete a reaction to a message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_reaction_user_cred] diff --git a/chat/client-libraries/cloud/delete-space-user-cred.js b/chat/client-libraries/cloud/delete-space-user-cred.js index 0cc849fd..32f2b1fc 100644 --- a/chat/client-libraries/cloud/delete-space-user-cred.js +++ b/chat/client-libraries/cloud/delete-space-user-cred.js @@ -24,7 +24,9 @@ const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.delete']; // This sample shows how to delete a space with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +41,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_delete_space_user_cred] diff --git a/chat/client-libraries/cloud/find-dm-space-app-cred.js b/chat/client-libraries/cloud/find-dm-space-app-cred.js index 812c58fd..7ac58ada 100644 --- a/chat/client-libraries/cloud/find-dm-space-app-cred.js +++ b/chat/client-libraries/cloud/find-dm-space-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_find_dm_space_app_cred] diff --git a/chat/client-libraries/cloud/find-dm-space-user-cred.js b/chat/client-libraries/cloud/find-dm-space-user-cred.js index 7197ada0..b60fefd1 100644 --- a/chat/client-libraries/cloud/find-dm-space-user-cred.js +++ b/chat/client-libraries/cloud/find-dm-space-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.spaces.readonly', +]; // This sample shows how to find a Direct Message space with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_find_dm_space_user_cred] diff --git a/chat/client-libraries/cloud/get-attachment-app-cred.js b/chat/client-libraries/cloud/get-attachment-app-cred.js index 52c474ef..cc23d7bf 100644 --- a/chat/client-libraries/cloud/get-attachment-app-cred.js +++ b/chat/client-libraries/cloud/get-attachment-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_attachment_app_cred] diff --git a/chat/client-libraries/cloud/get-custom-emoji-user-cred.js b/chat/client-libraries/cloud/get-custom-emoji-user-cred.js index c6f2a630..2aa583c9 100644 --- a/chat/client-libraries/cloud/get-custom-emoji-user-cred.js +++ b/chat/client-libraries/cloud/get-custom-emoji-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.customemojis']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.customemojis', +]; // This sample shows how to get custom emoji with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_custom_emoji_user_cred] diff --git a/chat/client-libraries/cloud/get-membership-app-cred.js b/chat/client-libraries/cloud/get-membership-app-cred.js index 98855d4f..09d85aa3 100644 --- a/chat/client-libraries/cloud/get-membership-app-cred.js +++ b/chat/client-libraries/cloud/get-membership-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_membership_app_cred] diff --git a/chat/client-libraries/cloud/get-membership-user-cred.js b/chat/client-libraries/cloud/get-membership-user-cred.js index f6bc87e0..7ab4aeb8 100644 --- a/chat/client-libraries/cloud/get-membership-user-cred.js +++ b/chat/client-libraries/cloud/get-membership-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships.readonly', +]; // This sample shows how to get membership with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_membership_user_cred] diff --git a/chat/client-libraries/cloud/get-message-app-cred.js b/chat/client-libraries/cloud/get-message-app-cred.js index e0c682ce..e30f9b10 100644 --- a/chat/client-libraries/cloud/get-message-app-cred.js +++ b/chat/client-libraries/cloud/get-message-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_message_app_cred] diff --git a/chat/client-libraries/cloud/get-message-user-cred.js b/chat/client-libraries/cloud/get-message-user-cred.js index c7c8af0a..c123aab0 100644 --- a/chat/client-libraries/cloud/get-message-user-cred.js +++ b/chat/client-libraries/cloud/get-message-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.readonly', +]; // This sample shows how to get message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_message_user_cred] diff --git a/chat/client-libraries/cloud/get-space-app-cred.js b/chat/client-libraries/cloud/get-space-app-cred.js index 4f2ab6b2..d5ee5119 100644 --- a/chat/client-libraries/cloud/get-space-app-cred.js +++ b/chat/client-libraries/cloud/get-space-app-cred.js @@ -37,6 +37,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_space_app_cred] diff --git a/chat/client-libraries/cloud/get-space-event-user-cred.js b/chat/client-libraries/cloud/get-space-event-user-cred.js index 3e699975..bd1c6bbf 100644 --- a/chat/client-libraries/cloud/get-space-event-user-cred.js +++ b/chat/client-libraries/cloud/get-space-event-user-cred.js @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// It may require modifications to work in your environment. // [START chat_get_space_event_user_cred] @@ -25,7 +24,9 @@ const USER_AUTH_OAUTH_SCOPES = ['SCOPE_NAME']; // This sample shows how to get space event with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -40,6 +41,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_space_event_user_cred] diff --git a/chat/client-libraries/cloud/get-space-notification-setting-user-cred.js b/chat/client-libraries/cloud/get-space-notification-setting-user-cred.js index ea51e48a..acad0e31 100644 --- a/chat/client-libraries/cloud/get-space-notification-setting-user-cred.js +++ b/chat/client-libraries/cloud/get-space-notification-setting-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.spacesettings']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.users.spacesettings', +]; // This sample shows how to get the space notification setting for the calling user async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s), replace the SPACE_NAME with an actual space name. const request = { @@ -38,6 +42,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_space_notification_setting_user_cred] diff --git a/chat/client-libraries/cloud/get-space-read-state-user-cred.js b/chat/client-libraries/cloud/get-space-read-state-user-cred.js index 5228cbc4..dbbe9860 100644 --- a/chat/client-libraries/cloud/get-space-read-state-user-cred.js +++ b/chat/client-libraries/cloud/get-space-read-state-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.readstate.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +]; // This sample shows how to get the space read state for the calling user async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_space_read_state_user_cred] diff --git a/chat/client-libraries/cloud/get-space-user-cred.js b/chat/client-libraries/cloud/get-space-user-cred.js index 121af34e..d1fe1ff4 100644 --- a/chat/client-libraries/cloud/get-space-user-cred.js +++ b/chat/client-libraries/cloud/get-space-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.spaces.readonly', +]; // This sample shows how to get space with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_space_user_cred] diff --git a/chat/client-libraries/cloud/get-thread-read-state-user-cred.js b/chat/client-libraries/cloud/get-thread-read-state-user-cred.js index 86ec394e..8a05f8c2 100644 --- a/chat/client-libraries/cloud/get-thread-read-state-user-cred.js +++ b/chat/client-libraries/cloud/get-thread-read-state-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.readstate.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.users.readstate.readonly', +]; // This sample shows how to get the thread read state for a space and calling user async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -39,6 +43,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_get_thread_read_state_user_cred] diff --git a/chat/client-libraries/cloud/list-custom-emojis-user-cred.js b/chat/client-libraries/cloud/list-custom-emojis-user-cred.js index 06b1ab83..dcddd38d 100644 --- a/chat/client-libraries/cloud/list-custom-emojis-user-cred.js +++ b/chat/client-libraries/cloud/list-custom-emojis-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.customemojis']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.customemojis', +]; // This sample shows how to get custom emoji with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -42,6 +46,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_custom_emojis_user_cred] diff --git a/chat/client-libraries/cloud/list-memberships-app-cred.js b/chat/client-libraries/cloud/list-memberships-app-cred.js index b6061582..89c8664f 100644 --- a/chat/client-libraries/cloud/list-memberships-app-cred.js +++ b/chat/client-libraries/cloud/list-memberships-app-cred.js @@ -43,6 +43,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_memberships_app_cred] diff --git a/chat/client-libraries/cloud/list-memberships-user-cred.js b/chat/client-libraries/cloud/list-memberships-user-cred.js index 1d6e716c..d416d819 100644 --- a/chat/client-libraries/cloud/list-memberships-user-cred.js +++ b/chat/client-libraries/cloud/list-memberships-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships.readonly', +]; // This sample shows how to list memberships with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -45,6 +49,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_memberships_user_cred] diff --git a/chat/client-libraries/cloud/list-messages-user-cred.js b/chat/client-libraries/cloud/list-messages-user-cred.js index 3e333112..4387e670 100644 --- a/chat/client-libraries/cloud/list-messages-user-cred.js +++ b/chat/client-libraries/cloud/list-messages-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.readonly', +]; // This sample shows how to list messages with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -42,6 +46,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_messages_user_cred] diff --git a/chat/client-libraries/cloud/list-reactions-user-cred.js b/chat/client-libraries/cloud/list-reactions-user-cred.js index 02fda27c..f778c939 100644 --- a/chat/client-libraries/cloud/list-reactions-user-cred.js +++ b/chat/client-libraries/cloud/list-reactions-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.reactions.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages.reactions.readonly', +]; // This sample shows how to list reactions to a message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -42,6 +46,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_reactions_user_cred] diff --git a/chat/client-libraries/cloud/list-space-events-user-cred.js b/chat/client-libraries/cloud/list-space-events-user-cred.js index e224ba1e..806bd344 100644 --- a/chat/client-libraries/cloud/list-space-events-user-cred.js +++ b/chat/client-libraries/cloud/list-space-events-user-cred.js @@ -28,14 +28,17 @@ const USER_AUTH_OAUTH_SCOPES = [ // This sample shows how to list space events with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { // Replace SPACE_NAME here parent: 'spaces/SPACE_NAME', // A required filter. Filters events about new memberships and messages - filter: 'eventTypes:"google.workspace.chat.membership.v1.created" OR eventTypes:"google.workspace.chat.message.v1.created"', + filter: + 'eventTypes:"google.workspace.chat.membership.v1.created" OR eventTypes:"google.workspace.chat.message.v1.created"', }; // Make the request @@ -48,6 +51,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_space_events_user_cred] diff --git a/chat/client-libraries/cloud/list-spaces-app-cred.js b/chat/client-libraries/cloud/list-spaces-app-cred.js index 3abbcd1c..e4c66984 100644 --- a/chat/client-libraries/cloud/list-spaces-app-cred.js +++ b/chat/client-libraries/cloud/list-spaces-app-cred.js @@ -40,6 +40,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_spaces_app_cred] diff --git a/chat/client-libraries/cloud/list-spaces-user-cred.js b/chat/client-libraries/cloud/list-spaces-user-cred.js index c017874d..141c193e 100644 --- a/chat/client-libraries/cloud/list-spaces-user-cred.js +++ b/chat/client-libraries/cloud/list-spaces-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.spaces.readonly', +]; // This sample shows how to list spaces with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -42,6 +46,6 @@ async function main() { } } -main().catch(console.error); +await main(); // [END chat_list_spaces_user_cred] diff --git a/chat/client-libraries/cloud/package.json b/chat/client-libraries/cloud/package.json index 1b6d71f9..2b30c3b4 100644 --- a/chat/client-libraries/cloud/package.json +++ b/chat/client-libraries/cloud/package.json @@ -57,11 +57,11 @@ "dependencies": { "@google-apps/chat": "catalog:", "@grpc/grpc-js": "catalog:", - "google-auth-library": "catalog:", "open": "catalog:", "server-destroy": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/chat/client-libraries/cloud/set-up-space-user-cred.js b/chat/client-libraries/cloud/set-up-space-user-cred.js index b294516a..714b006a 100644 --- a/chat/client-libraries/cloud/set-up-space-user-cred.js +++ b/chat/client-libraries/cloud/set-up-space-user-cred.js @@ -19,13 +19,17 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.create']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.spaces.create', +]; // This sample shows how to set up a named space with one initial member // with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -34,13 +38,15 @@ async function main() { // Replace DISPLAY_NAME here. displayName: 'DISPLAY_NAME', }, - memberships: [{ - member: { - // Replace USER_NAME here. - name: 'users/USER_NAME', - type: 'HUMAN', + memberships: [ + { + member: { + // Replace USER_NAME here. + name: 'users/USER_NAME', + type: 'HUMAN', + }, }, - }], + ], }; // Make the request @@ -50,6 +56,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_set_up_space_user_cred] diff --git a/chat/client-libraries/cloud/tsconfig.json b/chat/client-libraries/cloud/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/chat/client-libraries/cloud/tsconfig.json +++ b/chat/client-libraries/cloud/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/chat/client-libraries/cloud/update-membership-user-cred.js b/chat/client-libraries/cloud/update-membership-user-cred.js index 5aef3fdf..3316947e 100644 --- a/chat/client-libraries/cloud/update-membership-user-cred.js +++ b/chat/client-libraries/cloud/update-membership-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.memberships', +]; // This sample shows how to update a membership with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -47,6 +51,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_membership_user_cred] diff --git a/chat/client-libraries/cloud/update-message-app-cred.js b/chat/client-libraries/cloud/update-message-app-cred.js index fd379d28..189595a4 100644 --- a/chat/client-libraries/cloud/update-message-app-cred.js +++ b/chat/client-libraries/cloud/update-message-app-cred.js @@ -30,10 +30,17 @@ async function main() { // Replace SPACE_NAME and MESSAGE_NAME here name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME', text: 'Text updated with app credential!', - cardsV2: [{card: {header: { - title: 'Card updated with app credential!', - imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg', - }}}], + cardsV2: [ + { + card: { + header: { + title: 'Card updated with app credential!', + imageUrl: + 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg', + }, + }, + }, + ], }, // The field paths to update. Separate multiple values with commas or use // `*` to update all field paths. @@ -50,6 +57,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_message_app_cred] diff --git a/chat/client-libraries/cloud/update-message-user-cred.js b/chat/client-libraries/cloud/update-message-user-cred.js index 88b61408..96c6cce9 100644 --- a/chat/client-libraries/cloud/update-message-user-cred.js +++ b/chat/client-libraries/cloud/update-message-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.messages', +]; // This sample shows how to update a message with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -48,6 +52,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_message_user_cred] diff --git a/chat/client-libraries/cloud/update-space-notification-setting-user-cred.js b/chat/client-libraries/cloud/update-space-notification-setting-user-cred.js index c68d4c93..37ab02a2 100644 --- a/chat/client-libraries/cloud/update-space-notification-setting-user-cred.js +++ b/chat/client-libraries/cloud/update-space-notification-setting-user-cred.js @@ -47,6 +47,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_space_notification_setting_user_cred] diff --git a/chat/client-libraries/cloud/update-space-read-state-user-cred.js b/chat/client-libraries/cloud/update-space-read-state-user-cred.js index 66146649..559e0f5d 100644 --- a/chat/client-libraries/cloud/update-space-read-state-user-cred.js +++ b/chat/client-libraries/cloud/update-space-read-state-user-cred.js @@ -19,12 +19,16 @@ import {createClientWithUserCredentials} from './authentication-utils.js'; -const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.users.readstate']; +const USER_AUTH_OAUTH_SCOPES = [ + 'https://www.googleapis.com/auth/chat.users.readstate', +]; // This sample shows how to update a space read state for the calling user async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const timestamp = new Date('2000-01-01').getTime(); @@ -50,6 +54,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_space_read_state_user_cred] diff --git a/chat/client-libraries/cloud/update-space-user-cred.js b/chat/client-libraries/cloud/update-space-user-cred.js index c4891b28..a376f082 100644 --- a/chat/client-libraries/cloud/update-space-user-cred.js +++ b/chat/client-libraries/cloud/update-space-user-cred.js @@ -24,7 +24,9 @@ const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces']; // This sample shows how to update a space with user credential async function main() { // Create a client - const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES); + const chatClient = await createClientWithUserCredentials( + USER_AUTH_OAUTH_SCOPES, + ); // Initialize request argument(s) const request = { @@ -48,6 +50,6 @@ async function main() { console.log(response); } -main().catch(console.error); +await main(); // [END chat_update_space_user_cred] diff --git a/chat/quickstart/index.js b/chat/quickstart/index.js index 1b10b255..34ff6142 100644 --- a/chat/quickstart/index.js +++ b/chat/quickstart/index.js @@ -16,85 +16,26 @@ // [START chat_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; -import {authenticate} from '@google-cloud/local-auth'; +import path from 'node:path'; +import process from 'node:process'; import {ChatServiceClient} from '@google-apps/chat'; -import {auth} from 'google-auth-library'; +import {authenticate} from '@google-cloud/local-auth'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly']; - -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return auth.fromJSON(credentials); - } catch (err) { - console.log(err); - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * - * @return {Promise} + * Lists spaces with user credential. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listSpaces() { + const authClient = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists spaces with user credential. - * @param {OAuth2Client} authClient An authorized OAuth2 client. - */ -async function listSpaces(authClient) { // Create a client const chatClient = new ChatServiceClient({ - authClient: authClient, + authClient, scopes: SCOPES, }); @@ -114,6 +55,6 @@ async function listSpaces(authClient) { } } -authorize().then(listSpaces).catch(console.error); +await listSpaces(); // [END chat_quickstart] diff --git a/chat/quickstart/package.json b/chat/quickstart/package.json index 47df5462..d78ee633 100644 --- a/chat/quickstart/package.json +++ b/chat/quickstart/package.json @@ -13,6 +13,7 @@ "@google-cloud/local-auth": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/chat/quickstart/tsconfig.json b/chat/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/chat/quickstart/tsconfig.json +++ b/chat/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/classroom/quickstart/index.js b/classroom/quickstart/index.js index a9caa633..b871287b 100644 --- a/classroom/quickstart/index.js +++ b/classroom/quickstart/index.js @@ -13,86 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START classroom_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the first 10 courses the user has access to. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listCourses() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} - -/** - * Lists the first 10 courses the user has access to. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listCourses(auth) { const classroom = google.classroom({version: 'v1', auth}); - const res = await classroom.courses.list({ + const result = await classroom.courses.list({ pageSize: 10, }); - const courses = res.data.courses; + const courses = result.data.courses; if (!courses || courses.length === 0) { console.log('No courses found.'); return; @@ -103,5 +47,5 @@ async function listCourses(auth) { }); } -authorize().then(listCourses).catch(console.error); +await listCourses(); // [END classroom_quickstart] diff --git a/classroom/quickstart/package.json b/classroom/quickstart/package.json index 5ff44a50..acdf56e8 100644 --- a/classroom/quickstart/package.json +++ b/classroom/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/classroom/quickstart/tsconfig.json b/classroom/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/classroom/quickstart/tsconfig.json +++ b/classroom/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/docs/quickstart/index.js b/docs/quickstart/index.js index 2cb4152f..de52c150 100644 --- a/docs/quickstart/index.js +++ b/docs/quickstart/index.js @@ -13,87 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START docs_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/documents.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Prints the title of a sample doc: + * https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function printDocTitle() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} - -/** - * Prints the title of a sample doc: - * https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit - * @param {google.auth.OAuth2} auth The authenticated Google OAuth 2.0 client. - */ -async function printDocTitle(auth) { const docs = google.docs({version: 'v1', auth}); - const res = await docs.documents.get({ + const result = await docs.documents.get({ documentId: '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE', }); - console.log(`The title of the document is: ${res.data.title}`); + console.log(`The title of the document is: ${result.data.title}`); } -authorize().then(printDocTitle).catch(console.error); +await printDocTitle(); + // [END docs_quickstart] diff --git a/docs/quickstart/package.json b/docs/quickstart/package.json index 48b06087..2e94a739 100644 --- a/docs/quickstart/package.json +++ b/docs/quickstart/package.json @@ -9,9 +9,11 @@ "check": "tsc --noEmit" }, "dependencies": { + "@google-cloud/local-auth": "catalog:", "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/docs/quickstart/tsconfig.json b/docs/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/docs/quickstart/tsconfig.json +++ b/docs/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/activity-v2/index.js b/drive/activity-v2/index.js index 6730d42d..6ab4ac03 100644 --- a/drive/activity-v2/index.js +++ b/drive/activity-v2/index.js @@ -13,103 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START drive_activity_v2_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/drive.activity.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the recent activity in your Google Drive. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listDriveActivity() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} - -/** - * Lists the recent activity in your Google Drive. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listDriveActivity(auth) { const service = google.driveactivity({version: 'v2', auth}); const params = { pageSize: 10, }; - const res = await service.activity.query({requestBody: params}); - const activities = res.data.activities; + const result = await service.activity.query({requestBody: params}); + const activities = result.data.activities; if (!activities || activities.length === 0) { console.log('No activity.'); return; } console.log('Recent activity:'); - activities.forEach((activity) => { - const time = getTimeInfo(activity); - const action = getActionInfo(activity.primaryActionDetail); - const actors = activity.actors.map(getActorInfo); - const targets = activity.targets.map(getTargetInfo); - console.log( - `${time}: ${truncated(actors)}, ${action}, ` + `${truncated(targets)}`, - ); - }); + + console.log(JSON.stringify(activities, null, 2)); } -authorize().then(listDriveActivity).catch(console.error); +await listDriveActivity(); // [END drive_activity_v2_quickstart] diff --git a/drive/activity-v2/package.json b/drive/activity-v2/package.json index a2362aaf..28e0729b 100644 --- a/drive/activity-v2/package.json +++ b/drive/activity-v2/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/drive/activity-v2/tsconfig.json b/drive/activity-v2/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/drive/activity-v2/tsconfig.json +++ b/drive/activity-v2/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/quickstart/index.js b/drive/quickstart/index.js index 3a31ae6a..0338e777 100644 --- a/drive/quickstart/index.js +++ b/drive/quickstart/index.js @@ -13,96 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START drive_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the names and IDs of up to 10 files. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listFiles() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the names and IDs of up to 10 files. - * @param {OAuth2Client} authClient An authorized OAuth2 client. - */ -async function listFiles(authClient) { - const drive = google.drive({version: 'v3', auth: authClient}); - const res = await drive.files.list({ + const drive = google.drive({version: 'v3', auth}); + const result = await drive.files.list({ pageSize: 10, fields: 'nextPageToken, files(id, name)', }); - const files = res.data.files; - if (files.length === 0) { + const files = result.data.files; + if (!files) { console.log('No files found.'); return; } console.log('Files:'); - files.map((file) => { + files.forEach((file) => { console.log(`${file.name} (${file.id})`); }); } -authorize().then(listFiles).catch(console.error); +await listFiles(); // [END drive_quickstart] diff --git a/drive/quickstart/package.json b/drive/quickstart/package.json index 013047e2..c0b30fab 100644 --- a/drive/quickstart/package.json +++ b/drive/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/drive/quickstart/tsconfig.json b/drive/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/drive/quickstart/tsconfig.json +++ b/drive/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} 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 07d7498a..2ded0f2d 100644 --- a/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js +++ b/drive/snippets/drive_v2/appdata_snippets/fetch_appdata_folder.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_fetch_appdata_folder] -/** - * List out application data folder and prints folder ID - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * List out application data folder and prints folder ID + */ async function fetchAppdataFolder() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,17 +30,12 @@ async function fetchAppdataFolder() { scopes: 'https://www.googleapis.com/auth/drive.appdata', }); const service = google.drive({version: 'v2', auth}); - try { - const file = await service.files.get({ - fileId: 'appDataFolder', - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.get({ + fileId: 'appDataFolder', + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 0d4e1d4f..12c2cf54 100644 --- a/drive/snippets/drive_v2/appdata_snippets/list_appdata.js +++ b/drive/snippets/drive_v2/appdata_snippets/list_appdata.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_list_appdata] -/** - * List all files inserted in the application data folder - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * List all files inserted in the application data folder + */ async function listAppdata() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,20 +30,17 @@ async function listAppdata() { scopes: 'https://www.googleapis.com/auth/drive.appdata', }); const service = google.drive({version: 'v2', auth}); - try { - const res = await service.files.list({ - spaces: 'appDataFolder', - fields: 'nextPageToken, items(id, title)', - pageSize: 100, - }); - res.data.items.forEach(function(file) { - console.log('Found file:', file.title, file.id); - }); - return res.data.items; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.files.list({ + spaces: 'appDataFolder', + fields: 'nextPageToken, items(id, title)', + maxResults: 100, + }); + + (result.data.items ?? []).forEach((file) => { + console.log('Found file:', file.title, file.id); + }); + + return result.data.items; } // [END drive_list_appdata] diff --git a/drive/snippets/drive_v2/appdata_snippets/package.json b/drive/snippets/drive_v2/appdata_snippets/package.json index 318a44da..d831ee82 100644 --- a/drive/snippets/drive_v2/appdata_snippets/package.json +++ b/drive/snippets/drive_v2/appdata_snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v2/appdata_snippets/tsconfig.json b/drive/snippets/drive_v2/appdata_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v2/appdata_snippets/tsconfig.json +++ b/drive/snippets/drive_v2/appdata_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js b/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js index 65b29b48..33d706ef 100644 --- a/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js +++ b/drive/snippets/drive_v2/appdata_snippets/upload_appdata.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_appdata] -/** - * Insert a file in the application data folder and prints file Id. - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Insert a file in the application data folder and prints file Id. + */ async function uploadAppdata() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -42,18 +43,13 @@ async function uploadAppdata() { mimeType: 'application/json', body: fs.createReadStream('files/config.json'), }; - try { - const file = await service.files.insert({ - resource: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 a64d1c8d..3418c107 100644 --- a/drive/snippets/drive_v2/change_snippets/fetch_changes.js +++ b/drive/snippets/drive_v2/change_snippets/fetch_changes.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_fetch_changes] -/** - * Retrieve the list of changes for the currently authenticated user - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Retrieve the list of changes for the currently authenticated user + */ async function fetchChanges() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -30,20 +31,15 @@ async function fetchChanges() { }); const service = google.drive({version: 'v2', auth}); let pageToken; - try { - const res = await service.changes.list({ - pageToken: pageToken, - fields: '*', - }); - // Process changes - res.data.items.forEach(function(change) { - console.log('Change found for file:', change.fileId); - }); - return res.data.items; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.changes.list({ + pageToken, + fields: '*', + }); + // Process changes + (result.data.items ?? []).forEach((change) => { + console.log('Change found for file:', change.fileId); + }); + 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 01102537..d39dda8e 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 @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [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'; +/** + * Retrieve page token for the current state of the account + */ async function fetchStartPageToken() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,14 +30,9 @@ async function fetchStartPageToken() { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); - try { - const res = await service.changes.getStartPageToken(); - console.log('Start token:', res.data.startPageToken); - return res.data.startPageToken; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.changes.getStartPageToken(); + console.log('Start token:', result.data.startPageToken); + return result.data.startPageToken; } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v2/change_snippets/package.json b/drive/snippets/drive_v2/change_snippets/package.json index 784eeb7a..b2f750ee 100644 --- a/drive/snippets/drive_v2/change_snippets/package.json +++ b/drive/snippets/drive_v2/change_snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v2/change_snippets/tsconfig.json b/drive/snippets/drive_v2/change_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v2/change_snippets/tsconfig.json +++ b/drive/snippets/drive_v2/change_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v2/drive_snippets/create_drive.js b/drive/snippets/drive_v2/drive_snippets/create_drive.js index 649749d9..ab02adb8 100644 --- a/drive/snippets/drive_v2/drive_snippets/create_drive.js +++ b/drive/snippets/drive_v2/drive_snippets/create_drive.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_drive] -/** - * Create a drive. - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; import {v4 as uuid} from 'uuid'; +/** + * Create a drive. + */ async function createDrive() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -35,18 +36,13 @@ async function createDrive() { name: 'Project resources', }; const requestId = uuid(); - try { - const Drive = await service.drives.insert({ - resource: driveMetadata, - requestId: requestId, - fields: 'id', - }); - console.log('Drive Id:', Drive.data.id); - return Drive.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const Drive = await service.drives.insert({ + requestBody: driveMetadata, + requestId, + fields: 'id', + }); + console.log('Drive Id:', Drive.data.id); + return Drive.data.id; } // [END drive_create_drive] diff --git a/drive/snippets/drive_v2/drive_snippets/package.json b/drive/snippets/drive_v2/drive_snippets/package.json index 4979dcd6..0ad77215 100644 --- a/drive/snippets/drive_v2/drive_snippets/package.json +++ b/drive/snippets/drive_v2/drive_snippets/package.json @@ -8,9 +8,14 @@ "check": "tsc --noEmit" }, "devDependencies": { + "@types/uuid": "^10.0.0", + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v2/drive_snippets/recover_drives.js b/drive/snippets/drive_v2/drive_snippets/recover_drives.js index bb29a4f8..0e495893 100644 --- a/drive/snippets/drive_v2/drive_snippets/recover_drives.js +++ b/drive/snippets/drive_v2/drive_snippets/recover_drives.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_recover_drives] -/** - * Find all shared drives without an organizer and add one. - * @param{string} userEmail user ID - * */ 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 + */ async function recoverDrives(userEmail) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -30,42 +31,33 @@ async function recoverDrives(userEmail) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); - const drives = []; + const newOrganizerPermission = { type: 'user', role: 'organizer', value: userEmail, // Example: 'user@example.com' }; - let pageToken = null; - try { - const res = await service.drives.list({ - q: 'organizerCount = 0', - fields: 'nextPageToken, items(id, name)', + const result = await service.drives.list({ + q: 'organizerCount = 0', + fields: 'nextPageToken, items(id, name)', + useDomainAdminAccess: true, + }); + + for (const drive of result.data.items ?? []) { + if (!drive.id) { + continue; + } + + console.log('Found shared drive without organizer:', drive.name, drive.id); + await service.permissions.insert({ + requestBody: newOrganizerPermission, + fileId: drive.id, useDomainAdminAccess: true, - pageToken: pageToken, + supportsAllDrives: true, + fields: 'id', }); - Array.prototype.push.apply(drives, res.data.items); - for (const drive of res.data.items) { - console.log( - 'Found shared drive without organizer:', - drive.name, - drive.id, - ); - await service.permissions.insert({ - resource: newOrganizerPermission, - fileId: drive.id, - useDomainAdminAccess: true, - supportsAllDrives: true, - fields: 'id', - }); - } - pageToken = res.nextPageToken; - } catch (err) { - // TODO(developer) - Handle error - throw err; } - return drives; } // [END drive_recover_drives] diff --git a/drive/snippets/drive_v2/drive_snippets/tsconfig.json b/drive/snippets/drive_v2/drive_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v2/drive_snippets/tsconfig.json +++ b/drive/snippets/drive_v2/drive_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v2/file snippets/create_folder.js b/drive/snippets/drive_v2/file snippets/create_folder.js index 553c78e4..776667f8 100644 --- a/drive/snippets/drive_v2/file snippets/create_folder.js +++ b/drive/snippets/drive_v2/file snippets/create_folder.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_folder] -/** - * Create a folder and prints the folder ID - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Create a folder and prints the folder ID + */ async function createFolder() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -33,17 +34,12 @@ async function createFolder() { title: 'Invoices', mimeType: 'application/vnd.google-apps.folder', }; - try { - const file = await service.files.insert({ - resource: fileMetadata, - fields: 'id', - }); - console.log('Folder Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + fields: 'id', + }); + console.log('Folder Id:', file.data.id); + 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 d3b8825c..68bb495a 100644 --- a/drive/snippets/drive_v2/file snippets/create_shortcut.js +++ b/drive/snippets/drive_v2/file snippets/create_shortcut.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_shortcut] -/** - * Create a third party shortcut - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Create a third party shortcut + */ async function createShortcut() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -33,18 +34,12 @@ async function createShortcut() { title: 'Project plan', mimeType: 'application/vnd.google-apps.drive-sdk', }; - - try { - const file = await service.files.insert({ - resource: fileMetadata, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 505c6e89..38640b8c 100644 --- a/drive/snippets/drive_v2/file snippets/download_file.js +++ b/drive/snippets/drive_v2/file snippets/download_file.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_download_file] -/** - * Downloads a file - * @param{string} fileId file ID - * @return{obj} file status - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Downloads a file + * @param{string} fileId file ID + * @return{Promise} file status + */ async function downloadFile(fileId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -31,18 +32,12 @@ async function downloadFile(fileId) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); - - try { - const file = await service.files.get({ - fileId: fileId, - alt: 'media', - }); - console.log(file.status); - return file.status; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.get({ + fileId, + alt: 'media', + }); + console.log(file.status); + return file.status; } // [END drive_download_file] diff --git a/drive/snippets/drive_v2/file snippets/export_pdf.js b/drive/snippets/drive_v2/file snippets/export_pdf.js index ebfe94bd..8694fcae 100644 --- a/drive/snippets/drive_v2/file snippets/export_pdf.js +++ b/drive/snippets/drive_v2/file snippets/export_pdf.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_export_pdf] -/** - * Download a Document file in PDF format - * @param{string} fileId file ID - * @return{obj} file status - * */ 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 + */ async function exportPdf(fileId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -31,18 +32,12 @@ async function exportPdf(fileId) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); - - try { - const result = await service.files.export({ - fileId: fileId, - mimeType: 'application/pdf', - }); - console.log(result.status); - return result; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.files.export({ + fileId, + mimeType: 'application/pdf', + }); + console.log(result.status); + return result; } // [END drive_export_pdf] 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 21ba6635..adcc62c4 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 @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_move_file_to_folder] +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{obj} file status - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - + * @return{Promise} file status + */ async function moveFileToFolder(fileId, folderId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -32,32 +33,24 @@ async function moveFileToFolder(fileId, folderId) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); + // Retrieve the existing parents to remove + const file = await service.files.get({ + fileId, + fields: 'parents', + }); - try { - // Retrieve the existing parents to remove - const file = await service.files.get({ - fileId: fileId, - fields: 'parents', - }); - - // Move the file to the new folder - const previousParents = file.data.parents - .map(function(parent) { - return parent.id; - }) - .join(','); - const files = await service.files.update({ - fileId: fileId, - addParents: folderId, - removeParents: previousParents, - fields: 'id, parents', - }); - console.log(files.status); - return files.status; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + // Move the file to the new folder + const previousParents = (file.data.parents ?? []) + .map((parent) => parent.id) + .join(','); + const files = await service.files.update({ + fileId, + addParents: folderId, + removeParents: previousParents, + fields: 'id, parents', + }); + console.log(files.status); + return files.status; } // [END drive_move_file_to_folder] diff --git a/drive/snippets/drive_v2/file snippets/package.json b/drive/snippets/drive_v2/file snippets/package.json index 9dd196ae..5a643df8 100644 --- a/drive/snippets/drive_v2/file snippets/package.json +++ b/drive/snippets/drive_v2/file snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v2/file snippets/search_file.js b/drive/snippets/drive_v2/file snippets/search_file.js index 2f8b24b1..d949bdaa 100644 --- a/drive/snippets/drive_v2/file snippets/search_file.js +++ b/drive/snippets/drive_v2/file snippets/search_file.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_search_file] -/** - * Search file in drive location - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Search file in drive location + */ async function searchFile() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,23 +30,18 @@ async function searchFile() { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); - const files = []; - const pageToken = null; - try { - const res = await service.files.list({ - q: 'mimeType=\'image/jpeg\'', - fields: 'nextPageToken, items(id, title)', - spaces: 'drive', - pageToken: pageToken, - }); - Array.prototype.push.apply(files, res.items); - res.data.items.forEach(function(file) { - console.log('Found file:', file.title, file.id); - }); - return res.data.items; - } catch (err) { - throw err; - } + + const pageToken = undefined; + const result = await service.files.list({ + q: 'mimeType=\'image/jpeg\'', + fields: 'nextPageToken, items(id, title)', + spaces: 'drive', + pageToken, + }); + (result.data.items ?? []).forEach((file) => { + console.log('Found file:', file.title, file.id); + }); + 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 7b1e41ca..3ecb26db 100644 --- a/drive/snippets/drive_v2/file snippets/share_file.js +++ b/drive/snippets/drive_v2/file snippets/share_file.js @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_share_file] +import {GoogleAuth} from 'google-auth-library'; +import {google} from 'googleapis'; + /** * Download a Document file in PDF format * @param{string} fileId file ID * @param{string} targetUser username * @param{string} targetDomain domain - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - + */ async function shareFile(fileId, targetUser, targetDomain) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -54,8 +55,8 @@ async function shareFile(fileId, targetUser, targetDomain) { for (const permission of permissions) { try { const result = await service.permissions.insert({ - resource: permission, - fileId: fileId, + requestBody: permission, + fileId, fields: 'id', }); permissionIds.push(result.data.id); diff --git a/drive/snippets/drive_v2/file snippets/touch_file.js b/drive/snippets/drive_v2/file snippets/touch_file.js index 0c2e522c..90862fa9 100644 --- a/drive/snippets/drive_v2/file snippets/touch_file.js +++ b/drive/snippets/drive_v2/file snippets/touch_file.js @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_touch_file] +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 Modified date time of the file - * @return{obj} modified timestamp - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - + * @return{Promise} modified timestamp + */ async function touchFile(fileId, timestamp) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -32,23 +33,20 @@ async function touchFile(fileId, timestamp) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v2', auth}); + const fileMetadata = { modifiedDate: new Date().toISOString(), + modifiedTime: timestamp, }; - fileMetadata.modifiedTime = timestamp; - try { - const file = await service.files.update({ - fileId: fileId, - setModifiedDate: true, - resource: fileMetadata, - fields: 'id, modifiedDate', - }); - console.log('Modified time:', file.data.modifiedDate); - return file.data.modifiedDate; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + + const file = await service.files.update({ + fileId, + setModifiedDate: true, + requestBody: fileMetadata, + fields: 'id, modifiedDate', + }); + console.log('Modified time:', file.data.modifiedDate); + return file.data.modifiedDate; } // [END drive_touch_file] diff --git a/drive/snippets/drive_v2/file snippets/tsconfig.json b/drive/snippets/drive_v2/file snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v2/file snippets/tsconfig.json +++ b/drive/snippets/drive_v2/file snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v2/file snippets/upload_basic.js b/drive/snippets/drive_v2/file snippets/upload_basic.js index 84f287be..f47d0e7c 100644 --- a/drive/snippets/drive_v2/file snippets/upload_basic.js +++ b/drive/snippets/drive_v2/file snippets/upload_basic.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_basic] -/** - * Insert new file. - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Insert new file. + */ async function uploadBasic() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -37,18 +38,13 @@ async function uploadBasic() { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; - try { - const file = await service.files.insert({ - resource: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 fcb24dc5..aaf0a98c 100644 --- a/drive/snippets/drive_v2/file snippets/upload_to_folder.js +++ b/drive/snippets/drive_v2/file snippets/upload_to_folder.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_to_folder] -/** - * Upload a file to the specified folder and prints file ID, folder ID - * @param{string} folderId folder ID - * */ -import fs from 'fs'; +import fs from 'node:fs'; 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 + */ async function uploadToFolder(folderId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -39,19 +40,13 @@ async function uploadToFolder(folderId) { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; - - try { - const file = await service.files.insert({ - resource: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 205b9794..ef47eb74 100644 --- a/drive/snippets/drive_v2/file snippets/upload_with_conversion.js +++ b/drive/snippets/drive_v2/file snippets/upload_with_conversion.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_with_conversion] -/** - * Upload file with conversion - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Upload file with conversion + */ async function uploadWithConversion() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -38,19 +39,13 @@ async function uploadWithConversion() { mimeType: 'text/csv', body: fs.createReadStream('files/report.csv'), }; - - try { - const file = await service.files.insert({ - resource: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.insert({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + return file.data.id; } // [END drive_upload_with_conversion] export {uploadWithConversion}; diff --git a/drive/snippets/drive_v2/package.json b/drive/snippets/drive_v2/package.json deleted file mode 100644 index e24b5e11..00000000 --- a/drive/snippets/drive_v2/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "drive-snippets-drive-v2", - "version": "1.0.0", - "private": true, - "license": "Apache-2.0", - "type": "module", - "scripts": { - "check": "tsc --noEmit" - }, - "devDependencies": { - "typescript": "catalog:" - }, - "engines": { - "node": ">=20" - } -} \ No newline at end of file diff --git a/drive/snippets/drive_v2/tsconfig.json b/drive/snippets/drive_v2/tsconfig.json deleted file mode 100644 index e8c3a24a..00000000 --- a/drive/snippets/drive_v2/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file 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 cced6287..3110db9a 100644 --- a/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js +++ b/drive/snippets/drive_v3/appdata_snippets/fetch_appdata_folder.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_fetch_appdata_folder] -/** - * List out application data folder and prints folder ID - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * List out application data folder and prints folder ID + */ async function fetchAppdataFolder() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,17 +30,12 @@ async function fetchAppdataFolder() { scopes: 'https://www.googleapis.com/auth/drive.appdata', }); const service = google.drive({version: 'v3', auth}); - try { - const file = await service.files.get({ - fileId: 'appDataFolder', - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.get({ + fileId: 'appDataFolder', + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 bf5632bb..079ab7d7 100644 --- a/drive/snippets/drive_v3/appdata_snippets/list_appdata.js +++ b/drive/snippets/drive_v3/appdata_snippets/list_appdata.js @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_list_appdata] -/** - * List all files inserted in the application data folder - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * List all files inserted in the application data folder + */ async function listAppdata() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,20 +30,15 @@ async function listAppdata() { scopes: 'https://www.googleapis.com/auth/drive.appdata', }); const service = google.drive({version: 'v3', auth}); - try { - const res = await service.files.list({ - spaces: 'appDataFolder', - fields: 'nextPageToken, files(id, name)', - pageSize: 100, - }); - res.data.files.forEach(function(file) { - console.log('Found file:', file.name, file.id); - }); - return res.data.files; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.files.list({ + spaces: 'appDataFolder', + fields: 'nextPageToken, files(id, name)', + pageSize: 100, + }); + (result.data.files ?? []).forEach((file) => { + console.log('Found file:', file.name, file.id); + }); + return result.data.files; } // [END drive_list_appdata] diff --git a/drive/snippets/drive_v3/appdata_snippets/package.json b/drive/snippets/drive_v3/appdata_snippets/package.json index 9e512f7d..82661140 100644 --- a/drive/snippets/drive_v3/appdata_snippets/package.json +++ b/drive/snippets/drive_v3/appdata_snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v3/appdata_snippets/tsconfig.json b/drive/snippets/drive_v3/appdata_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v3/appdata_snippets/tsconfig.json +++ b/drive/snippets/drive_v3/appdata_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js b/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js index a3136ade..58ff720d 100644 --- a/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js +++ b/drive/snippets/drive_v3/appdata_snippets/upload_appdata.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_appdata] -/** - * Insert a file in the application data folder and prints file Id - * */ +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; -import fs from 'fs'; +/** + * Insert a file in the application data folder and prints file Id + */ async function uploadAppdata() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -38,18 +39,13 @@ async function uploadAppdata() { mimeType: 'application/json', body: fs.createReadStream('files/config.json'), }; - try { - const file = await service.files.create({ - requestBody: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + 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 27f1299b..ffe025b3 100644 --- a/drive/snippets/drive_v3/change_snippets/fetch_changes.js +++ b/drive/snippets/drive_v3/change_snippets/fetch_changes.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_fetch_changes] +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 **/ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - async function fetchChanges(savedStartPageToken) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -30,23 +31,18 @@ async function fetchChanges(savedStartPageToken) { scopes: 'https://www.googleapis.com/auth/drive.readonly', }); const service = google.drive({version: 'v3', auth}); - try { - let pageToken = savedStartPageToken; - do { - const res = await service.changes.list({ - pageToken: savedStartPageToken, - fields: '*', - }); - res.data.changes.forEach((change) => { - console.log('change found for file: ', change.fileId); - }); - pageToken = res.data.newStartPageToken; - return pageToken; - } while (pageToken); - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + /** @type {string|null|undefined} */ + let pageToken = savedStartPageToken; + do { + const result = await service.changes.list({ + pageToken: savedStartPageToken, + fields: '*', + }); + (result.data.changes ?? []).forEach((change) => { + console.log('change found for file: ', change.fileId); + }); + 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 6e4603d2..fc8f6240 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_fetch_start_page_token] /** @@ -29,15 +30,10 @@ async function fetchStartPageToken() { scopes: 'https://www.googleapis.com/auth/drive.appdata', }); const service = google.drive({version: 'v3', auth}); - try { - const res = await service.changes.getStartPageToken({}); - const token = res.data.startPageToken; - console.log('start token: ', token); - return token; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const res = await service.changes.getStartPageToken({}); + const token = res.data.startPageToken; + console.log('start token: ', token); + return token; } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v3/change_snippets/package.json b/drive/snippets/drive_v3/change_snippets/package.json index 37338fe6..da290121 100644 --- a/drive/snippets/drive_v3/change_snippets/package.json +++ b/drive/snippets/drive_v3/change_snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v3/change_snippets/tsconfig.json b/drive/snippets/drive_v3/change_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v3/change_snippets/tsconfig.json +++ b/drive/snippets/drive_v3/change_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v3/drive_snippets/create_drive.js b/drive/snippets/drive_v3/drive_snippets/create_drive.js index cc54f0ab..ce846e57 100644 --- a/drive/snippets/drive_v3/drive_snippets/create_drive.js +++ b/drive/snippets/drive_v3/drive_snippets/create_drive.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_drive] -/** - * Create a drive. - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; import {v4 as uuid} from 'uuid'; +/** + * Create a drive. + */ async function createDrive() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -35,18 +36,13 @@ async function createDrive() { name: 'Project resources', }; const requestId = uuid(); - try { - const Drive = await service.drives.create({ - resource: driveMetadata, - requestId: requestId, - fields: 'id', - }); - console.log('Drive Id:', Drive.data.id); - return Drive.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const Drive = await service.drives.create({ + requestBody: driveMetadata, + requestId, + fields: 'id', + }); + console.log('Drive Id:', Drive.data.id); + return Drive.data.id; } // [END drive_create_drive] diff --git a/drive/snippets/drive_v3/drive_snippets/package.json b/drive/snippets/drive_v3/drive_snippets/package.json index 9faba91d..2d1b69cd 100644 --- a/drive/snippets/drive_v3/drive_snippets/package.json +++ b/drive/snippets/drive_v3/drive_snippets/package.json @@ -8,9 +8,14 @@ "check": "tsc --noEmit" }, "devDependencies": { + "@types/uuid": "^10.0.0", + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v3/drive_snippets/recover_drives.js b/drive/snippets/drive_v3/drive_snippets/recover_drives.js index 102d852f..0e622c78 100644 --- a/drive/snippets/drive_v3/drive_snippets/recover_drives.js +++ b/drive/snippets/drive_v3/drive_snippets/recover_drives.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_recover_drives] -/** - * Find all shared drives without an organizer and add one. - * @param{string} userEmail user ID to assign ownership to - * */ 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 + */ async function recoverDrives(userEmail) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -30,42 +31,33 @@ async function recoverDrives(userEmail) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); - const drives = []; const newOrganizerPermission = { type: 'user', role: 'organizer', emailAddress: userEmail, // Example: 'user@example.com' }; - let pageToken = null; - try { - const res = await service.drives.list({ - q: 'organizerCount = 0', - fields: 'nextPageToken, drives(id, name)', + const result = await service.drives.list({ + q: 'organizerCount = 0', + fields: 'nextPageToken, drives(id, name)', + useDomainAdminAccess: true, + }); + + for (const drive of result.data.drives ?? []) { + if (!drive.id) { + continue; + } + + console.log('Found shared drive without organizer:', drive.name, drive.id); + await service.permissions.create({ + requestBody: newOrganizerPermission, + fileId: drive.id, useDomainAdminAccess: true, - pageToken: pageToken, + supportsAllDrives: true, + fields: 'id', }); - Array.prototype.push.apply(drives, res.data.items); - for (const drive of res.data.drives) { - console.log( - 'Found shared drive without organizer:', - drive.name, - drive.id, - ); - await service.permissions.create({ - resource: newOrganizerPermission, - fileId: drive.id, - useDomainAdminAccess: true, - supportsAllDrives: true, - fields: 'id', - }); - } - pageToken = res.nextPageToken; - } catch (err) { - // TODO(developer) - Handle error - throw err; } - return drives; + return result.data.drives; } // [END drive_recover_drives] diff --git a/drive/snippets/drive_v3/drive_snippets/tsconfig.json b/drive/snippets/drive_v3/drive_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v3/drive_snippets/tsconfig.json +++ b/drive/snippets/drive_v3/drive_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v3/file_snippets/create_folder.js b/drive/snippets/drive_v3/file_snippets/create_folder.js index 99c76e2b..6864d640 100644 --- a/drive/snippets/drive_v3/file_snippets/create_folder.js +++ b/drive/snippets/drive_v3/file_snippets/create_folder.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_folder] -/** - * Create a folder and prints the folder ID - * @return{obj} folder Id - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Create a folder and prints the folder ID + * @return{Promise} folder Id + */ async function createFolder() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -34,17 +35,12 @@ async function createFolder() { name: 'Invoices', mimeType: 'application/vnd.google-apps.folder', }; - try { - const file = await service.files.create({ - requestBody: fileMetadata, - fields: 'id', - }); - console.log('Folder Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody: fileMetadata, + fields: 'id', + }); + console.log('Folder Id:', file.data.id); + return file.data.id; } // [END drive_create_folder] diff --git a/drive/snippets/drive_v3/file_snippets/create_shortcut.js b/drive/snippets/drive_v3/file_snippets/create_shortcut.js index b4619a77..340ff631 100644 --- a/drive/snippets/drive_v3/file_snippets/create_shortcut.js +++ b/drive/snippets/drive_v3/file_snippets/create_shortcut.js @@ -13,15 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_create_shortcut] -/** - * Create a third party shortcut - * @return{obj} shortcut Id - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Create a third party shortcut + * @return{Promise} shortcut Id + */ async function createShortcut() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -34,18 +35,12 @@ async function createShortcut() { name: 'Project plan', mimeType: 'application/vnd.google-apps.drive-sdk', }; - - try { - const file = await service.files.create({ - requestBody: fileMetadata, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody: fileMetadata, + fields: 'id', + }); + console.log('File Id:', file.data.id); + return file.data.id; } // [END drive_create_shortcut] diff --git a/drive/snippets/drive_v3/file_snippets/download_file.js b/drive/snippets/drive_v3/file_snippets/download_file.js index ee676858..a81c58ab 100644 --- a/drive/snippets/drive_v3/file_snippets/download_file.js +++ b/drive/snippets/drive_v3/file_snippets/download_file.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_download_file] -/** - * Downloads a file - * @param{string} realFileId file ID - * @return{obj} file status - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Downloads a file + * @param{string} realFileId file ID + * @return{Promise} file status + */ async function downloadFile(realFileId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -32,18 +33,13 @@ async function downloadFile(realFileId) { }); const service = google.drive({version: 'v3', auth}); - fileId = realFileId; - try { - const file = await service.files.get({ - fileId: fileId, - alt: 'media', - }); - console.log(file.status); - return file.status; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const fileId = realFileId; + const file = await service.files.get({ + fileId, + alt: 'media', + }); + console.log(file.status); + return file.status; } // [END drive_download_file] diff --git a/drive/snippets/drive_v3/file_snippets/export_pdf.js b/drive/snippets/drive_v3/file_snippets/export_pdf.js index f1941bb4..89939e1b 100644 --- a/drive/snippets/drive_v3/file_snippets/export_pdf.js +++ b/drive/snippets/drive_v3/file_snippets/export_pdf.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_export_pdf] -/** - * Download a Document file in PDF format - * @param{string} fileId file ID - * @return{obj} file status - * */ 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 + */ async function exportPdf(fileId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -30,18 +31,12 @@ async function exportPdf(fileId) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); - - try { - const result = await service.files.export({ - fileId: fileId, - mimeType: 'application/pdf', - }); - console.log(result.status); - return result; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const result = await service.files.export({ + fileId, + mimeType: 'application/pdf', + }); + console.log(result.status); + return result.status; } // [END drive_export_pdf] 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 631020a9..41bed697 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 @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_move_file_to_folder] +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{obj} file status - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - + * @return{Promise} result status + */ async function moveFileToFolder(fileId, folderId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -31,29 +32,22 @@ async function moveFileToFolder(fileId, folderId) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); + // Retrieve the existing parents to remove + const file = await service.files.get({ + fileId, + fields: 'parents', + }); - try { - // Retrieve the existing parents to remove - const file = await service.files.get({ - fileId: fileId, - fields: 'parents', - }); - - // Move the file to the new folder - const previousParents = file.data.parents - .join(','); - const files = await service.files.update({ - fileId: fileId, - addParents: folderId, - removeParents: previousParents, - fields: 'id, parents', - }); - console.log(files.status); - return files.status; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + // Move the file to the new folder + const previousParents = (file.data.parents ?? []).join(','); + const result = await service.files.update({ + fileId, + addParents: folderId, + removeParents: previousParents, + fields: 'id, parents', + }); + console.log(result.status); + return result.status; } // [END drive_move_file_to_folder] diff --git a/drive/snippets/drive_v3/file_snippets/package.json b/drive/snippets/drive_v3/file_snippets/package.json index a0365f1c..e9dbdc30 100644 --- a/drive/snippets/drive_v3/file_snippets/package.json +++ b/drive/snippets/drive_v3/file_snippets/package.json @@ -8,9 +8,13 @@ "check": "tsc --noEmit" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { "node": ">=20" + }, + "dependencies": { + "googleapis": "catalog:" } -} \ No newline at end of file +} diff --git a/drive/snippets/drive_v3/file_snippets/search_file.js b/drive/snippets/drive_v3/file_snippets/search_file.js index 5a55d814..e7c8d6d7 100644 --- a/drive/snippets/drive_v3/file_snippets/search_file.js +++ b/drive/snippets/drive_v3/file_snippets/search_file.js @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_search_file] -/** - * Search file in drive location - * @return{obj} data file - * */ import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Search file in drive location + */ async function searchFile() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -29,22 +29,16 @@ async function searchFile() { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); - const files = []; - try { - const res = await service.files.list({ - q: 'mimeType=\'image/jpeg\'', - fields: 'nextPageToken, files(id, name)', - spaces: 'drive', - }); - Array.prototype.push.apply(files, res.files); - res.data.files.forEach(function(file) { - console.log('Found file:', file.name, file.id); - }); - return res.data.files; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + + const result = await service.files.list({ + q: 'mimeType=\'image/jpeg\'', + fields: 'nextPageToken, files(id, name)', + spaces: 'drive', + }); + (result.data.files ?? []).forEach((file) => { + console.log('Found file:', file.name, file.id); + }); + 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 e088ee29..5216547e 100644 --- a/drive/snippets/drive_v3/file_snippets/share_file.js +++ b/drive/snippets/drive_v3/file_snippets/share_file.js @@ -13,18 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_share_file] +import {GoogleAuth} from 'google-auth-library'; +import {google} from 'googleapis'; + /** * Batch permission modification + * * @param{string} fileId file ID * @param{string} targetUserEmail username * @param{string} targetDomainName domain - * @return{list} permission id - * */ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - + * @return{Promise>} permission id + */ async function shareFile(fileId, targetUserEmail, targetDomainName) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -32,6 +34,7 @@ async function shareFile(fileId, targetUserEmail, targetDomainName) { scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); + /** @type {Array} */ const permissionIds = []; const permissions = [ @@ -46,23 +49,20 @@ async function shareFile(fileId, targetUserEmail, targetDomainName) { domain: targetDomainName, // '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. + for (const permission of permissions) { - try { - const result = await service.permissions.create({ - resource: permission, - fileId: fileId, - fields: 'id', - }); - permissionIds.push(result.data.id); - console.log(`Inserted permission id: ${result.data.id}`); - } catch (err) { - // TODO(developer): Handle failed permissions - console.error(err); + const result = await service.permissions.create({ + requestBody: permission, + fileId, + fields: 'id', + }); + + if (!result.data.id) { + throw new Error('Failed to create permission'); } + + permissionIds.push(result.data.id); + console.log(`Inserted permission id: ${result.data.id}`); } return permissionIds; } diff --git a/drive/snippets/drive_v3/file_snippets/touch_file.js b/drive/snippets/drive_v3/file_snippets/touch_file.js index e13ab3d3..0567bc81 100644 --- a/drive/snippets/drive_v3/file_snippets/touch_file.js +++ b/drive/snippets/drive_v3/file_snippets/touch_file.js @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_touch_file] +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 Modified date time of the file - * @return{obj} modified Timestamp + * @return{Promise} modified Timestamp **/ -import {GoogleAuth} from 'google-auth-library'; -import {google} from 'googleapis'; - async function touchFile(fileId, Timestamp) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -35,18 +36,13 @@ async function touchFile(fileId, Timestamp) { modifiedTime: new Date().toISOString(), }; fileMetadata.modifiedTime = Timestamp; - try { - const file = await service.files.update({ - fileId: fileId, - requestBody: fileMetadata, - fields: 'id, modifiedTime', - }); - console.log('Modified time:', file.data.modifiedTime); - return file.data.modifiedTime; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.update({ + fileId, + requestBody: fileMetadata, + fields: 'id, modifiedTime', + }); + console.log('Modified time:', file.data.modifiedTime); + return file.data.modifiedTime; } // [END drive_touch_file] diff --git a/drive/snippets/drive_v3/file_snippets/tsconfig.json b/drive/snippets/drive_v3/file_snippets/tsconfig.json index e8c3a24a..37b1fdba 100644 --- a/drive/snippets/drive_v3/file_snippets/tsconfig.json +++ b/drive/snippets/drive_v3/file_snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/drive/snippets/drive_v3/file_snippets/upload_basic.js b/drive/snippets/drive_v3/file_snippets/upload_basic.js index f5da2526..03d11b84 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_basic.js +++ b/drive/snippets/drive_v3/file_snippets/upload_basic.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_basic] -/** - * Insert new file. - * @return{obj} file Id - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Insert new file. + * @return{Promise} file Id + */ async function uploadBasic() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -38,17 +39,12 @@ async function uploadBasic() { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg'), }; - try { - const file = await service.files.create({ - requestBody, - media: media, - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody, + media, + }); + console.log('File Id:', file.data.id); + return file.data.id; } // [END drive_upload_basic] 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 a87649a5..6009e2b1 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_to_folder.js +++ b/drive/snippets/drive_v3/file_snippets/upload_to_folder.js @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_to_folder] -/** - * Upload a file to the specified folder - * @param{string} folderId folder ID - * @return{obj} file Id - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Upload a file to the specified folder + * @param{string} folderId folder ID + */ async function uploadToFolder(folderId) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -34,7 +34,7 @@ async function uploadToFolder(folderId) { // TODO(developer): set folder Id // folderId = '1lWo8HghUBd-3mN4s98ArNFMdqmhqCXH7'; - const fileMetadata = { + const requestBody = { name: 'photo.jpg', parents: [folderId], }; @@ -43,18 +43,14 @@ async function uploadToFolder(folderId) { body: fs.createReadStream('files/photo.jpg'), }; - try { - const file = await service.files.create({ - requestBody: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody, + media, + fields: 'id', + }); + + console.log('File Id:', file.data.id); + 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 38d3094e..46090ede 100644 --- a/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js +++ b/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // [START drive_upload_with_conversion] -/** - * Upload file with conversion - * @return{obj} file Id - * */ -import fs from 'fs'; +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; +/** + * Upload file with conversion + * @return{Promise} file Id + */ async function uploadWithConversion() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app @@ -38,19 +39,13 @@ async function uploadWithConversion() { mimeType: 'text/csv', body: fs.createReadStream('files/report.csv'), }; - - try { - const file = await service.files.create({ - requestBody: fileMetadata, - media: media, - fields: 'id', - }); - console.log('File Id:', file.data.id); - return file.data.id; - } catch (err) { - // TODO(developer) - Handle error - throw err; - } + const file = await service.files.create({ + requestBody: fileMetadata, + media, + fields: 'id', + }); + console.log('File Id:', file.data.id); + return file.data.id; } // [END drive_upload_with_conversion] diff --git a/drive/snippets/files/package.json b/drive/snippets/files/package.json deleted file mode 100644 index 747fd64c..00000000 --- a/drive/snippets/files/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "drive-snippets-files", - "version": "1.0.0", - "private": true, - "license": "Apache-2.0", - "type": "module", - "scripts": { - "check": "tsc --noEmit" - }, - "devDependencies": { - "typescript": "catalog:" - }, - "engines": { - "node": ">=20" - } -} \ No newline at end of file diff --git a/drive/snippets/files/tsconfig.json b/drive/snippets/files/tsconfig.json deleted file mode 100644 index c5b794f3..00000000 --- a/drive/snippets/files/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json" -} \ No newline at end of file diff --git a/drive/snippets/test/helpers.js b/drive/snippets/test/helpers.js index edbce0f1..22f0e428 100644 --- a/drive/snippets/test/helpers.js +++ b/drive/snippets/test/helpers.js @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +import fs from 'node:fs'; import {GoogleAuth} from 'google-auth-library'; import {google} from 'googleapis'; -import fs from 'fs'; /** * Helper functions for Google Drive @@ -65,7 +66,7 @@ class Helpers { */ async createFile(fileMetadata, media) { const file = await this.service.files.create({ - resource: fileMetadata, + requestBody: fileMetadata, media, fields: 'id', }); diff --git a/drive/snippets/test/test_drive_v2_create_drive.js b/drive/snippets/test/test_drive_v2_create_drive.js index b6868855..3675965b 100644 --- a/drive/snippets/test/test_drive_v2_create_drive.js +++ b/drive/snippets/test/test_drive_v2_create_drive.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createDrive} from '../drive_v2/drive_snippets/create_drive.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_create_folder.js b/drive/snippets/test/test_drive_v2_create_folder.js index 3ce7f619..1249090a 100644 --- a/drive/snippets/test/test_drive_v2_create_folder.js +++ b/drive/snippets/test/test_drive_v2_create_folder.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createFolder} from '../drive_v2/file snippets/create_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_create_shortcut.js b/drive/snippets/test/test_drive_v2_create_shortcut.js index 46814fdf..09342718 100644 --- a/drive/snippets/test/test_drive_v2_create_shortcut.js +++ b/drive/snippets/test/test_drive_v2_create_shortcut.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createShortcut} from '../drive_v2/file snippets/create_shortcut.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_download_file.js b/drive/snippets/test/test_drive_v2_download_file.js index 9f1e2566..137c2399 100644 --- a/drive/snippets/test/test_drive_v2_download_file.js +++ b/drive/snippets/test/test_drive_v2_download_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {downloadFile} from '../drive_v2/file snippets/download_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_export_pdf.js b/drive/snippets/test/test_drive_v2_export_pdf.js index d2e24c44..325c29eb 100644 --- a/drive/snippets/test/test_drive_v2_export_pdf.js +++ b/drive/snippets/test/test_drive_v2_export_pdf.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {exportPdf} from '../drive_v2/file snippets/export_pdf.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_fetch_appdata_folder.js b/drive/snippets/test/test_drive_v2_fetch_appdata_folder.js index 7f647308..015220fa 100644 --- a/drive/snippets/test/test_drive_v2_fetch_appdata_folder.js +++ b/drive/snippets/test/test_drive_v2_fetch_appdata_folder.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchAppdataFolder} from '../drive_v2/appdata_snippets/fetch_appdata_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_fetch_changes.js b/drive/snippets/test/test_drive_v2_fetch_changes.js index e90d9aeb..e72fa774 100644 --- a/drive/snippets/test/test_drive_v2_fetch_changes.js +++ b/drive/snippets/test/test_drive_v2_fetch_changes.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchChanges} from '../drive_v2/change_snippets/fetch_changes.js'; import {fetchStartPageToken} from '../drive_v2/change_snippets/fetch_start_page_token.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_fetch_start_page_token.js b/drive/snippets/test/test_drive_v2_fetch_start_page_token.js index 546e8f94..457ba514 100644 --- a/drive/snippets/test/test_drive_v2_fetch_start_page_token.js +++ b/drive/snippets/test/test_drive_v2_fetch_start_page_token.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchStartPageToken} from '../drive_v2/change_snippets/fetch_start_page_token.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_list_appdata.js b/drive/snippets/test/test_drive_v2_list_appdata.js index 48594c10..ae741692 100644 --- a/drive/snippets/test/test_drive_v2_list_appdata.js +++ b/drive/snippets/test/test_drive_v2_list_appdata.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {uploadAppdata} from '../drive_v2/appdata_snippets/upload_appdata.js'; import {listAppdata} from '../drive_v2/appdata_snippets/list_appdata.js'; +import {uploadAppdata} from '../drive_v2/appdata_snippets/upload_appdata.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_move_file_to_folder.js b/drive/snippets/test/test_drive_v2_move_file_to_folder.js index 8810de29..8a346211 100644 --- a/drive/snippets/test/test_drive_v2_move_file_to_folder.js +++ b/drive/snippets/test/test_drive_v2_move_file_to_folder.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createFolder} from '../drive_v2/file snippets/create_folder.js'; import {moveFileToFolder} from '../drive_v2/file snippets/move_file_to_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_recover_drives.js b/drive/snippets/test/test_drive_v2_recover_drives.js index 5e02cea7..f0f56b53 100644 --- a/drive/snippets/test/test_drive_v2_recover_drives.js +++ b/drive/snippets/test/test_drive_v2_recover_drives.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {recoverDrives} from '../drive_v2/drive_snippets/recover_drives.js'; import {createDrive} from '../drive_v2/drive_snippets/create_drive.js'; +import {recoverDrives} from '../drive_v2/drive_snippets/recover_drives.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_search_file.js b/drive/snippets/test/test_drive_v2_search_file.js index 797b6309..a4dbc631 100644 --- a/drive/snippets/test/test_drive_v2_search_file.js +++ b/drive/snippets/test/test_drive_v2_search_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {searchFile} from '../drive_v2/file snippets/search_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_share_file.js b/drive/snippets/test/test_drive_v2_share_file.js index 592c7c67..d89eb533 100644 --- a/drive/snippets/test/test_drive_v2_share_file.js +++ b/drive/snippets/test/test_drive_v2_share_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {shareFile} from '../drive_v2/file snippets/share_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_touch_file.js b/drive/snippets/test/test_drive_v2_touch_file.js index d4017470..17963757 100644 --- a/drive/snippets/test/test_drive_v2_touch_file.js +++ b/drive/snippets/test/test_drive_v2_touch_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {touchFile} from '../drive_v2/file snippets/touch_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_upload_appdata.js b/drive/snippets/test/test_drive_v2_upload_appdata.js index 26abfe61..2ac914af 100644 --- a/drive/snippets/test/test_drive_v2_upload_appdata.js +++ b/drive/snippets/test/test_drive_v2_upload_appdata.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadAppdata} from '../drive_v2/appdata_snippets/upload_appdata.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_upload_basic.js b/drive/snippets/test/test_drive_v2_upload_basic.js index 81944e02..a6a83155 100644 --- a/drive/snippets/test/test_drive_v2_upload_basic.js +++ b/drive/snippets/test/test_drive_v2_upload_basic.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadBasic} from '../drive_v2/file snippets/upload_basic.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_upload_to_folder.js b/drive/snippets/test/test_drive_v2_upload_to_folder.js index cf4a7afb..56b23b30 100644 --- a/drive/snippets/test/test_drive_v2_upload_to_folder.js +++ b/drive/snippets/test/test_drive_v2_upload_to_folder.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {uploadToFolder} from '../drive_v2/file snippets/upload_to_folder.js'; import {createFolder} from '../drive_v2/file snippets/create_folder.js'; +import {uploadToFolder} from '../drive_v2/file snippets/upload_to_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v2_upload_with_conversion.js b/drive/snippets/test/test_drive_v2_upload_with_conversion.js index 25b12add..4b9164cc 100644 --- a/drive/snippets/test/test_drive_v2_upload_with_conversion.js +++ b/drive/snippets/test/test_drive_v2_upload_with_conversion.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadWithConversion} from '../drive_v2/file snippets/upload_with_conversion.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_create_drive.js b/drive/snippets/test/test_drive_v3_create_drive.js index cee27462..d2fcb184 100644 --- a/drive/snippets/test/test_drive_v3_create_drive.js +++ b/drive/snippets/test/test_drive_v3_create_drive.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createDrive} from '../drive_v3/drive_snippets/create_drive.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_create_folder.js b/drive/snippets/test/test_drive_v3_create_folder.js index e2a2c472..ae66d1af 100644 --- a/drive/snippets/test/test_drive_v3_create_folder.js +++ b/drive/snippets/test/test_drive_v3_create_folder.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createFolder} from '../drive_v3/file_snippets/create_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_create_shortcut.js b/drive/snippets/test/test_drive_v3_create_shortcut.js index 801c4070..d10717d8 100644 --- a/drive/snippets/test/test_drive_v3_create_shortcut.js +++ b/drive/snippets/test/test_drive_v3_create_shortcut.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createShortcut} from '../drive_v3/file_snippets/create_shortcut.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_download_file.js b/drive/snippets/test/test_drive_v3_download_file.js index c6a0ef30..3377df74 100644 --- a/drive/snippets/test/test_drive_v3_download_file.js +++ b/drive/snippets/test/test_drive_v3_download_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {downloadFile} from '../drive_v3/file_snippets/download_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_export_pdf.js b/drive/snippets/test/test_drive_v3_export_pdf.js index 0a0b209a..33c326c2 100644 --- a/drive/snippets/test/test_drive_v3_export_pdf.js +++ b/drive/snippets/test/test_drive_v3_export_pdf.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {exportPdf} from '../drive_v3/file_snippets/export_pdf.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_fetch_appdata_folder.js b/drive/snippets/test/test_drive_v3_fetch_appdata_folder.js index 9f6eb80d..e7fa0871 100644 --- a/drive/snippets/test/test_drive_v3_fetch_appdata_folder.js +++ b/drive/snippets/test/test_drive_v3_fetch_appdata_folder.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchAppdataFolder} from '../drive_v3/appdata_snippets/fetch_appdata_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_fetch_changes.js b/drive/snippets/test/test_drive_v3_fetch_changes.js index 44428e98..27dd8f6e 100644 --- a/drive/snippets/test/test_drive_v3_fetch_changes.js +++ b/drive/snippets/test/test_drive_v3_fetch_changes.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchChanges} from '../drive_v3/change_snippets/fetch_changes.js'; import {fetchStartPageToken} from '../drive_v3/change_snippets/fetch_start_page_token.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_fetch_start_page_token.js b/drive/snippets/test/test_drive_v3_fetch_start_page_token.js index e7ed3347..9cc5786f 100644 --- a/drive/snippets/test/test_drive_v3_fetch_start_page_token.js +++ b/drive/snippets/test/test_drive_v3_fetch_start_page_token.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {fetchStartPageToken} from '../drive_v3/change_snippets/fetch_start_page_token.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_list_appdata.js b/drive/snippets/test/test_drive_v3_list_appdata.js index 5eaf5a7b..9af72d1a 100644 --- a/drive/snippets/test/test_drive_v3_list_appdata.js +++ b/drive/snippets/test/test_drive_v3_list_appdata.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {uploadAppdata} from '../drive_v3/appdata_snippets/upload_appdata.js'; import {listAppdata} from '../drive_v3/appdata_snippets/list_appdata.js'; +import {uploadAppdata} from '../drive_v3/appdata_snippets/upload_appdata.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_move_file_to_folder.js b/drive/snippets/test/test_drive_v3_move_file_to_folder.js index 7107f7cc..858be0b7 100644 --- a/drive/snippets/test/test_drive_v3_move_file_to_folder.js +++ b/drive/snippets/test/test_drive_v3_move_file_to_folder.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createFolder} from '../drive_v3/file_snippets/create_folder.js'; import {moveFileToFolder} from '../drive_v3/file_snippets/move_file_to_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_recover_drives.js b/drive/snippets/test/test_drive_v3_recover_drives.js index 06a59779..32942c1d 100644 --- a/drive/snippets/test/test_drive_v3_recover_drives.js +++ b/drive/snippets/test/test_drive_v3_recover_drives.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {recoverDrives} from '../drive_v3/drive_snippets/recover_drives.js'; import {createDrive} from '../drive_v3/drive_snippets/create_drive.js'; +import {recoverDrives} from '../drive_v3/drive_snippets/recover_drives.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); @@ -40,11 +40,11 @@ describe('Drive snippets', () => { */ async function createOrphanedTeamDrive() { const fileId = await createDrive(); - const res = await helpers.service.permissions.list({ + const result = await helpers.service.permissions.list({ fileId, supportsTeamDrives: true, }); - res.data.permissions.forEach((permission) => { + result.data.permissions.forEach((permission) => { helpers.service.permissions.delete({ fileId, permissionId: permission.id, diff --git a/drive/snippets/test/test_drive_v3_search_file.js b/drive/snippets/test/test_drive_v3_search_file.js index 66d964c4..3852de6a 100644 --- a/drive/snippets/test/test_drive_v3_search_file.js +++ b/drive/snippets/test/test_drive_v3_search_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {searchFile} from '../drive_v3/file_snippets/search_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_share_file.js b/drive/snippets/test/test_drive_v3_share_file.js index bfb24e35..8748ba35 100644 --- a/drive/snippets/test/test_drive_v3_share_file.js +++ b/drive/snippets/test/test_drive_v3_share_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {shareFile} from '../drive_v3/file_snippets/share_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_touch_file.js b/drive/snippets/test/test_drive_v3_touch_file.js index 5f512787..3ced518c 100644 --- a/drive/snippets/test/test_drive_v3_touch_file.js +++ b/drive/snippets/test/test_drive_v3_touch_file.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {touchFile} from '../drive_v3/file_snippets/touch_file.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_upload_appdata.js b/drive/snippets/test/test_drive_v3_upload_appdata.js index c5e03088..0ffd2a97 100644 --- a/drive/snippets/test/test_drive_v3_upload_appdata.js +++ b/drive/snippets/test/test_drive_v3_upload_appdata.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadAppdata} from '../drive_v3/appdata_snippets/upload_appdata.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_upload_basic.js b/drive/snippets/test/test_drive_v3_upload_basic.js index d3fa483e..0039bc98 100644 --- a/drive/snippets/test/test_drive_v3_upload_basic.js +++ b/drive/snippets/test/test_drive_v3_upload_basic.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadBasic} from '../drive_v3/file_snippets/upload_basic.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_upload_to_folder.js b/drive/snippets/test/test_drive_v3_upload_to_folder.js index dca2d464..bb624ff2 100644 --- a/drive/snippets/test/test_drive_v3_upload_to_folder.js +++ b/drive/snippets/test/test_drive_v3_upload_to_folder.js @@ -15,9 +15,9 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; -import {uploadToFolder} from '../drive_v3/file_snippets/upload_to_folder.js'; import {createFolder} from '../drive_v3/file_snippets/create_folder.js'; +import {uploadToFolder} from '../drive_v3/file_snippets/upload_to_folder.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/drive/snippets/test/test_drive_v3_upload_with_conversion.js b/drive/snippets/test/test_drive_v3_upload_with_conversion.js index 01ede9de..63880d16 100644 --- a/drive/snippets/test/test_drive_v3_upload_with_conversion.js +++ b/drive/snippets/test/test_drive_v3_upload_with_conversion.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {uploadWithConversion} from '../drive_v3/file_snippets/upload_with_conversion.js'; +import {Helpers} from './helpers.js'; describe('Drive snippets', () => { const helpers = new Helpers(); diff --git a/eslint.config.js b/eslint.config.js index ec99a63f..b595a021 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -19,6 +19,7 @@ export default { rules: { ...google.rules, 'require-jsdoc': 'off', + 'valid-jsdoc': 'off', 'max-len': ['warn', {code: 100}], 'camelcase': [ 'warn', diff --git a/forms/snippets/add_item.js b/forms/snippets/add_item.js index 600cd68c..ba51e065 100644 --- a/forms/snippets/add_item.js +++ b/forms/snippets/add_item.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_add_item] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; async function addItem() { const authClient = await authenticate({ @@ -33,7 +34,12 @@ async function addItem() { const createResponse = await formsClient.forms.create({ requestBody: newForm, }); - console.log('New formId was: ' + createResponse.data.formId); + + if (!createResponse.data.formId) { + throw new Error('Form ID not returned.'); + } + + console.log(`New formId was: ${createResponse.data.formId}`); // Request body to add video item to a Form const update = { diff --git a/forms/snippets/add_responder.js b/forms/snippets/add_responder.js index a1dcc6db..df3387bc 100644 --- a/forms/snippets/add_responder.js +++ b/forms/snippets/add_responder.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_add_responder] -import path from 'path'; -import {drive} from '@googleapis/drive'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {drive} from '@googleapis/drive'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.file']; @@ -41,13 +42,13 @@ async function addResponder(formId, email) { }; try { - const res = await driveService.permissions.create({ + const result = await driveService.permissions.create({ fileId: formId, requestBody: permissionBody, fields: 'id,emailAddress,role,type,view', sendNotificationEmail: false, // Optional }); - console.log('Responder added:', res.data); + console.log('Responder added:', result.data); } catch (err) { console.error('Error adding responder:', err); } diff --git a/forms/snippets/anyone_with_link_responder.js b/forms/snippets/anyone_with_link_responder.js index 588d3e40..d69cc3b8 100644 --- a/forms/snippets/anyone_with_link_responder.js +++ b/forms/snippets/anyone_with_link_responder.js @@ -10,14 +10,16 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -import path from 'path'; -import {drive} from '@googleapis/drive'; + +// [START forms_is_anyone_with_link_responder_js] + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {drive} from '@googleapis/drive'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.file']; -// [START forms_is_anyone_with_link_responder_js] /** * Checks if anyone with the link is a responder for the form. * @@ -33,13 +35,13 @@ async function isAnyoneWithLinkResponder(formId) { let anyoneWithLinkResponder = false; try { - const res = await driveService.permissions.list({ + const result = await driveService.permissions.list({ fileId: formId, fields: 'permissions(id,type,role,view)', includePermissionsForView: 'published', }); - const permissions = res.data.permissions || []; + const permissions = result.data.permissions || []; if (permissions.length === 0) { console.log(`No permissions found for form ID: ${formId}`); } else { @@ -64,11 +66,8 @@ async function isAnyoneWithLinkResponder(formId) { `Form '${formId}' is NOT configured for 'Anyone with the link' to respond.`, ); } - } catch (err) { - console.error( - 'Error checking "anyone with link" permission:', - err.message || err, - ); + } catch (e) { + console.error(`Error checking "anyone with link" permission: ${e}`); } } // [END forms_is_anyone_with_link_responder_js] @@ -94,19 +93,16 @@ async function setAnyoneWithLinkResponder(formId) { }; try { - const res = await driveService.permissions.create({ + const result = await driveService.permissions.create({ fileId: formId, requestBody: permissionBody, fields: 'id', // Request only needed fields }); console.log( - `'Anyone with the link can respond' permission set for form '${formId}'. Permission ID: ${res.data.id}`, - ); - } catch (err) { - console.error( - 'Error setting "anyone with link" permission:', - err.message || err, + `'Anyone with the link can respond' permission set for form '${formId}'. Permission ID: ${result.data.id}`, ); + } catch (e) { + console.error(`Error setting "anyone with link" permission: ${e}`); } } // [END forms_set_anyone_with_link_responder_js] @@ -127,13 +123,13 @@ async function removeAnyoneWithLinkResponder(formId) { let permissionIdToDelete = null; try { - const res = await driveService.permissions.list({ + const result = await driveService.permissions.list({ fileId: formId, fields: 'permissions(id,type,role,view)', includePermissionsForView: 'published', }); - const permissions = res.data.permissions || []; + const permissions = result.data.permissions || []; for (const permission of permissions) { if ( permission.type === 'anyone' && @@ -158,11 +154,8 @@ async function removeAnyoneWithLinkResponder(formId) { `'Anyone with the link can respond' permission not found for form '${formId}'. Nothing to remove.`, ); } - } catch (err) { - console.error( - 'Error removing "anyone with link" permission:', - err.message || err, - ); + } catch (e) { + console.error(`Error removing "anyone with link" permission: ${e}`); } } // [END forms_remove_anyone_with_link_responder_js] diff --git a/forms/snippets/convert_form.js b/forms/snippets/convert_form.js index 3c0e5288..bff3cd7c 100644 --- a/forms/snippets/convert_form.js +++ b/forms/snippets/convert_form.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_convert_form] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; async function convertForm() { const authClient = await authenticate({ @@ -33,7 +34,12 @@ async function convertForm() { const createResponse = await formsClient.forms.create({ requestBody: newForm, }); - console.log('New formId was: ' + createResponse.data.formId); + + if (!createResponse.data.formId) { + throw new Error('Failed to create form.'); + } + + console.log(`New formId was: ${createResponse.data.formId}`); // Request body to convert form to a quiz const updateRequest = { @@ -50,12 +56,13 @@ async function convertForm() { }, ], }; - const res = await formsClient.forms.batchUpdate({ + + const result = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: updateRequest, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_convert_form] diff --git a/forms/snippets/create_form.js b/forms/snippets/create_form.js index 21dd1967..e3cfa600 100644 --- a/forms/snippets/create_form.js +++ b/forms/snippets/create_form.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_create_form] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; async function createForm() { const authClient = await authenticate({ @@ -30,11 +31,11 @@ async function createForm() { title: 'Creating a new form in Node', }, }; - const res = await formsClient.forms.create({ + const result = await formsClient.forms.create({ requestBody: newForm, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_create_form] diff --git a/forms/snippets/create_watch.js b/forms/snippets/create_watch.js index 0b162f20..d7b8babb 100644 --- a/forms/snippets/create_watch.js +++ b/forms/snippets/create_watch.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_create_watch] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; @@ -37,12 +38,12 @@ async function createWatch() { eventType: 'RESPONSES', }, }; - const res = await formsClient.forms.watches.create({ + const result = await formsClient.forms.watches.create({ formId: formID, requestBody: watchRequest, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_create_watch] diff --git a/forms/snippets/delete_watch.js b/forms/snippets/delete_watch.js index f0d28718..0dc7a5b3 100644 --- a/forms/snippets/delete_watch.js +++ b/forms/snippets/delete_watch.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_delete_watch] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; const watchID = ''; @@ -28,12 +29,12 @@ async function deleteWatch() { version: 'v1', auth: authClient, }); - const res = await formsClient.forms.watches.delete({ + const result = await formsClient.forms.watches.delete({ formId: formID, watchId: watchID, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_delete_watch] diff --git a/forms/snippets/get_all_responses.js b/forms/snippets/get_all_responses.js index 4555e0d2..5f535891 100644 --- a/forms/snippets/get_all_responses.js +++ b/forms/snippets/get_all_responses.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_retrieve_all_responses] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; @@ -25,13 +26,13 @@ async function getAllResponses() { }); const formsClient = forms({ version: 'v1', - auth: auth, + auth, }); - const res = await formsClient.forms.responses.list({ + const result = await formsClient.forms.responses.list({ formId: formID, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_retrieve_all_responses] diff --git a/forms/snippets/get_form.js b/forms/snippets/get_form.js index fcea8c27..e1c7f4ee 100644 --- a/forms/snippets/get_form.js +++ b/forms/snippets/get_form.js @@ -12,24 +12,25 @@ // limitations under the License. // [START forms_retrieve_contents] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; -async function getForm(query) { +async function getForm() { const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.body.readonly', }); const formsClient = forms({ version: 'v1', - auth: auth, + auth, }); - const res = await formsClient.forms.get({formId: formID}); - console.log(res.data); - return res.data; + const result = await formsClient.forms.get({formId: formID}); + console.log(result.data); + return result.data; } // [END forms_retrieve_contents] diff --git a/forms/snippets/get_responders.js b/forms/snippets/get_responders.js index 453dc270..a1268428 100644 --- a/forms/snippets/get_responders.js +++ b/forms/snippets/get_responders.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_get_responders] -import path from 'path'; -import {drive} from '@googleapis/drive'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {drive} from '@googleapis/drive'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; @@ -33,12 +34,12 @@ async function getResponders(formId) { const driveService = drive({version: 'v3', auth: authClient}); try { - const res = await driveService.permissions.list({ + const result = await driveService.permissions.list({ fileId: formId, includePermissionsForView: 'published', fields: 'permissions(id,emailAddress,type,role,view)', }); - const permissions = res.data.permissions || []; + const permissions = result.data.permissions || []; if (permissions.length === 0) { console.log(`No permissions found for form ID: ${formId}`); } else { diff --git a/forms/snippets/get_single_response.js b/forms/snippets/get_single_response.js index 180930ab..451b7199 100644 --- a/forms/snippets/get_single_response.js +++ b/forms/snippets/get_single_response.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_retrieve_single_response] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; const responseID = ''; @@ -26,14 +27,14 @@ async function getSingleResponse() { }); const formsClient = forms({ version: 'v1', - auth: auth, + auth, }); - const res = await formsClient.forms.responses.get({ + const result = await formsClient.forms.responses.get({ formId: formID, responseId: responseID, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_retrieve_single_response] diff --git a/forms/snippets/list_watches.js b/forms/snippets/list_watches.js index 5de5271f..431e7664 100644 --- a/forms/snippets/list_watches.js +++ b/forms/snippets/list_watches.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_list_form_watches] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const formID = ''; @@ -25,11 +26,11 @@ async function listWatches() { }); const formsClient = forms({ version: 'v1', - auth: auth, + auth, }); - const res = await formsClient.forms.watches.list({formId: formID}); - console.log(res.data); - return res.data; + const result = await formsClient.forms.watches.list({formId: formID}); + console.log(result.data); + return result.data; } // [END forms_list_form_watches] diff --git a/forms/snippets/package.json b/forms/snippets/package.json index 5a8b6d6f..47f22eb3 100644 --- a/forms/snippets/package.json +++ b/forms/snippets/package.json @@ -9,9 +9,13 @@ "check": "tsc --noEmit" }, "dependencies": { + "@google-cloud/local-auth": "catalog:", + "@googleapis/drive": "^15.0.0", + "@googleapis/forms": "^4.0.1", "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/forms/snippets/publish_form.js b/forms/snippets/publish_form.js index 7c50ade6..475091c2 100644 --- a/forms/snippets/publish_form.js +++ b/forms/snippets/publish_form.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_publish_form] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; @@ -45,11 +46,11 @@ async function publishForm(formIdToPublish) { }; try { - const res = await formsClient.forms.setPublishSettings({ + const result = await formsClient.forms.setPublishSettings({ formId: formIdToPublish, requestBody: setPublishSettingsRequest, }); - console.log('Form publish settings updated:', res.data); + console.log('Form publish settings updated:', result.data); } catch (err) { console.error('Error setting publish settings:', err); } diff --git a/forms/snippets/remove_responders.js b/forms/snippets/remove_responders.js index 9939affe..1ad8acb9 100644 --- a/forms/snippets/remove_responders.js +++ b/forms/snippets/remove_responders.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_remove_responder] -import path from 'path'; -import {drive} from '@googleapis/drive'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {drive} from '@googleapis/drive'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.file']; @@ -34,25 +35,29 @@ async function removeResponders(formId, email) { const driveService = drive({version: 'v3', auth: authClient}); try { - const res = await driveService.permissions.list({ + const result = await driveService.permissions.list({ fileId: formId, includePermissionsForView: 'published', fields: 'permissions(id,emailAddress,type,role,view)', }); - const permissions = res.data.permissions || []; + const permissions = result.data.permissions || []; const responderToRemove = permissions.find( - (permission) => permission.view === 'published' && - permission.role === 'reader' && permission.emailAddress === email); + (permission) => + permission.view === 'published' && + permission.role === 'reader' && + permission.emailAddress === email, + ); - if (responderToRemove) { + if (responderToRemove?.id) { const permissionId = responderToRemove.id; await driveService.permissions.delete({ fileId: formId, - permissionId: permissionId, + permissionId: responderToRemove.id, }); - console.log(`Responder with permission ID '${ - permissionId}' removed successfully.`); + console.log( + `Responder with permission ID '${permissionId}' removed successfully.`, + ); } 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 3b72c6d5..95f539d3 100644 --- a/forms/snippets/renew_watch.js +++ b/forms/snippets/renew_watch.js @@ -12,7 +12,8 @@ // limitations under the License. // [START forms_renew_watch] -import path from 'path'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; @@ -28,12 +29,12 @@ async function renewWatch() { version: 'v1', auth: authClient, }); - const res = await formsClient.forms.watches.renew({ + const result = await formsClient.forms.watches.renew({ formId: formID, watchId: watchID, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_renew_watch] diff --git a/forms/snippets/stop_accepting_responses.js b/forms/snippets/stop_accepting_responses.js index 8f11ba7a..9643db65 100644 --- a/forms/snippets/stop_accepting_responses.js +++ b/forms/snippets/stop_accepting_responses.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_stop_accepting_responses] + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; -import path from 'path'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; @@ -46,7 +47,7 @@ async function stopAcceptingResponses(formId) { try { const res = await formsClient.forms.setPublishSettings({ - formId: formId, + formId, requestBody: setPublishSettingsRequest, }); console.log('Form is no longer accepting responses.', res.data); diff --git a/forms/snippets/supports_publishing.js b/forms/snippets/supports_publishing.js index 8157b424..f2f19d89 100644 --- a/forms/snippets/supports_publishing.js +++ b/forms/snippets/supports_publishing.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_supports_publishing] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; @@ -36,20 +37,26 @@ async function supportsPublishing(formIdToCheck) { }); try { - const res = await formsClient.forms.get({ + const result = await formsClient.forms.get({ formId: formIdToCheck, }); - const formTitle = res.data.info.title; + const formTitle = result.data.info?.title; // If 'publishSettings' field exists (even if empty), it supports the new // publishing model. - if (res.data && res.data.publishSettings !== undefined) { - console.log(`Form '${formIdToCheck}' (Title: ${ - formTitle}) is NOT a legacy form (supports publishSettings).`); + if (result.data && result.data.publishSettings !== undefined) { + console.log( + `Form '${formIdToCheck}' (Title: ${ + formTitle + }) is NOT a legacy form (supports publishSettings).`, + ); } else { - console.log(`Form '${formIdToCheck}' (Title: ${ - formTitle}) IS a legacy form (does not have publishSettings field).`); + console.log( + `Form '${formIdToCheck}' (Title: ${ + formTitle + }) IS a legacy form (does not have publishSettings field).`, + ); } } catch (err) { console.error(`Error getting form metadata for '${formIdToCheck}':`, err); diff --git a/forms/snippets/tsconfig.json b/forms/snippets/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/forms/snippets/tsconfig.json +++ b/forms/snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/forms/snippets/unpublish_form.js b/forms/snippets/unpublish_form.js index fd5ef0e6..675ced9e 100644 --- a/forms/snippets/unpublish_form.js +++ b/forms/snippets/unpublish_form.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_unpublish_form] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; diff --git a/forms/snippets/update_form.js b/forms/snippets/update_form.js index 02a0c8a2..f2d24c3f 100644 --- a/forms/snippets/update_form.js +++ b/forms/snippets/update_form.js @@ -12,9 +12,10 @@ // limitations under the License. // [START forms_update_form] -import path from 'path'; -import {forms} from '@googleapis/forms'; + +import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; +import {forms} from '@googleapis/forms'; async function updateForm() { const authClient = await authenticate({ @@ -33,7 +34,10 @@ async function updateForm() { const createResponse = await formsClient.forms.create({ requestBody: newForm, }); - console.log('New formId was: ' + createResponse.data.formId); + + if (!createResponse.data.formId) throw new Error('Form ID not returned.'); + + console.log(`New formId was: ${createResponse.data.formId}`); // Request body to add description to a Form const update = { @@ -49,12 +53,12 @@ async function updateForm() { }, ], }; - const res = await formsClient.forms.batchUpdate({ + const result = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: update, }); - console.log(res.data); - return res.data; + console.log(result.data); + return result.data; } // [END forms_update_form] diff --git a/gmail/quickstart/index.js b/gmail/quickstart/index.js index ff49f3b3..a8acd54d 100644 --- a/gmail/quickstart/index.js +++ b/gmail/quickstart/index.js @@ -13,86 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START gmail_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the labels in the user's account. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listLabels() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the labels in the user's account. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listLabels(auth) { const gmail = google.gmail({version: 'v1', auth}); - const res = await gmail.users.labels.list({ + const result = await gmail.users.labels.list({ userId: 'me', }); - const labels = res.data.labels; + const labels = result.data.labels; if (!labels || labels.length === 0) { console.log('No labels found.'); return; @@ -103,6 +48,6 @@ async function listLabels(auth) { }); } -authorize().then(listLabels).catch(console.error); +await listLabels(); // [END gmail_quickstart] diff --git a/gmail/quickstart/package.json b/gmail/quickstart/package.json index 951a5980..12a3d26b 100644 --- a/gmail/quickstart/package.json +++ b/gmail/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/gmail/quickstart/tsconfig.json b/gmail/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/gmail/quickstart/tsconfig.json +++ b/gmail/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/meet/quickstart/index.js b/meet/quickstart/index.js index 7a5cb695..50c57346 100644 --- a/meet/quickstart/index.js +++ b/meet/quickstart/index.js @@ -13,94 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START meet_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; -import {authenticate} from '@google-cloud/local-auth'; + +import path from 'node:path'; +import process from 'node:process'; import {SpacesServiceClient} from '@google-apps/meet'; -import {auth} from 'google-auth-library'; +import {authenticate} from '@google-cloud/local-auth'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/meetings.space.created']; - -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return auth.fromJSON(credentials); - } catch (err) { - console.log(err); - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Creates a new meeting space. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function createSpace() { + const authClient = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Creates a new meeting space. - * @param {OAuth2Client} authClient An authorized OAuth2 client. - */ -async function createSpace(authClient) { const meetClient = new SpacesServiceClient({ - authClient: authClient, + authClient, }); // Construct request - const request = { - }; + const request = {}; // Run request const response = await meetClient.createSpace(request); console.log(`Meet URL: ${response[0].meetingUri}`); } -authorize().then(createSpace).catch(console.error); +await createSpace(); // [END meet_quickstart] diff --git a/meet/quickstart/package.json b/meet/quickstart/package.json index 04012a26..b0250060 100644 --- a/meet/quickstart/package.json +++ b/meet/quickstart/package.json @@ -13,6 +13,7 @@ "@google-cloud/local-auth": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/meet/quickstart/tsconfig.json b/meet/quickstart/tsconfig.json index 378b3b9c..9536a0f4 100644 --- a/meet/quickstart/tsconfig.json +++ b/meet/quickstart/tsconfig.json @@ -1,3 +1,3 @@ { - "extends": "../../tsconfig.base.json", -} \ No newline at end of file + "extends": "../../tsconfig.base.json" +} diff --git a/package.json b/package.json index e93753ed..e95704fc 100644 --- a/package.json +++ b/package.json @@ -35,5 +35,11 @@ "packageManager": "pnpm@10.15.1", "engines": { "node": ">=20" + }, + "pnpm": { + "overrides": { + "googleapis-common": "catalog:", + "google-auth-library": "catalog:" + } } } diff --git a/people/quickstart/index.js b/people/quickstart/index.js index c96d4831..3b3f0b9d 100644 --- a/people/quickstart/index.js +++ b/people/quickstart/index.js @@ -13,88 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START people_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Print the display name if available for 10 connections. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listConnectionNames() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Print the display name if available for 10 connections. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listConnectionNames(auth) { const service = google.people({version: 'v1', auth}); - const res = await service.people.connections.list({ + const result = await service.people.connections.list({ resourceName: 'people/me', pageSize: 10, personFields: 'names,emailAddresses', }); - const connections = res.data.connections; + const connections = result.data.connections; if (!connections || connections.length === 0) { console.log('No connections found.'); return; @@ -109,6 +54,5 @@ async function listConnectionNames(auth) { }); } -authorize().then(listConnectionNames).catch(console.error); - +await listConnectionNames(); // [END people_quickstart] diff --git a/people/quickstart/package.json b/people/quickstart/package.json index c1569338..b6ee5d60 100644 --- a/people/quickstart/package.json +++ b/people/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/people/quickstart/tsconfig.json b/people/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/people/quickstart/tsconfig.json +++ b/people/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3c16d252..da9860e5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,7 +13,7 @@ catalogs: specifier: ^0.7.0 version: 0.7.0 '@google-cloud/local-auth': - specifier: ^3.0.1 + specifier: 3.0.1 version: 3.0.1 '@grpc/grpc-js': specifier: ^1.13.4 @@ -36,11 +36,8 @@ catalogs: expect: specifier: ^29.2.1 version: 29.7.0 - google-auth-library: - specifier: ^10.3.0 - version: 10.3.0 googleapis: - specifier: ^159.0.0 + specifier: 159.0.0 version: 159.0.0 mocha: specifier: ^10.0.0 @@ -58,6 +55,10 @@ catalogs: specifier: ^5.9.2 version: 5.9.2 +overrides: + googleapis-common: 8.0.0 + google-auth-library: 10.3.0 + importers: .: @@ -90,6 +91,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -103,6 +107,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -116,12 +123,22 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 apps-script/execute: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -135,6 +152,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -148,6 +168,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -160,9 +183,6 @@ importers: '@grpc/grpc-js': specifier: 'catalog:' version: 1.13.4 - google-auth-library: - specifier: 'catalog:' - version: 10.3.0 open: specifier: 'catalog:' version: 10.2.0 @@ -170,6 +190,9 @@ importers: specifier: 'catalog:' version: 1.0.1 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -183,6 +206,9 @@ importers: specifier: 'catalog:' version: 3.0.1 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -196,16 +222,25 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 docs/quickstart: dependencies: + '@google-cloud/local-auth': + specifier: 'catalog:' + version: 3.0.1 googleapis: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -219,6 +254,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -232,76 +270,141 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: - typescript: - specifier: 'catalog:' - version: 5.9.2 - - drive/snippets/drive_v2: - devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v2/appdata_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v2/change_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v2/drive_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + '@types/uuid': + specifier: ^10.0.0 + version: 10.0.0 + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v2/file snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v3/appdata_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v3/change_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v3/drive_snippets: + dependencies: + googleapis: + specifier: 'catalog:' + version: 159.0.0 devDependencies: + '@types/uuid': + specifier: ^10.0.0 + version: 10.0.0 + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 drive/snippets/drive_v3/file_snippets: - devDependencies: - typescript: + dependencies: + googleapis: specifier: 'catalog:' - version: 5.9.2 - - drive/snippets/files: + version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 forms/snippets: dependencies: + '@google-cloud/local-auth': + specifier: 'catalog:' + version: 3.0.1 + '@googleapis/drive': + specifier: ^15.0.0 + version: 15.0.0 + '@googleapis/forms': + specifier: ^4.0.1 + version: 4.0.1 googleapis: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -315,6 +418,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -328,6 +434,9 @@ importers: specifier: 'catalog:' version: 3.0.1 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -341,6 +450,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -354,15 +466,15 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 sheets/snippets: dependencies: - google-auth-library: - specifier: 'catalog:' - version: 10.3.0 googleapis: specifier: 'catalog:' version: 159.0.0 @@ -370,6 +482,9 @@ importers: expect: specifier: 'catalog:' version: 29.7.0 + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 mocha: specifier: 'catalog:' version: 10.8.2 @@ -386,15 +501,15 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 slides/snippets: dependencies: - google-auth-library: - specifier: 'catalog:' - version: 10.3.0 googleapis: specifier: 'catalog:' version: 159.0.0 @@ -402,6 +517,9 @@ importers: expect: specifier: 'catalog:' version: 29.7.0 + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 mocha: specifier: 'catalog:' version: 10.8.2 @@ -418,6 +536,9 @@ importers: specifier: 'catalog:' version: 159.0.0 devDependencies: + google-auth-library: + specifier: 10.3.0 + version: 10.3.0 typescript: specifier: 'catalog:' version: 5.9.2 @@ -462,6 +583,14 @@ packages: resolution: {integrity: sha512-YJ3GFbksfHyEarbVHPSCzhKpjbnlAhdzg2SEf79l6ODukrSM1qUOqfopY232Xkw26huKSndyzmJz+A6b2WYn7Q==} engines: {node: '>=14.0.0'} + '@googleapis/drive@15.0.0': + resolution: {integrity: sha512-PGuhTZMrS8HCJnFpYRhCU92GXgWEszku6XA517rYv1ohNB3nJFrVvjdMvzr/QOD4Q8R4Kg3fFLl6ULpKewLc0A==} + engines: {node: '>=12.0.0'} + + '@googleapis/forms@4.0.1': + resolution: {integrity: sha512-SuBTmkdCv9gzbzGK71VP98o7I6ESeZRBdcJQT0r3sYFhAL2kZHXJj4Y2+KxZ4FoPVi4cVR/jpAInNof6xh7S1Q==} + engines: {node: '>=12.0.0'} + '@grpc/grpc-js@1.13.4': resolution: {integrity: sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==} engines: {node: '>=12.10.0'} @@ -601,6 +730,9 @@ packages: '@types/stack-utils@2.0.3': resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==} + '@types/uuid@10.0.0': + resolution: {integrity: sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==} + '@types/yargs-parser@21.0.3': resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} @@ -941,18 +1073,10 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - gaxios@6.7.1: - resolution: {integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==} - engines: {node: '>=14'} - gaxios@7.1.1: resolution: {integrity: sha512-Odju3uBUJyVCkW64nLD4wKLhbh93bh6vIg/ZIXkWiLPBrdgtc65+tls/qml+un3pr6JqYVFDZbbmLDQT68rTOQ==} engines: {node: '>=18'} - gcp-metadata@6.1.1: - resolution: {integrity: sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==} - engines: {node: '>=14'} - gcp-metadata@7.0.1: resolution: {integrity: sha512-UcO3kefx6dCcZkgcTGgVOTFb7b1LlQ02hY1omMjjrrBzkajRMCFgYOjs7J71WqnuG1k2b+9ppGL7FsOfhZMQKQ==} engines: {node: '>=18'} @@ -994,18 +1118,10 @@ packages: resolution: {integrity: sha512-ylSE3RlCRZfZB56PFJSfUCuiuPq83Fx8hqu1KPWGK8FVdSaxlp/qkeMMX/DT/18xkwXIHvXEXkZsljRwfrdEfQ==} engines: {node: '>=18'} - google-auth-library@9.15.1: - resolution: {integrity: sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==} - engines: {node: '>=14'} - google-gax@5.0.3: resolution: {integrity: sha512-DkWybwgkV8HA9aIizNEHEUHd8ho1BzGGQ/YMGDsTt167dQ8pk/oMiwxpUFvh6Ta93m8ZN7KwdWmP3o46HWjV+A==} engines: {node: '>=18'} - google-logging-utils@0.0.2: - resolution: {integrity: sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==} - engines: {node: '>=14'} - google-logging-utils@1.1.1: resolution: {integrity: sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==} engines: {node: '>=14'} @@ -1028,10 +1144,6 @@ packages: graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} - gtoken@7.1.0: - resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==} - engines: {node: '>=14.0.0'} - gtoken@8.0.0: resolution: {integrity: sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==} engines: {node: '>=18'} @@ -1126,10 +1238,6 @@ packages: resolution: {integrity: sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==} engines: {node: '>=8'} - is-stream@2.0.1: - resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} - engines: {node: '>=8'} - is-unicode-supported@0.1.0: resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} engines: {node: '>=10'} @@ -1269,15 +1377,6 @@ packages: engines: {node: '>=10.5.0'} deprecated: Use your platform's native DOMException instead - node-fetch@2.7.0: - resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} - engines: {node: 4.x || >=6.0.0} - peerDependencies: - encoding: ^0.1.0 - peerDependenciesMeta: - encoding: - optional: true - node-fetch@3.3.2: resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1501,9 +1600,6 @@ packages: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} - tr46@0.0.3: - resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} - turbo-darwin-64@2.5.6: resolution: {integrity: sha512-3C1xEdo4aFwMJAPvtlPqz1Sw/+cddWIOmsalHFMrsqqydcptwBfu26WW2cDm3u93bUzMbBJ8k3zNKFqxJ9ei2A==} cpu: [x64] @@ -1563,20 +1659,10 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - uuid@9.0.1: - resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==} - hasBin: true - web-streams-polyfill@3.3.3: resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==} engines: {node: '>= 8'} - webidl-conversions@3.0.1: - resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} - - whatwg-url@5.0.0: - resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -1676,11 +1762,22 @@ snapshots: '@google-cloud/local-auth@3.0.1': dependencies: arrify: 2.0.1 - google-auth-library: 9.15.1 + google-auth-library: 10.3.0 open: 7.4.2 server-destroy: 1.0.1 transitivePeerDependencies: - - encoding + - supports-color + + '@googleapis/drive@15.0.0': + dependencies: + googleapis-common: 8.0.0 + transitivePeerDependencies: + - supports-color + + '@googleapis/forms@4.0.1': + dependencies: + googleapis-common: 8.0.0 + transitivePeerDependencies: - supports-color '@grpc/grpc-js@1.13.4': @@ -1824,6 +1921,8 @@ snapshots: '@types/stack-utils@2.0.3': {} + '@types/uuid@10.0.0': {} + '@types/yargs-parser@21.0.3': {} '@types/yargs@17.0.33': @@ -2174,17 +2273,6 @@ snapshots: function-bind@1.1.2: {} - gaxios@6.7.1: - dependencies: - extend: 3.0.2 - https-proxy-agent: 7.0.6 - is-stream: 2.0.1 - node-fetch: 2.7.0 - uuid: 9.0.1 - transitivePeerDependencies: - - encoding - - supports-color - gaxios@7.1.1: dependencies: extend: 3.0.2 @@ -2193,15 +2281,6 @@ snapshots: transitivePeerDependencies: - supports-color - gcp-metadata@6.1.1: - dependencies: - gaxios: 6.7.1 - google-logging-utils: 0.0.2 - json-bigint: 1.0.0 - transitivePeerDependencies: - - encoding - - supports-color - gcp-metadata@7.0.1: dependencies: gaxios: 7.1.1 @@ -2271,18 +2350,6 @@ snapshots: transitivePeerDependencies: - supports-color - google-auth-library@9.15.1: - dependencies: - base64-js: 1.5.1 - ecdsa-sig-formatter: 1.0.11 - gaxios: 6.7.1 - gcp-metadata: 6.1.1 - gtoken: 7.1.0 - jws: 4.0.0 - transitivePeerDependencies: - - encoding - - supports-color - google-gax@5.0.3: dependencies: '@grpc/grpc-js': 1.13.4 @@ -2299,8 +2366,6 @@ snapshots: transitivePeerDependencies: - supports-color - google-logging-utils@0.0.2: {} - google-logging-utils@1.1.1: {} googleapis-common@8.0.0: @@ -2326,14 +2391,6 @@ snapshots: graphemer@1.4.0: {} - gtoken@7.1.0: - dependencies: - gaxios: 6.7.1 - jws: 4.0.0 - transitivePeerDependencies: - - encoding - - supports-color - gtoken@8.0.0: dependencies: gaxios: 7.1.1 @@ -2415,8 +2472,6 @@ snapshots: is-plain-obj@2.1.0: {} - is-stream@2.0.1: {} - is-unicode-supported@0.1.0: {} is-wsl@2.2.0: @@ -2604,10 +2659,6 @@ snapshots: node-domexception@1.0.0: {} - node-fetch@2.7.0: - dependencies: - whatwg-url: 5.0.0 - node-fetch@3.3.2: dependencies: data-uri-to-buffer: 4.0.1 @@ -2844,8 +2895,6 @@ snapshots: dependencies: is-number: 7.0.0 - tr46@0.0.3: {} - turbo-darwin-64@2.5.6: optional: true @@ -2891,17 +2940,8 @@ snapshots: util-deprecate@1.0.2: {} - uuid@9.0.1: {} - web-streams-polyfill@3.3.3: {} - webidl-conversions@3.0.1: {} - - whatwg-url@5.0.0: - dependencies: - tr46: 0.0.3 - webidl-conversions: 3.0.1 - which@2.0.2: dependencies: isexe: 2.0.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5a8f9e6c..a11506a5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,7 +4,7 @@ packages: catalog: '@google-apps/chat': ^0.19.0 '@google-apps/meet': ^0.7.0 - '@google-cloud/local-auth': ^3.0.1 + '@google-cloud/local-auth': 3.0.1 '@grpc/grpc-js': ^1.13.4 '@types/jest': ^30.0.0 '@types/mocha': ^10.0.10 @@ -12,8 +12,9 @@ catalog: eslint: ^8.57.1 eslint-config-google: ^0.14.0 expect: ^29.2.1 - google-auth-library: ^10.3.0 - googleapis: ^159.0.0 + google-auth-library: 10.3.0 + googleapis: 159.0.0 + googleapis-common: 8.0.0 mocha: ^10.0.0 open: ^10.1.2 server-destroy: ^1.0.1 diff --git a/sheets/quickstart/index.js b/sheets/quickstart/index.js index aba64a93..302f2e20 100644 --- a/sheets/quickstart/index.js +++ b/sheets/quickstart/index.js @@ -13,87 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START sheets_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Prints the names and majors of students in a sample spreadsheet: + * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listMajors() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} - -/** - * Prints the names and majors of students in a sample spreadsheet: - * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit - * @param {google.auth.OAuth2} auth The authenticated Google OAuth client. - */ -async function listMajors(auth) { const sheets = google.sheets({version: 'v4', auth}); - const res = await sheets.spreadsheets.values.get({ + const result = await sheets.spreadsheets.values.get({ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', range: 'Class Data!A2:E', }); - const rows = res.data.values; + const rows = result.data.values; if (!rows || rows.length === 0) { console.log('No data found.'); return; @@ -105,5 +50,5 @@ async function listMajors(auth) { }); } -authorize().then(listMajors).catch(console.error); +await listMajors(); // [END sheets_quickstart] diff --git a/sheets/quickstart/package.json b/sheets/quickstart/package.json index 4aa6eac7..6e69c65a 100644 --- a/sheets/quickstart/package.json +++ b/sheets/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/sheets/quickstart/tsconfig.json b/sheets/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/sheets/quickstart/tsconfig.json +++ b/sheets/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/sheets/snippets/package.json b/sheets/snippets/package.json index 20dbeeb0..cbfe602a 100644 --- a/sheets/snippets/package.json +++ b/sheets/snippets/package.json @@ -9,11 +9,11 @@ "test": "mocha --timeout 60000" }, "dependencies": { - "google-auth-library": "catalog:", "googleapis": "catalog:" }, "devDependencies": { "expect": "catalog:", + "google-auth-library": "catalog:", "mocha": "catalog:", "typescript": "catalog:" }, diff --git a/sheets/snippets/sheets_append_values.js b/sheets/snippets/sheets_append_values.js index 755d646b..24143157 100644 --- a/sheets/snippets/sheets_append_values.js +++ b/sheets/snippets/sheets_append_values.js @@ -44,19 +44,14 @@ async function appendValues(spreadsheetId, range, valueInputOption, _values) { const resource = { values, }; - try { - const result = await service.spreadsheets.values.append({ - spreadsheetId, - range, - valueInputOption, - resource, - }); - console.log(`${result.data.updates.updatedCells} cells appended.`); - return result; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const result = await service.spreadsheets.values.append({ + spreadsheetId, + range, + valueInputOption, + resource, + }); + console.log(`${result.data.updates.updatedCells} cells appended.`); + return result; } // [END sheets_append_values] diff --git a/sheets/snippets/sheets_batch_get_values.js b/sheets/snippets/sheets_batch_get_values.js index a7872f39..e1c585ed 100644 --- a/sheets/snippets/sheets_batch_get_values.js +++ b/sheets/snippets/sheets_batch_get_values.js @@ -35,18 +35,12 @@ async function batchGetValues(spreadsheetId, _ranges) { ]; // [START_EXCLUDE silent] ranges = _ranges; - // [END_EXCLUDE] - try { - const result = await service.spreadsheets.values.batchGet({ - spreadsheetId, - ranges, - }); - console.log(`${result.data.valueRanges.length} ranges retrieved.`); - return result; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const result = await service.spreadsheets.values.batchGet({ + spreadsheetId, + ranges, + }); + console.log(`${result.data.valueRanges.length} ranges retrieved.`); + return result; } // [END sheets_batch_get_values] diff --git a/sheets/snippets/sheets_batch_update.js b/sheets/snippets/sheets_batch_update.js index 9383ad18..21a32588 100644 --- a/sheets/snippets/sheets_batch_update.js +++ b/sheets/snippets/sheets_batch_update.js @@ -52,18 +52,13 @@ async function batchUpdate(spreadsheetId, title, find, replacement) { }); // Add additional requests (operations) ... const batchUpdateRequest = {requests}; - try { - const response = await service.spreadsheets.batchUpdate({ - spreadsheetId, - resource: batchUpdateRequest, - }); - const findReplaceResponse = response.data.replies[1].findReplace; - console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`); - return response; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const response = await service.spreadsheets.batchUpdate({ + spreadsheetId, + requestBody: batchUpdateRequest, + }); + const findReplaceResponse = response.data.replies[1].findReplace; + console.log(`${findReplaceResponse.occurrencesChanged} replacements made.`); + return response; } // [END sheets_batch_update] diff --git a/sheets/snippets/sheets_batch_update_values.js b/sheets/snippets/sheets_batch_update_values.js index f246f45d..50a70a0d 100644 --- a/sheets/snippets/sheets_batch_update_values.js +++ b/sheets/snippets/sheets_batch_update_values.js @@ -57,17 +57,12 @@ async function batchUpdateValues( data, valueInputOption, }; - try { - const result = await service.spreadsheets.values.batchUpdate({ - spreadsheetId, - resource, - }); - console.log('%d cells updated.', result.data.totalUpdatedCells); - return result; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const result = await service.spreadsheets.values.batchUpdate({ + spreadsheetId, + resource, + }); + console.log('%d cells updated.', result.data.totalUpdatedCells); + return result; } // [END sheets_batch_update_values] diff --git a/sheets/snippets/sheets_conditional_formatting.js b/sheets/snippets/sheets_conditional_formatting.js index 285cfc49..ff21fc67 100644 --- a/sheets/snippets/sheets_conditional_formatting.js +++ b/sheets/snippets/sheets_conditional_formatting.js @@ -75,17 +75,12 @@ async function conditionalFormatting(spreadsheetId) { const resource = { requests, }; - try { - const response = await service.spreadsheets.batchUpdate({ - spreadsheetId, - resource, - }); - console.log(`${response.data.replies.length} cells updated.`); - return response; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const response = await service.spreadsheets.batchUpdate({ + spreadsheetId, + resource, + }); + console.log(`${response.data.replies.length} cells updated.`); + return response; } // [END sheets_conditional_formatting] diff --git a/sheets/snippets/sheets_create.js b/sheets/snippets/sheets_create.js index fb11cf76..834a94bd 100644 --- a/sheets/snippets/sheets_create.js +++ b/sheets/snippets/sheets_create.js @@ -34,17 +34,12 @@ async function create(title) { title, }, }; - try { - const spreadsheet = await service.spreadsheets.create({ - resource, - fields: 'spreadsheetId', - }); - console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`); - return spreadsheet.data.spreadsheetId; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const spreadsheet = await service.spreadsheets.create({ + resource, + fields: 'spreadsheetId', + }); + console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`); + return spreadsheet.data.spreadsheetId; } // [END sheets_create] diff --git a/sheets/snippets/sheets_get_values.js b/sheets/snippets/sheets_get_values.js index c2c82b84..f1f08510 100644 --- a/sheets/snippets/sheets_get_values.js +++ b/sheets/snippets/sheets_get_values.js @@ -30,18 +30,13 @@ async function getValues(spreadsheetId, range) { }); const service = google.sheets({version: 'v4', auth}); - try { - const result = await service.spreadsheets.values.get({ - spreadsheetId, - range, - }); - const numRows = result.data.values ? result.data.values.length : 0; - console.log(`${numRows} rows retrieved.`); - return result; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const result = await service.spreadsheets.values.get({ + spreadsheetId, + range, + }); + const numRows = result.data.values ? result.data.values.length : 0; + console.log(`${numRows} rows retrieved.`); + return result; } // [END sheets_get_values] diff --git a/sheets/snippets/sheets_pivot_table.js b/sheets/snippets/sheets_pivot_table.js index dc25a7a9..b896f842 100644 --- a/sheets/snippets/sheets_pivot_table.js +++ b/sheets/snippets/sheets_pivot_table.js @@ -29,84 +29,79 @@ async function pivotTable(spreadsheetId) { }); const service = google.sheets({version: 'v4', auth}); - try { - // Create two sheets for our pivot table - let requests = [ - { - addSheet: {}, - }, - { - addSheet: {}, - }, - ]; - let resource = {requests}; - let response = await service.spreadsheets.batchUpdate({ - spreadsheetId, - resource, - }); - const sourceSheetId = response.data.replies[0].addSheet.properties.sheetId; - const targetSheetId = response.data.replies[1].addSheet.properties.sheetId; + // Create two sheets for our pivot table + let requests = [ + { + addSheet: {}, + }, + { + addSheet: {}, + }, + ]; + let resource = {requests}; + let response = await service.spreadsheets.batchUpdate({ + spreadsheetId, + resource, + }); + const sourceSheetId = response.data.replies[0].addSheet.properties.sheetId; + const targetSheetId = response.data.replies[1].addSheet.properties.sheetId; - requests = [ - { - updateCells: { - rows: { - values: [ - { - pivotTable: { - source: { - sheetId: sourceSheetId, - startRowIndex: 0, - startColumnIndex: 0, - endRowIndex: 20, - endColumnIndex: 7, - }, - rows: [ - { - sourceColumnOffset: 1, - showTotals: true, - sortOrder: 'ASCENDING', - }, - ], - columns: [ - { - sourceColumnOffset: 4, - sortOrder: 'ASCENDING', - showTotals: true, - }, - ], - values: [ - { - summarizeFunction: 'COUNTA', - sourceColumnOffset: 4, - }, - ], - valueLayout: 'HORIZONTAL', + requests = [ + { + updateCells: { + rows: { + values: [ + { + pivotTable: { + source: { + sheetId: sourceSheetId, + startRowIndex: 0, + startColumnIndex: 0, + endRowIndex: 20, + endColumnIndex: 7, }, + rows: [ + { + sourceColumnOffset: 1, + showTotals: true, + sortOrder: 'ASCENDING', + }, + ], + columns: [ + { + sourceColumnOffset: 4, + sortOrder: 'ASCENDING', + showTotals: true, + }, + ], + values: [ + { + summarizeFunction: 'COUNTA', + sourceColumnOffset: 4, + }, + ], + valueLayout: 'HORIZONTAL', }, - ], - }, - start: { - sheetId: targetSheetId, - rowIndex: 0, - columnIndex: 0, - }, - fields: 'pivotTable', + }, + ], }, + start: { + sheetId: targetSheetId, + rowIndex: 0, + columnIndex: 0, + }, + fields: 'pivotTable', }, - ]; - resource = { - requests, - }; - response = service.spreadsheets.batchUpdate({ - spreadsheetId, - resource, - }); - return response; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + }, + ]; + resource = { + requests, + }; + response = service.spreadsheets.batchUpdate({ + spreadsheetId, + resource, + }); + return response; } // [END sheets_pivot_tables] diff --git a/sheets/snippets/sheets_update_values.js b/sheets/snippets/sheets_update_values.js index 92c4b0f9..62a79d7a 100644 --- a/sheets/snippets/sheets_update_values.js +++ b/sheets/snippets/sheets_update_values.js @@ -44,19 +44,14 @@ async function updateValues(spreadsheetId, range, valueInputOption, _values) { const resource = { values, }; - try { - const result = await service.spreadsheets.values.update({ - spreadsheetId, - range, - valueInputOption, - resource, - }); - console.log('%d cells updated.', result.data.updatedCells); - return result; - } catch (err) { - // TODO (Developer) - Handle exception - throw err; - } + const result = await service.spreadsheets.values.update({ + spreadsheetId, + range, + valueInputOption, + resource, + }); + console.log('%d cells updated.', result.data.updatedCells); + return result; } // [END sheets_update_values] diff --git a/sheets/snippets/test/helpers.js b/sheets/snippets/test/helpers.js index 4b2afe07..85078188 100644 --- a/sheets/snippets/test/helpers.js +++ b/sheets/snippets/test/helpers.js @@ -68,16 +68,16 @@ class Helpers { * @return {Promise} A promise to return the Google API service. */ async createTestSpreadsheet() { - const res = await this.sheetsService.spreadsheets.create({ - resource: { + const result = await this.sheetsService.spreadsheets.create({ + requestBody: { properties: { title: 'Test Spreadsheet', }, }, fields: 'spreadsheetId', }); - this.deleteFileOnCleanup(res.data.spreadsheetId); - return res.data.spreadsheetId; + this.deleteFileOnCleanup(result.data.spreadsheetId); + return result.data.spreadsheetId; } /** @@ -88,7 +88,7 @@ class Helpers { async populateValues(spreadsheetId) { await this.sheetsService.spreadsheets.batchUpdate({ spreadsheetId, - resource: { + requestBody: { requests: [ { repeatCell: { diff --git a/sheets/snippets/test/test_sheets_append_values.js b/sheets/snippets/test/test_sheets_append_values.js index 8d16d562..fb1ab80b 100644 --- a/sheets/snippets/test/test_sheets_append_values.js +++ b/sheets/snippets/test/test_sheets_append_values.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {appendValues} from '../sheets_append_values.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet append values snippet', () => { const helpers = new Helpers(); @@ -28,15 +28,10 @@ describe('Spreadsheet append values snippet', () => { it('should append values to a spreadsheet', async () => { const spreadsheetId = await helpers.createTestSpreadsheet(); await helpers.populateValues(spreadsheetId); - const result = await appendValues( - spreadsheetId, - 'Sheet1', - 'USER_ENTERED', - [ - ['A', 'B'], - ['C', 'D'], - ], - ); + const result = await appendValues(spreadsheetId, 'Sheet1', 'USER_ENTERED', [ + ['A', 'B'], + ['C', 'D'], + ]); expect(result.data.tableRange).toBe('Sheet1!A1:J10'); const updates = result.data.updates; expect(updates.updatedRows).toBe(2); diff --git a/sheets/snippets/test/test_sheets_batch_get_values.js b/sheets/snippets/test/test_sheets_batch_get_values.js index 96ab10a5..20af1b04 100644 --- a/sheets/snippets/test/test_sheets_batch_get_values.js +++ b/sheets/snippets/test/test_sheets_batch_get_values.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {batchGetValues} from '../sheets_batch_get_values.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet batch get values snippet', () => { const helpers = new Helpers(); @@ -28,10 +28,7 @@ describe('Spreadsheet batch get values snippet', () => { it('should batch get spreadsheet values', async () => { const spreadsheetId = await helpers.createTestSpreadsheet(); await helpers.populateValues(spreadsheetId); - const result = await batchGetValues(spreadsheetId, [ - 'A1:A3', - 'B1:C1', - ]); + const result = await batchGetValues(spreadsheetId, ['A1:A3', 'B1:C1']); const valueRanges = result.data.valueRanges; expect(valueRanges.length).toBe(2); const values = valueRanges[0].values; diff --git a/sheets/snippets/test/test_sheets_batch_update.js b/sheets/snippets/test/test_sheets_batch_update.js index 4cf157de..5ffd2ca9 100644 --- a/sheets/snippets/test/test_sheets_batch_update.js +++ b/sheets/snippets/test/test_sheets_batch_update.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {batchUpdate} from '../sheets_batch_update.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet batch update snippet', () => { const helpers = new Helpers(); diff --git a/sheets/snippets/test/test_sheets_batch_update_values.js b/sheets/snippets/test/test_sheets_batch_update_values.js index f02579eb..812e0820 100644 --- a/sheets/snippets/test/test_sheets_batch_update_values.js +++ b/sheets/snippets/test/test_sheets_batch_update_values.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {batchUpdateValues} from '../sheets_batch_update_values.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet batch update values snippet', () => { const helpers = new Helpers(); diff --git a/sheets/snippets/test/test_sheets_conditional_formatting.js b/sheets/snippets/test/test_sheets_conditional_formatting.js index f7f4ec02..858faf49 100644 --- a/sheets/snippets/test/test_sheets_conditional_formatting.js +++ b/sheets/snippets/test/test_sheets_conditional_formatting.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {conditionalFormatting} from '../sheets_conditional_formatting.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet conditional formatting snippet', () => { const helpers = new Helpers(); @@ -28,9 +28,7 @@ describe('Spreadsheet conditional formatting snippet', () => { it('should conditionally format', async () => { const spreadsheetId = await helpers.createTestSpreadsheet(); await helpers.populateValues(spreadsheetId); - const result = await conditionalFormatting( - spreadsheetId, - ); + const result = await conditionalFormatting(spreadsheetId); expect(result.data.replies.length).toBe(2); }); }); diff --git a/sheets/snippets/test/test_sheets_create.js b/sheets/snippets/test/test_sheets_create.js index ca278d1f..c54b707b 100644 --- a/sheets/snippets/test/test_sheets_create.js +++ b/sheets/snippets/test/test_sheets_create.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {create} from '../sheets_create.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet create snippet', () => { const helpers = new Helpers(); diff --git a/sheets/snippets/test/test_sheets_get_values.js b/sheets/snippets/test/test_sheets_get_values.js index c5d34597..703a248d 100644 --- a/sheets/snippets/test/test_sheets_get_values.js +++ b/sheets/snippets/test/test_sheets_get_values.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {getValues} from '../sheets_get_values.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet get values snippet', () => { const helpers = new Helpers(); diff --git a/sheets/snippets/test/test_sheets_pivot_table.js b/sheets/snippets/test/test_sheets_pivot_table.js index a4785915..8ea5381a 100644 --- a/sheets/snippets/test/test_sheets_pivot_table.js +++ b/sheets/snippets/test/test_sheets_pivot_table.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {pivotTable} from '../sheets_pivot_table.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet pivot table snippet', () => { const helpers = new Helpers(); diff --git a/sheets/snippets/test/test_sheets_update_values.js b/sheets/snippets/test/test_sheets_update_values.js index e9989e7b..4132a7e5 100644 --- a/sheets/snippets/test/test_sheets_update_values.js +++ b/sheets/snippets/test/test_sheets_update_values.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {updateValues} from '../sheets_update_values.js'; +import {Helpers} from './helpers.js'; describe('Spreadsheet update values snippet', () => { const helpers = new Helpers(); @@ -27,15 +27,10 @@ describe('Spreadsheet update values snippet', () => { it('should update spreadsheet values', async () => { const spreadsheetId = await helpers.createTestSpreadsheet(); - const result = await updateValues( - spreadsheetId, - 'A1:B2', - 'USER_ENTERED', - [ - ['A', 'B'], - ['C', 'D'], - ], - ); + const result = await updateValues(spreadsheetId, 'A1:B2', 'USER_ENTERED', [ + ['A', 'B'], + ['C', 'D'], + ]); expect(result.data.updatedRows).toBe(2); expect(result.data.updatedColumns).toBe(2); expect(result.data.updatedCells).toBe(4); diff --git a/sheets/snippets/tsconfig.json b/sheets/snippets/tsconfig.json index c5b794f3..2fb554f9 100644 --- a/sheets/snippets/tsconfig.json +++ b/sheets/snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/slides/quickstart/index.js b/slides/quickstart/index.js index 1791efa6..904db2ca 100644 --- a/slides/quickstart/index.js +++ b/slides/quickstart/index.js @@ -13,96 +13,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START slides_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/presentations.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Prints the number of slides and elements in a sample presentation: + * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listSlides() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Prints the number of slides and elements in a sample presentation: - * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit - * @param {google.auth.OAuth2} auth The authenticated Google OAuth client. - */ -async function listSlides(auth) { const slidesApi = google.slides({version: 'v1', auth}); - const res = await slidesApi.presentations.get({ + const result = await slidesApi.presentations.get({ presentationId: '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc', }); - const slides = res.data.slides; + const slides = result.data.slides; if (!slides || slides.length === 0) { console.log('No slides found.'); return; } console.log('The presentation contains %s slides:', slides.length); - res.data.slides.forEach((slide, i) => { + (result.data.slides ?? []).forEach((slide, i) => { console.log( - `- Slide #${i + 1} contains ${slide.pageElements.length} elements.`, + `- Slide #${i + 1} contains ${ + slide?.pageElements?.length ?? 0 + }} elements.`, ); }); } -authorize().then(listSlides).catch(console.error); +await listSlides(); // [END slides_quickstart] diff --git a/slides/quickstart/package.json b/slides/quickstart/package.json index 2aa25eeb..3e472735 100644 --- a/slides/quickstart/package.json +++ b/slides/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/slides/quickstart/tsconfig.json b/slides/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/slides/quickstart/tsconfig.json +++ b/slides/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/slides/snippets/package.json b/slides/snippets/package.json index 5e1be535..3a744e9d 100644 --- a/slides/snippets/package.json +++ b/slides/snippets/package.json @@ -9,11 +9,11 @@ "test": "mocha --timeout 60000" }, "dependencies": { - "google-auth-library": "catalog:", "googleapis": "catalog:" }, "devDependencies": { "expect": "catalog:", + "google-auth-library": "catalog:", "mocha": "catalog:", "typescript": "catalog:" }, diff --git a/slides/snippets/slides_copy_presentation.js b/slides/snippets/slides_copy_presentation.js index a0cb243b..f5dcf1bd 100644 --- a/slides/snippets/slides_copy_presentation.js +++ b/slides/snippets/slides_copy_presentation.js @@ -32,19 +32,13 @@ async function copyPresentation(presentationId, copyTitle) { const request = { name: copyTitle, }; - - try { - const driveResponse = await service.files.copy({ - fileId: presentationId, - resource: request, - }); - const presentationCopyId = driveResponse.data.id; - console.log('Created copied presentation with ID: ' + presentationCopyId); - return driveResponse; - } catch (err) { - // TODO (developer) - handle exception - throw err; - } + const driveResponse = await service.files.copy({ + fileId: presentationId, + requestBody: request, + }); + const presentationCopyId = driveResponse.data.id; + console.log(`Created copied presentation with ID: ${presentationCopyId}`); + return driveResponse; } // [END slides_copy_presentation] diff --git a/slides/snippets/slides_create_bulleted_text.js b/slides/snippets/slides_create_bulleted_text.js index 3c2f7bb6..aa7e7abf 100644 --- a/slides/snippets/slides_create_bulleted_text.js +++ b/slides/snippets/slides_create_bulleted_text.js @@ -42,21 +42,14 @@ async function createBulletedText(presentationId, shapeId) { }, }, ]; - - // Execute the requests. - try { - const batchUpdateResponse = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log(`Added bullets to text in shape with ID: ${shapeId}`); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const batchUpdateResponse = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log(`Added bullets to text in shape with ID: ${shapeId}`); + return batchUpdateResponse.data; } // [END slides_create_bulleted_text] diff --git a/slides/snippets/slides_create_image.js b/slides/snippets/slides_create_image.js index 5d0961e9..2fcde756 100644 --- a/slides/snippets/slides_create_image.js +++ b/slides/snippets/slides_create_image.js @@ -60,22 +60,15 @@ async function createImage(presentationId, pageId) { }, }, ]; - - // Execute the request. - try { - const response = await service.presentations.batchUpdate({ - presentationId, - resource: {requests}, - }); - const createImageResponse = response.data.replies; - console.log( - `Created image with ID: ${createImageResponse[0].createImage.objectId}`, - ); - return createImageResponse; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const response = await service.presentations.batchUpdate({ + presentationId, + requestBody: {requests}, + }); + const createImageResponse = response.data.replies; + console.log( + `Created image with ID: ${createImageResponse[0].createImage.objectId}`, + ); + return createImageResponse; } // [END slides_create_image] diff --git a/slides/snippets/slides_create_presentation.js b/slides/snippets/slides_create_presentation.js index fedda7a4..dc96b5d7 100644 --- a/slides/snippets/slides_create_presentation.js +++ b/slides/snippets/slides_create_presentation.js @@ -28,18 +28,13 @@ async function createPresentation(title) { }); const service = google.slides({version: 'v1', auth}); - try { - const presentation = await service.presentations.create({ - title, - }); - console.log( - `Created presentation with ID: ${presentation.data.presentationId}`, - ); - return presentation; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const presentation = await service.presentations.create({ + title, + }); + console.log( + `Created presentation with ID: ${presentation.data.presentationId}`, + ); + return presentation; } // [END slides_create_presentation] diff --git a/slides/snippets/slides_create_sheets_chart.js b/slides/snippets/slides_create_sheets_chart.js index fc3a5ee5..2d4d2d2f 100644 --- a/slides/snippets/slides_create_sheets_chart.js +++ b/slides/snippets/slides_create_sheets_chart.js @@ -49,7 +49,7 @@ async function createSheetsChart( { createSheetsChart: { objectId: presentationChartId, - spreadsheetId: spreadsheetId, + spreadsheetId, chartId: sheetChartId, linkingMode: 'LINKED', elementProperties: { @@ -69,21 +69,14 @@ async function createSheetsChart( }, }, ]; - - // Execute the request. - try { - const batchUpdateResponse = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log(`Added a linked Sheets chart with ID: ${presentationChartId}`); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const batchUpdateResponse = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log(`Added a linked Sheets chart with ID: ${presentationChartId}`); + return batchUpdateResponse.data; } // [END slides_create_sheets_chart] diff --git a/slides/snippets/slides_create_slide.js b/slides/snippets/slides_create_slide.js index 1d8b3231..2a879b9e 100644 --- a/slides/snippets/slides_create_slide.js +++ b/slides/snippets/slides_create_slide.js @@ -40,25 +40,16 @@ async function createSlide(presentationId, pageId) { }, }, ]; - // If you wish to populate the slide with elements, add element create requests here, - // using the pageId. - - // Execute the request. - try { - const res = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log( - `Created slide with ID: ${res.data.replies[0].createSlide.objectId}`, - ); - return res; - } catch (err) { - // TODO (developer) - handle exception - throw err; - } + const result = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log( + `Created slide with ID: ${result.data.replies[0].createSlide.objectId}`, + ); + return res; } // [END slides_create_slide] diff --git a/slides/snippets/slides_create_textbox_with_text.js b/slides/snippets/slides_create_textbox_with_text.js index 24892dcb..481f9047 100644 --- a/slides/snippets/slides_create_textbox_with_text.js +++ b/slides/snippets/slides_create_textbox_with_text.js @@ -64,21 +64,16 @@ async function createTextboxWithText(presentationId, pageId) { }, }, ]; - // Execute the request. - try { - const createTextboxWithTextResponse = - await service.presentations.batchUpdate({ + const createTextboxWithTextResponse = await service.presentations.batchUpdate( + { presentationId, - resource: {requests}, - }); - const createShapeResponse = - createTextboxWithTextResponse.data.replies[0].createShape; - console.log(`Created textbox with ID: ${createShapeResponse.objectId}`); - return createTextboxWithTextResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + requestBody: {requests}, + }, + ); + const createShapeResponse = + createTextboxWithTextResponse.data.replies[0].createShape; + console.log(`Created textbox with ID: ${createShapeResponse.objectId}`); + return createTextboxWithTextResponse.data; } // [END slides_create_textbox_with_text] diff --git a/slides/snippets/slides_image_merging.js b/slides/snippets/slides_image_merging.js index 2756cff8..d8e309f6 100644 --- a/slides/snippets/slides_image_merging.js +++ b/slides/snippets/slides_image_merging.js @@ -38,60 +38,55 @@ async function imageMerging(templatePresentationId, imageUrl, customerName) { const customerGraphicUrl = imageUrl; // Duplicate the template presentation using the Drive API. - const copyTitle = customerName + ' presentation'; - try { - const driveResponse = await driveService.files.copy({ - fileId: templatePresentationId, - resource: { - name: copyTitle, - }, - }); - const presentationCopyId = driveResponse.data.id; + const copyTitle = `${customerName} presentation`; + const driveResponse = await driveService.files.copy({ + fileId: templatePresentationId, + requestBody: { + name: copyTitle, + }, + }); + const presentationCopyId = driveResponse.data.id; - // Create the image merge (replaceAllShapesWithImage) requests. - const requests = [ - { - replaceAllShapesWithImage: { - imageUrl: logoUrl, - replaceMethod: 'CENTER_INSIDE', - containsText: { - text: '{{company-logo}}', - matchCase: true, - }, + // Create the image merge (replaceAllShapesWithImage) requests. + const requests = [ + { + replaceAllShapesWithImage: { + imageUrl: logoUrl, + replaceMethod: 'CENTER_INSIDE', + containsText: { + text: '{{company-logo}}', + matchCase: true, }, }, - { - replaceAllShapesWithImage: { - imageUrl: customerGraphicUrl, - replaceMethod: 'CENTER_INSIDE', - containsText: { - text: '{{customer-graphic}}', - matchCase: true, - }, + }, + { + replaceAllShapesWithImage: { + imageUrl: customerGraphicUrl, + replaceMethod: 'CENTER_INSIDE', + containsText: { + text: '{{customer-graphic}}', + matchCase: true, }, }, - ]; + }, + ]; - // Execute the requests for this presentation. - const batchUpdateResponse = await slidesService.presentations.batchUpdate({ - presentationId: presentationCopyId, - resource: { - requests, - }, - }); - let numReplacements = 0; - for (let i = 0; i < batchUpdateResponse.data.replies.length; ++i) { - numReplacements += - batchUpdateResponse.data.replies[i].replaceAllShapesWithImage - .occurrencesChanged; - } - console.log(`Created merged presentation with ID: ${presentationCopyId}`); - console.log(`Replaced ${numReplacements} shapes with images.`); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; + // Execute the requests for this presentation. + const batchUpdateResponse = await slidesService.presentations.batchUpdate({ + presentationId: presentationCopyId, + requestBody: { + requests, + }, + }); + let numReplacements = 0; + for (let i = 0; i < batchUpdateResponse.data.replies.length; ++i) { + numReplacements += + batchUpdateResponse.data.replies[i].replaceAllShapesWithImage + .occurrencesChanged; } + console.log(`Created merged presentation with ID: ${presentationCopyId}`); + console.log(`Replaced ${numReplacements} shapes with images.`); + return batchUpdateResponse.data; } // [END slides_image_merging] diff --git a/slides/snippets/slides_refresh_sheets_chart.js b/slides/snippets/slides_refresh_sheets_chart.js index fd91c06c..3914e077 100644 --- a/slides/snippets/slides_refresh_sheets_chart.js +++ b/slides/snippets/slides_refresh_sheets_chart.js @@ -37,23 +37,16 @@ async function refreshSheetsChart(presentationId, presentationChartId) { }, }, ]; - - // Execute the request. - try { - const batchUpdateResponse = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log( - `Refreshed a linked Sheets chart with ID: ${presentationChartId}`, - ); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const batchUpdateResponse = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log( + `Refreshed a linked Sheets chart with ID: ${presentationChartId}`, + ); + return batchUpdateResponse.data; } // [END slides_refresh_sheets_chart] diff --git a/slides/snippets/slides_simple_text_replace.js b/slides/snippets/slides_simple_text_replace.js index f8486b4d..dd523143 100644 --- a/slides/snippets/slides_simple_text_replace.js +++ b/slides/snippets/slides_simple_text_replace.js @@ -48,20 +48,14 @@ async function simpleTextReplace(presentationId, shapeId, replacementText) { }, }, ]; - // Execute the requests. - try { - const batchUpdateResponse = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log(`Replaced text in shape with ID: ${shapeId}`); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exception - throw err; - } + const batchUpdateResponse = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log(`Replaced text in shape with ID: ${shapeId}`); + return batchUpdateResponse.data; } // [END slides_simple_text_replace] diff --git a/slides/snippets/slides_text_merging.js b/slides/snippets/slides_text_merging.js index 31fc605c..937d3536 100644 --- a/slides/snippets/slides_text_merging.js +++ b/slides/snippets/slides_text_merging.js @@ -39,91 +39,80 @@ async function textMerging(templatePresentationId, dataSpreadsheetId) { // Use the Sheets API to load data, one record per row. const responses = []; const dataRangeNotation = 'A2:M6'; + const sheetsResponse = await sheetsService.spreadsheets.values.get({ + spreadsheetId: dataSpreadsheetId, + range: dataRangeNotation, + }); + const values = sheetsResponse.data.values; - try { - const sheetsResponse = await sheetsService.spreadsheets.values.get({ - spreadsheetId: dataSpreadsheetId, - range: dataRangeNotation, - }); - const values = sheetsResponse.data.values; - - // For each record, create a new merged presentation. - 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 + // For each record, create a new merged presentation. + 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 - // Duplicate the template presentation using the Drive API. - const copyTitle = customerName + ' presentation'; - let requests = { - name: copyTitle, - }; + // Duplicate the template presentation using the Drive API. + const title = `${customerName} presentation`; - const driveResponse = await driveService.files.copy({ - fileId: templatePresentationId, - requests, - }); + 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 = [ - { - replaceAllText: { - containsText: { - text: '{{customer-name}}', - matchCase: true, - }, - replaceText: customerName, + const presentationCopyId = driveResponse.data.id; + // Create the text merge (replaceAllText) requests for this presentation. + requests = [ + { + replaceAllText: { + containsText: { + text: '{{customer-name}}', + matchCase: true, }, + replaceText: customerName, }, - { - replaceAllText: { - containsText: { - text: '{{case-description}}', - matchCase: true, - }, - replaceText: caseDescription, + }, + { + replaceAllText: { + containsText: { + text: '{{case-description}}', + matchCase: true, }, + replaceText: caseDescription, }, - { - replaceAllText: { - containsText: { - text: '{{total-portfolio}}', - matchCase: true, - }, - replaceText: totalPortfolio, + }, + { + replaceAllText: { + containsText: { + text: '{{total-portfolio}}', + matchCase: true, }, + replaceText: totalPortfolio, }, - ]; - // Execute the requests for this presentation. - const batchUpdateResponse = await slidesService.presentations.batchUpdate( - { - presentationId: presentationCopyId, - resource: { - requests, - }, - }, - ); - 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) { - numReplacements += result.replies[i].replaceAllText.occurrencesChanged; - } - console.log( - `Created presentation for ${customerName} with ID: ` + - presentationCopyId, - ); - console.log(`Replaced ${numReplacements} text instances`); - return result; + }, + ]; + // Execute the requests for this presentation. + const batchUpdateResponse = await slidesService.presentations.batchUpdate({ + presentationId: presentationCopyId, + requestBody: { + requests, + }, + }); + 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) { + numReplacements += result.replies[i].replaceAllText.occurrencesChanged; } - } catch (err) { - // TODO (developer) - Handle exception - throw err; + console.log( + `Created presentation for ${customerName} with ID: ${presentationCopyId}`, + ); + 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 c8ec7281..6b92c7c7 100644 --- a/slides/snippets/slides_text_style_update.js +++ b/slides/snippets/slides_text_style_update.js @@ -93,21 +93,14 @@ async function textStyleUpdate(presentationId, shapeId) { }, }, ]; - - // Execute the requests. - try { - const batchUpdateResponse = await service.presentations.batchUpdate({ - presentationId, - resource: { - requests, - }, - }); - console.log(`Updated the text style for shape with ID: ${shapeId}`); - return batchUpdateResponse.data; - } catch (err) { - // TODO (developer) - Handle exceptions - throw err; - } + const batchUpdateResponse = await service.presentations.batchUpdate({ + presentationId, + requestBody: { + requests, + }, + }); + console.log(`Updated the text style for shape with ID: ${shapeId}`); + return batchUpdateResponse.data; } // [END slides_text_style_update] diff --git a/slides/snippets/test/helpers.js b/slides/snippets/test/helpers.js index e82cf2d0..d6e44e46 100644 --- a/slides/snippets/test/helpers.js +++ b/slides/snippets/test/helpers.js @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {google} from 'googleapis'; + import {GoogleAuth} from 'google-auth-library'; +import {google} from 'googleapis'; /** * Helper functions for Google Slides @@ -69,11 +70,11 @@ class Helpers { * @return {Promise} A promise to return the presentation ID. */ async createTestPresentation() { - const res = await this.slidesService.presentations.create({ + const result = await this.slidesService.presentations.create({ title: 'Test Preso', }); - this.deleteFileOnCleanup(res.data.presentationId); - return res.data.presentationId; + this.deleteFileOnCleanup(result.data.presentationId); + return result.data.presentationId; } /** @@ -99,7 +100,7 @@ class Helpers { } await this.slidesService.presentations.batchUpdate({ presentationId, - resource: { + requestBody: { requests, }, }); @@ -147,13 +148,13 @@ class Helpers { }, }, ]; - const res = await this.slidesService.presentations.batchUpdate({ + const result = await this.slidesService.presentations.batchUpdate({ presentationId, - resource: { + requestBody: { requests, }, }); - return res.data.replies[0].createShape.objectId; + return result.data.replies[0].createShape.objectId; } /** @@ -179,7 +180,7 @@ class Helpers { { createSheetsChart: { objectId: chartId, - spreadsheetId: spreadsheetId, + spreadsheetId, chartId: sheetChartId, linkingMode: 'LINKED', elementProperties: { @@ -200,13 +201,13 @@ class Helpers { }, ]; - const res = await this.slidesService.presentations.batchUpdate({ + const result = await this.slidesService.presentations.batchUpdate({ presentationId, - resource: { + requestBody: { requests, }, }); - return res.data.replies[0].createSheetsChart.objectId; + return result.data.replies[0].createSheetsChart.objectId; } /** @@ -214,8 +215,8 @@ class Helpers { * @return {Promise} A promise to return the Google API service. */ async createTestSpreadsheet() { - const res = await this.sheetsService.spreadsheets.create({ - resource: { + const result = await this.sheetsService.spreadsheets.create({ + requestBody: { properties: { title: 'Test Spreadsheet', }, @@ -223,8 +224,8 @@ class Helpers { fields: 'spreadsheetId', }); - this.deleteFileOnCleanup(res.data.spreadsheetId); - return res.data.spreadsheetId; + this.deleteFileOnCleanup(result.data.spreadsheetId); + return result.data.spreadsheetId; } /** @@ -235,7 +236,7 @@ class Helpers { async populateValues(spreadsheetId) { await this.sheetsService.spreadsheets.batchUpdate({ spreadsheetId, - resource: { + requestBody: { requests: [ { repeatCell: { diff --git a/slides/snippets/test/test_slides_copy_presentation.js b/slides/snippets/test/test_slides_copy_presentation.js index 19dd4056..ec435b6a 100644 --- a/slides/snippets/test/test_slides_copy_presentation.js +++ b/slides/snippets/test/test_slides_copy_presentation.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {copyPresentation} from '../slides_copy_presentation.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); diff --git a/slides/snippets/test/test_slides_create_bulleted_text.js b/slides/snippets/test/test_slides_create_bulleted_text.js index a7b9d1ed..05f8de8c 100644 --- a/slides/snippets/test/test_slides_create_bulleted_text.js +++ b/slides/snippets/test/test_slides_create_bulleted_text.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createBulletedText} from '../slides_create_bulleted_text.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -29,10 +29,7 @@ describe('Presentation snippets', () => { const pageIds = await helpers.addSlides(presentationId, 1, 'BLANK'); const pageId = pageIds[0]; const boxId = await helpers.createTestTextbox(presentationId, pageId); - const response = await createBulletedText( - presentationId, - boxId, - ); + const response = await createBulletedText(presentationId, boxId); expect(1).toEqual(response.replies.length); }); }); diff --git a/slides/snippets/test/test_slides_create_image.js b/slides/snippets/test/test_slides_create_image.js index 6a1ef3a8..d033c698 100644 --- a/slides/snippets/test/test_slides_create_image.js +++ b/slides/snippets/test/test_slides_create_image.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createImage} from '../slides_create_image.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -28,10 +28,7 @@ describe('Presentation snippets', () => { const presentationId = await helpers.createTestPresentation(); const ids = await helpers.addSlides(presentationId, 1, 'BLANK'); const pageId = ids[0]; - const response = await createImage( - presentationId, - pageId, - ); + const response = await createImage(presentationId, pageId); expect(response.length).toBe(1); const imageId = response[0].createImage.objectId; expect(imageId).toBeDefined(); diff --git a/slides/snippets/test/test_slides_create_presentation.js b/slides/snippets/test/test_slides_create_presentation.js index 16494a6f..886e58d2 100644 --- a/slides/snippets/test/test_slides_create_presentation.js +++ b/slides/snippets/test/test_slides_create_presentation.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createPresentation} from '../slides_create_presentation.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -25,9 +25,7 @@ describe('Presentation snippets', () => { }); it('should create a presentation', async () => { - const presentation = await createPresentation( - 'Title', - ); + const presentation = await createPresentation('Title'); expect(presentation).toBeDefined(); helpers.deleteFileOnCleanup(presentation.data.presentationId); }); diff --git a/slides/snippets/test/test_slides_create_sheets_chart.js b/slides/snippets/test/test_slides_create_sheets_chart.js index d2fcd59b..855cd73d 100644 --- a/slides/snippets/test/test_slides_create_sheets_chart.js +++ b/slides/snippets/test/test_slides_create_sheets_chart.js @@ -14,8 +14,8 @@ // * limitations under the License. // */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createSheetsChart} from '../slides_create_sheets_chart.js'; +import {Helpers} from './helpers.js'; // Replace with your test spreadsheets id and charts id const CHART_ID = 1107320627; diff --git a/slides/snippets/test/test_slides_create_slide.js b/slides/snippets/test/test_slides_create_slide.js index 433d17d4..299562c8 100644 --- a/slides/snippets/test/test_slides_create_slide.js +++ b/slides/snippets/test/test_slides_create_slide.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createSlide} from '../slides_create_slide.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -28,10 +28,7 @@ describe('Presentation snippets', () => { const presentationId = await helpers.createTestPresentation(); await helpers.addSlides(presentationId, 3, 'TITLE_AND_TWO_COLUMNS'); const pageId = 'my_page_id'; - const response = await createSlide( - presentationId, - pageId, - ); + const response = await createSlide(presentationId, pageId); expect(pageId).toEqual(response.data.replies[0].createSlide.objectId); }); }); diff --git a/slides/snippets/test/test_slides_create_textbox_with_text.js b/slides/snippets/test/test_slides_create_textbox_with_text.js index 4cae25cc..1738d89c 100644 --- a/slides/snippets/test/test_slides_create_textbox_with_text.js +++ b/slides/snippets/test/test_slides_create_textbox_with_text.js @@ -15,8 +15,8 @@ */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {createTextboxWithText} from '../slides_create_textbox_with_text.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -29,10 +29,7 @@ describe('Presentation snippets', () => { const presentationId = await helpers.createTestPresentation(); const ids = await helpers.addSlides(presentationId, 1, 'BLANK'); const pageId = ids[0]; - const response = await createTextboxWithText( - presentationId, - pageId, - ); + const response = await createTextboxWithText(presentationId, pageId); expect(response.replies.length).toEqual(2); const boxId = response.replies[0].createShape.objectId; expect(boxId).toBeDefined(); diff --git a/slides/snippets/test/test_slides_image_merging.js b/slides/snippets/test/test_slides_image_merging.js index 4f0e4abe..0b37a4a1 100644 --- a/slides/snippets/test/test_slides_image_merging.js +++ b/slides/snippets/test/test_slides_image_merging.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {imageMerging} from '../slides_image_merging.js'; +import {Helpers} from './helpers.js'; const TEMPLATE_PRESENTATION_ID = '1MmTR712m7U_kgeweE57POWwkEyWAV17AVAWjpmltmIg'; const IMAGE_URL = diff --git a/slides/snippets/test/test_slides_refresh_sheets_chart.js b/slides/snippets/test/test_slides_refresh_sheets_chart.js index 16c9f0c5..e0fcf0bd 100644 --- a/slides/snippets/test/test_slides_refresh_sheets_chart.js +++ b/slides/snippets/test/test_slides_refresh_sheets_chart.js @@ -14,8 +14,8 @@ // * limitations under the License. // */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {refreshSheetsChart} from '../slides_refresh_sheets_chart.js'; +import {Helpers} from './helpers.js'; // Replace with your test spreadsheets id and charts id const CHART_ID = 1107320627; @@ -38,10 +38,7 @@ describe('Presentation snippets', () => { DATA_SPREADSHEET_ID, CHART_ID, ); - const response = await refreshSheetsChart( - presentationId, - sheetChartId, - ); + const response = await refreshSheetsChart(presentationId, sheetChartId); expect(1).toEqual(response.replies.length); }); }); diff --git a/slides/snippets/test/test_slides_simple_text_replace.js b/slides/snippets/test/test_slides_simple_text_replace.js index a40c2a9e..2fb56916 100644 --- a/slides/snippets/test/test_slides_simple_text_replace.js +++ b/slides/snippets/test/test_slides_simple_text_replace.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {simpleTextReplace} from '../slides_simple_text_replace.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); diff --git a/slides/snippets/test/test_slides_text_merging.js b/slides/snippets/test/test_slides_text_merging.js index 1e20f226..28786bb9 100644 --- a/slides/snippets/test/test_slides_text_merging.js +++ b/slides/snippets/test/test_slides_text_merging.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {textMerging} from '../slides_text_merging.js'; +import {Helpers} from './helpers.js'; const TEMPLATE_PRESENTATION_ID = '1MmTR712m7U_kgeweE57POWwkEyWAV17AVAWjpmltmIg'; @@ -29,10 +29,7 @@ describe('Presentation snippets', () => { it('should merge text', async () => { let sheetId = await helpers.createTestSpreadsheet(); sheetId = await helpers.populateValues(sheetId); - const responses = await textMerging( - TEMPLATE_PRESENTATION_ID, - sheetId, - ); + const responses = await textMerging(TEMPLATE_PRESENTATION_ID, sheetId); // console.log(responses); expect(3).toEqual(responses.replies.length); let numReplacements = 0; diff --git a/slides/snippets/test/test_slides_text_style_update.js b/slides/snippets/test/test_slides_text_style_update.js index b12cd9cc..9554621f 100644 --- a/slides/snippets/test/test_slides_text_style_update.js +++ b/slides/snippets/test/test_slides_text_style_update.js @@ -14,8 +14,8 @@ * limitations under the License. */ import {expect} from 'expect'; -import {Helpers} from './helpers.js'; import {textStyleUpdate} from '../slides_text_style_update.js'; +import {Helpers} from './helpers.js'; describe('Presentation snippets', () => { const helpers = new Helpers(); @@ -29,10 +29,7 @@ describe('Presentation snippets', () => { const pageIds = await helpers.addSlides(presentationId, 1, 'BLANK'); const pageId = pageIds[0]; const boxId = await helpers.createTestTextbox(presentationId, pageId); - const response = await textStyleUpdate( - presentationId, - boxId, - ); + const response = await textStyleUpdate(presentationId, boxId); expect(3).toEqual(response.replies.length); }); }); diff --git a/slides/snippets/tsconfig.json b/slides/snippets/tsconfig.json index c5b794f3..2fb554f9 100644 --- a/slides/snippets/tsconfig.json +++ b/slides/snippets/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/tasks/quickstart/index.js b/tasks/quickstart/index.js index 3f4144eb..6cac8f83 100644 --- a/tasks/quickstart/index.js +++ b/tasks/quickstart/index.js @@ -13,87 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* eslint-disable camelcase */ + // [START tasks_quickstart] -import fs from 'fs/promises'; -import path from 'path'; -import process from 'process'; + +import path from 'node:path'; +import process from 'node:process'; import {authenticate} from '@google-cloud/local-auth'; import {google} from 'googleapis'; -// If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/tasks.readonly']; -// The file token.json stores the user's access and refresh tokens, and is -// created automatically when the authorization flow completes for the first -// time. -const TOKEN_PATH = path.join(process.cwd(), 'token.json'); const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json'); /** - * Reads previously authorized credentials from the save file. - * - * @return {Promise} - */ -async function loadSavedCredentialsIfExist() { - try { - const content = await fs.readFile(TOKEN_PATH); - const credentials = JSON.parse(content); - return google.auth.fromJSON(credentials); - } catch (err) { - return null; - } -} - -/** - * Serializes credentials to a file compatible with GoogleAuth.fromJSON. - * - * @param {OAuth2Client} client - * @return {Promise} - */ -async function saveCredentials(client) { - const content = await fs.readFile(CREDENTIALS_PATH); - const keys = JSON.parse(content); - const key = keys.installed || keys.web; - const payload = JSON.stringify({ - type: 'authorized_user', - client_id: key.client_id, - client_secret: key.client_secret, - refresh_token: client.credentials.refresh_token, - }); - await fs.writeFile(TOKEN_PATH, payload); -} - -/** - * Load or request or authorization to call APIs. - * + * Lists the user's first 10 task lists. */ -async function authorize() { - let client = await loadSavedCredentialsIfExist(); - if (client) { - return client; - } - client = await authenticate({ +async function listTaskLists() { + const auth = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH, }); - if (client.credentials) { - await saveCredentials(client); - } - return client; -} -/** - * Lists the user's first 10 task lists. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -async function listTaskLists(auth) { const service = google.tasks({version: 'v1', auth}); - const res = await service.tasklists.list({ + const result = await service.tasklists.list({ maxResults: 10, }); - const taskLists = res.data.items; - if (taskLists && taskLists.length) { + const taskLists = result.data.items; + if (taskLists?.length) { console.log('Task lists:'); taskLists.forEach((taskList) => { console.log(`${taskList.title} (${taskList.id})`); @@ -103,6 +48,6 @@ async function listTaskLists(auth) { } } -authorize().then(listTaskLists).catch(console.error); +await listTaskLists(); // [END tasks_quickstart] diff --git a/tasks/quickstart/package.json b/tasks/quickstart/package.json index aac9d5eb..472c210b 100644 --- a/tasks/quickstart/package.json +++ b/tasks/quickstart/package.json @@ -13,6 +13,7 @@ "googleapis": "catalog:" }, "devDependencies": { + "google-auth-library": "catalog:", "typescript": "catalog:" }, "engines": { diff --git a/tasks/quickstart/tsconfig.json b/tasks/quickstart/tsconfig.json index 4280ce73..cae9d8e1 100644 --- a/tasks/quickstart/tsconfig.json +++ b/tasks/quickstart/tsconfig.json @@ -1,3 +1,4 @@ { - "extends": "../../tsconfig.base.json" -} \ No newline at end of file + "extends": "../../tsconfig.base.json", + "include": ["**/*.js"] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index f4ac5f13..3301625d 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -8,13 +8,7 @@ "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, - "outDir": "./dist", + "outDir": "./dist" }, - "include": [ - "**/*.js" - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file + "exclude": ["node_modules", "dist"] +}