### Install google-proto-files Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/nodejs-proto-files/README.md Install the package using npm. ```bash npm install google-proto-files ``` -------------------------------- ### Install gaxios Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gaxios/README.md Install gaxios using npm. This is the first step before using the library. ```sh npm install gaxios ``` -------------------------------- ### Install Google Auth Library Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Install the google-auth-library package using npm. ```bash npm install google-auth-library ``` -------------------------------- ### Install gcp-metadata Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gcp-metadata/README.md Install the gcp-metadata client library using npm. ```bash npm install gcp-metadata ``` -------------------------------- ### Install Pack-N-Play Node.js Client Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/README.md Use npm to install the Pack-N-Play client library. This command installs the latest stable version. ```bash npm install pack-n-play ``` -------------------------------- ### Complete Serialization and Deserialization Example Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/proto3-json-serializer-nodejs/README.md Demonstrates loading a proto file, creating a protobuf object, deserializing proto3 JSON into it, and then serializing it back to verify correctness. This example uses google-proto-files for sample protos. ```javascript const assert = require('assert'); const path = require('path'); const protobuf = require('protobufjs'); const serializer = require('proto3-json-serializer'); // We'll take sample protos from google-proto-files but the code will work with any protos const protos = require('google-proto-files'); // Load some proto file const rpcProtos = protos.getProtoPath('rpc'); const root = protobuf.loadSync([ path.join(rpcProtos, 'status.proto'), path.join(rpcProtos, 'error_details.proto'), ]); const Status = root.lookupType('google.rpc.Status'); // If you have a protobuf object that follows proto3 JSON syntax // https://developers.google.com/protocol-buffers/docs/proto3#json // (this is an example of google.rpc.Status message in JSON) const json = { code: 3, message: 'Test error message', details: [ { '@type': 'google.rpc.BadRequest', fieldViolations: [ { field: 'field', description: 'must not be null', }, ], }, ], }; // You can deserialize it into a protobuf.js object: const deserialized = serializer.fromProto3JSON(Status, json); console.log(deserialized); // And serialize it back const serialized = serializer.toProto3JSON(deserialized); assert.deepStrictEqual(serialized, json); ``` -------------------------------- ### Install the Cloud Speech-to-Text Client Library Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/test-fixtures/google-cloud-speech-nodejs/speech-v1p1beta1-nodejs/README.md Use npm to install the client library for the Cloud Speech-to-Text API. This command should be run in your project directory. ```bash npm install @google-cloud/speech ``` -------------------------------- ### Using googleapis Client Library for Google Drive API Source: https://context7.com/googleapis/google-cloud-node-core/llms.txt Demonstrates how to use the googleapis client library to interact with the Google Drive API. This example shows authentication setup and making a file list request. ```javascript const { google } = require('googleapis'); const auth = new google.auth.GoogleAuth({ scopes: ['https://www.googleapis.com/auth/drive.readonly'], }); const drive = google.drive({ version: 'v3', auth }); const { data } = await drive.files.list({ pageSize: 10, q: "'root' in parents", fields: 'files(id, name)', }); console.log(data.files); ``` -------------------------------- ### Install Cloud Tasks Node.js Client Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/test-fixtures/google-cloud-tasks-nodejs/tasks-v2beta2-nodejs/README.md Install the Cloud Tasks client library for Node.js using npm. ```bash npm install @google-cloud/tasks ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/CONTRIBUTING.md Run this command to install project dependencies before running tests or making changes. ```bash npm install ``` -------------------------------- ### Quickstart: Using the gcp-metadata Client Library Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gcp-metadata/README.md Demonstrates how to check metadata server availability and retrieve instance and project metadata. Ensure you are running within a Google Cloud environment for metadata to be available. ```javascript const gcpMetadata = require('gcp-metadata'); async function quickstart() { // check to see if this code can access a metadata server const isAvailable = await gcpMetadata.isAvailable(); console.log(`Is available: ${isAvailable}`); // Instance and Project level metadata will only be available if // running inside of a Google Cloud compute environment such as // Cloud Functions, App Engine, Kubernetes Engine, or Compute Engine. // To learn more about the differences between instance and project // level metadata, see: // https://cloud.google.com/compute/docs/storing-retrieving-metadata#project-instance-metadata if (isAvailable) { // grab all top level metadata from the service const instanceMetadata = await gcpMetadata.instance(); console.log('Instance metadata:'); console.log(instanceMetadata); // get all project level metadata const projectMetadata = await gcpMetadata.project(); console.log('Project metadata:'); console.log(projectMetadata); } } quickstart(); ``` -------------------------------- ### Start Showcase Server with Docker Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md Run the Showcase API server using Docker. This command exposes the necessary ports for the API to be accessible. ```sh # in another window $ docker run -p 7469:7469/tcp -p 7469:7469/udp -p 1337:1337/tcp --rm gcr.io/gapic-images/gapic-showcase:0.6.1 ``` -------------------------------- ### Install and Test Generated Code Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md After generating the TypeScript libraries, navigate to the output directory, install dependencies, format the code, and run unit tests. ```sh $ cd showcase-typescript $ npm install # install dependencies $ npm run fix # format the code $ npm test # run unit tests ``` -------------------------------- ### Example JSDoc Configuration Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/jsdoc-fresh/README.md A comprehensive example of a .jsdoc.json configuration file. It includes settings for tags, source inclusion/exclusion patterns, plugins, template-specific options like reference title and sorting, and output options. ```json { "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc"] }, "source": { "include": ["lib", "package.json", "README.md"], "includePattern": ".js$", "excludePattern": "(node_modules/|docs)" }, "plugins": [ "plugins/markdown" ], "templates": { "referenceTitle": "My SDK Name", "disableSort": false, "collapse": true, "resources": { "google": "https://www.google.com/" } }, "opts": { "destination": "./docs/", "encoding": "utf8", "private": true, "recurse": true, "template": "./node_modules/jsdoc-template" } } ``` -------------------------------- ### Install Dependencies and Compile without Bazel Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md If Bazel is not installed, use npm and Yarn to install dependencies and compile the project. This assumes Yarn is installed globally. ```sh # in gapic-generator-typescript folder $ npm install --global yarn # install yarn if you haven't already $ yarn install # install dependencies $ npm run compile # build project with Bazel ``` -------------------------------- ### Install Legacy Version of Pack-N-Play Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/README.md To install a version compatible with older Node.js runtimes, use npm dist-tags with the legacy naming convention. For example, to install for Node.js 8, use `legacy-8`. ```bash npm install pack-n-play@legacy-8 ``` -------------------------------- ### Install googleapis-common Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/nodejs-googleapis-common/README.md Install the googleapis-common package using npm. This is the first step to using Google API client libraries in your Node.js project. ```bash npm install googleapis-common ``` -------------------------------- ### Install retry-request and teeny-request Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/retry-request/readme.md Install the retry-request package along with teeny-request, which it uses for making HTTP requests. ```sh $ npm install --save teeny-request $ npm install --save retry-request ``` -------------------------------- ### Use Generated Client in Node.js Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md Example of how to use the generated client library in a Node.js environment. It demonstrates creating a client instance and making a call to the Echo service. ```javascript $ node Welcome to Node.js v12.1.0. Type ".help" for more information. > const showcase = require('.') // assuming you're in showcase-typescript undefined > const client = new showcase.EchoClient({ sslCreds: require('@grpc/grpc-js').credentials.createInsecure() }) undefined > client.echo({ content: 'hello world!' }).then(console.log) Promise { } > [ { content: 'hello world!' }, undefined, undefined ] ``` -------------------------------- ### Complete OAuth2 Example Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Demonstrates a full OAuth2 authorization code flow, including setting up a local server to handle callbacks, acquiring tokens, and making an authenticated API request. Ensure you have an `oauth2.keys.json` file with your Google Cloud project's credentials. ```javascript const {OAuth2Client} = require('google-auth-library'); const http = require('http'); const url = require('url'); const open = require('open'); const destroyer = require('server-destroy'); // Download your OAuth2 configuration from the Google const keys = require('./oauth2.keys.json'); /** * Start by acquiring a pre-authenticated oAuth2 client. */ async function main() { const oAuth2Client = await getAuthenticatedClient(); // Make a simple request to the People API using our pre-authenticated client. The `fetch` and // `request` methods accept a [`GaxiosOptions`](https://github.com/googleapis/gaxios) // object. const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; const res = await oAuth2Client.fetch(url); console.log(res.data); // After acquiring an access_token, you may want to check on the audience, expiration, // or original scopes requested. You can do that with the `getTokenInfo` method. const tokenInfo = await oAuth2Client.getTokenInfo( oAuth2Client.credentials.access_token ); console.log(tokenInfo); } /** * Create a new OAuth2Client, and go through the OAuth2 content * workflow. Return the full client to the callback. */ function getAuthenticatedClient() { return new Promise((resolve, reject) => { // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file, // which should be downloaded from the Google Developers Console. const oAuth2Client = new OAuth2Client({ clientId: keys.web.client_id, clientSecret: keys.web.client_secret, redirectUri: keys.web.redirect_uris[0] }); // Generate the url that will be used for the consent dialog. const authorizeUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/userinfo.profile', }); // Open an http server to accept the oauth callback. In this simple example, the // only request to our webserver is to /oauth2callback?code= const server = http .createServer(async (req, res) => { try { if (req.url.indexOf('/oauth2callback') > -1) { // acquire the code from the querystring, and close the web server. const qs = new url.URL(req.url, 'http://localhost:3000') .searchParams; const code = qs.get('code'); console.log(`Code is ${code}`); res.end('Authentication successful! Please return to the console.'); server.destroy(); // Now that we have the code, use that to acquire tokens. const r = await oAuth2Client.getToken(code); // Make sure to set the credentials on the OAuth2 client. oAuth2Client.setCredentials(r.tokens); console.info('Tokens acquired.'); resolve(oAuth2Client); } } catch (e) { reject(e); } }) .listen(3000, () => { // open the browser to the authorize url to start the workflow open(authorizeUrl, {wait: false}).then(cp => cp.unref()); }); destroyer(server); }); } main().catch(console.error); ``` -------------------------------- ### Use google-proto-files in Node.js Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/nodejs-proto-files/README.md Demonstrates how to get proto paths and load proto files using the google-proto-files library. Use `protos.getProtoPath` to retrieve directory paths for specific API versions, and `protos.load` or `protos.loadSync` to load proto files. ```javascript const protos = require('google-proto-files'); async function quickstart() { // Get a directory path by executing as a function const files = protos.getProtoPath('logging', 'v2'); console.log(files); // node_modules/google-proto-files/google/logging/v2 // Get a path to the entry proto file for a specific API version console.log(protos.pubsub.v1); // node_modules/google-proto-files/google/pubsub/v1/pubsub.proto // Load a proto which depends on google common protos. const root1 = await protos.load('./cloudcats.proto'); const service1 = root1.lookup('example.MyService'); console.log(service1); // Load protos synchronously const root2 = protos.loadSync('./cloudcats.proto'); const service2 = root2.lookup('example.MyService'); console.log(service2); } quickstart(); ``` -------------------------------- ### Basic GET Request with Callback (TypeScript) Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/teeny-request/README.md Shows how to perform a GET request in TypeScript, including type annotations for the callback parameters. Requires '@types/request' for type declarations. ```typescript import {teenyRequest as request} from 'teeny-request'; import * as r from 'request'; // Only for type declarations request({uri: 'http://ip.jsontest.com/'}, (error: any, response: r.Response, body: any) => { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the JSON. }); ``` -------------------------------- ### Compile Code with Bazel Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md Compile the project using Bazel. This command is used if Bazel is installed and configured for the project. ```sh bazel build //... ``` -------------------------------- ### Generate SAML Config from URL Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Use this command to generate a SAML configuration file when the SAML assertion is sourced from a URL. The URL must host a GET endpoint that returns the SAML assertion. Additional headers can be specified. ```bash # Generate a SAML configuration file for file-sourced credentials. gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ --credential-source-url=$URL_TO_GET_SAML_ASSERTION \ --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file=/path/to/generated/config.json ``` -------------------------------- ### Make HTTP Requests with gaxios Source: https://context7.com/googleapis/google-cloud-node-core/llms.txt Use `gaxios.request` for simple GET requests with automatic JSON parsing. For POST requests, include a method, headers, and data. The `instance.fetch` method provides a fetch-compatible API without automatic parsing. ```javascript import { request, Gaxios } from 'gaxios'; // Simple GET with automatic JSON parsing const res = await request({ url: 'https://httpbin.org/json' }); console.log(res.data); // parsed JSON object console.log(res.status); // 200 // POST with body, custom headers, and timeout const postRes = await request({ url: 'https://httpbin.org/post', method: 'POST', headers: new Headers({ 'X-Custom': 'value' }), data: { key: 'value' }, timeout: 5000, }); console.log(postRes.data.json); // { key: 'value' } // fetch-compatible API import { instance } from 'gaxios'; const fetchRes = await instance.fetch('https://httpbin.org/get'); // No auto-parsed .data — use responseType or .adapter to control ``` ```javascript // Custom instance with defaults + retry config const client = new Gaxios(); client.defaults = { baseURL: 'https://api.example.com', headers: new Headers({ Authorization: 'Bearer TOKEN' }), retryConfig: { retry: 3, httpMethodsToRetry: ['GET', 'POST'], statusCodesToRetry: [[429, 429], [500, 599]], retryDelay: 200, onRetryAttempt: err => console.warn('Retrying...', err.message), }, }; try { const data = await client.request({ url: '/v1/resources' }); console.log(data.data); } catch (err) { // GaxiosError with .response, .config, .code console.error(err.message); } ``` ```javascript // Streaming response const stream = await request({ url: 'https://httpbin.org/stream/3', responseType: 'stream', }); // stream.data is a ReadableStream (native fetch) or stream.Readable (node-fetch) ``` ```javascript // Multipart upload const upload = await request({ url: 'https://example.com/upload', method: 'POST', multipart: [ { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'file' }) }, { headers: { 'Content-Type': 'image/png' }, body: fs.createReadStream('./photo.png') }, ], }); ``` -------------------------------- ### Generate OIDC Config from URL Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Use this command to generate an OIDC configuration file when the OIDC token is sourced from a URL. The URL must host a GET endpoint that returns the OIDC token. Additional headers can be specified. ```bash # Generate an OIDC configuration file for URL-sourced credentials. gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file=/path/to/generated/config.json ``` -------------------------------- ### Run Credentials Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the sample demonstrating credential management. ```bash node samples/credentials.js ``` -------------------------------- ### Run Authenticate API Key Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the sample for authenticating with an API key. ```bash node samples/authenticateAPIKey.js ``` -------------------------------- ### Run Compute Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the sample for Compute Engine service account authentication. ```bash node samples/compute.js ``` -------------------------------- ### Run ADC Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the Application Default Credentials (ADC) sample. ```bash node samples/adc.js ``` -------------------------------- ### Install and Test Packages with `packNTest` Source: https://context7.com/googleapis/google-cloud-node-core/llms.txt Use `packNTest` to package your npm module into a tarball, install it in a temporary directory with dependencies, and run code against it. This is useful for CI to verify installation and compilation from a published tarball, catching issues like missing files or type errors. ```javascript const { packNTest } = require('pack-n-play'); // In your test suite (e.g., Mocha/Jest) describe('installation smoke test', () => { it('works as CommonJS', async () => { await packNTest({ sample: { description: 'CJS require test', cjs: ' const myLib = require(\'my-library\'); if (!myLib.MyClass) throw new Error(\'MyClass not exported\'); console.log(\'CJS import OK\'); ', dependencies: [], // extra npm deps for the sample }, }); }); it('works as ESM', async () => { await packNTest({ sample: { description: 'ESM import test', esm: ' import { MyClass } from \'my-library\'; const instance = new MyClass({ option: \'value\' }); console.log(\'ESM import OK\'); ', }, }); }); it('works with TypeScript', async () => { await packNTest({ sample: { description: 'TypeScript type-check test', ts: ' import { MyClass } from \'my-library\'; const x: MyClass = new MyClass(); x.doSomething(); ', devDependencies: ['@types/node'], }, }); }); it('works from a specific directory', async () => { await packNTest({ packageDir: '/path/to/my-package', sample: { description: 'Test specific package dir', js: 'require(\'my-library\').someFunction();', }, }); }); }); ``` -------------------------------- ### Run Sample Integration Tests with npm Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/CONTRIBUTING.md Use this command to run sample integration tests for the project. ```bash # Run sample integration tests. npm run samples-test ``` -------------------------------- ### Run Authenticate Explicit Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the sample for explicit authentication. ```bash node samples/authenticateExplicit.js ``` -------------------------------- ### Install legacy version for Node.js 8 Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/nodejs-googleapis-common/README.md Install a legacy version of googleapis-common compatible with Node.js 8 using npm dist-tags. This is useful if you are working with older Node.js runtimes. ```bash npm install googleapis-common@legacy-8 ``` -------------------------------- ### Basic GET Request with Callback (JavaScript) Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/teeny-request/README.md Demonstrates a simple GET request to an API endpoint using a callback function to handle the response. This is the primary way to use teeny-request for basic HTTP operations. ```javascript const request = require('teeny-request').teenyRequest; request({uri: 'http://ip.jsontest.com/'}, function (error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the JSON. }); ``` -------------------------------- ### Run Authenticate Implicit With Adc Sample Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/samples/README.md Execute the sample for implicit authentication with Application Default Credentials (ADC). ```bash node samples/authenticateImplicitWithAdc.js ``` -------------------------------- ### packNTest(options) — Pack a Package and Run Code Against It Source: https://context7.com/googleapis/google-cloud-node-core/llms.txt Packages the current npm module into a tarball, installs it into a temporary directory with specified dependencies, and executes a code sample against it. This is used to ensure a library installs and compiles correctly from its published tarball. ```APIDOC ## `packNTest(options)` — Pack a Package and Run Code Against It Packages the current npm module into a tarball, installs it into a fresh temporary directory alongside specified dependencies, and executes a code sample against it. Used in CI to ensure a library installs and compiles correctly from the published tarball (catches missing files, type errors, ESM/CJS compatibility issues). ### Usage ```js const { packNTest } = require('pack-n-play'); // In your test suite (e.g., Mocha/Jest) describe('installation smoke test', () => { it('works as CommonJS', async () => { await packNTest({ sample: { description: 'CJS require test', cjs: ` const myLib = require('my-library'); if (!myLib.MyClass) throw new Error('MyClass not exported'); console.log('CJS import OK'); `, dependencies: [], // extra npm deps for the sample }, }); }); it('works as ESM', async () => { await packNTest({ sample: { description: 'ESM import test', esm: ` import { MyClass } from 'my-library'; const instance = new MyClass({ option: 'value' }); console.log('ESM import OK'); `, }, }); }); it('works with TypeScript', async () => { await packNTest({ sample: { description: 'TypeScript type-check test', ts: ` import { MyClass } from 'my-library'; const x: MyClass = new MyClass(); x.doSomething(); `, devDependencies: ['@types/node'], }, }); }); it('works from a specific directory', async () => { await packNTest({ packageDir: '/path/to/my-package', sample: { description: 'Test specific package dir', js: `require('my-library').someFunction();`, }, }); }); }); ``` ``` -------------------------------- ### Access Metadata with Custom Headers Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gcp-metadata/README.md Make metadata requests with custom headers, for example, to disable tracing. ```javascript await gcpMetadata.instance({ headers: { 'no-trace': '1' } }); // ...Request is untraced ``` -------------------------------- ### Run Tests Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/nodejs-proto-files/CONTRIBUTING.md Execute this command to run the project's test suite. ```bash npm test ``` -------------------------------- ### Long-Running Operations Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Explains how to handle long-running operations, including getting the result, checking status, and cancelling operations. ```APIDOC ## Long-Running Operations ### Initiating a Long-Running Operation ```ts const [operation] = await client.sampleLongRunningMethod(request); ``` ### Getting the Operation Result ```ts const [response] = await operation.promise(); ``` ### Checking Operation Status and Metadata ```ts console.log(operation.name); console.log(operation.done); console.log(operation.metadata); console.log(operation.result); ``` ### Cancelling a Long-Running Operation ```ts operation.cancel(); ``` ### Overriding Call Options for Long-Running Operations ```ts const [operation] = await client.sampleLongRunningMethod(request, options); ``` ### Tracking Operation Progress by Name ```ts const operation = await checkSampleLongRunningMethodProgress(operationName); // now check `operation.done`, `operation.metadata`, `operation.result` ``` ``` -------------------------------- ### Regular Methods Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Demonstrates the usage of regular API methods with async/await and promises, including how to cancel calls and override call options. ```APIDOC ## Regular Methods ### Usage with `async`/`await` ```ts const [response] = await client.sampleMethod(request); ``` ### Usage with Promises ```ts client.doStuff(request).then(([response]) => { /* handle response */ }); ``` ### Cancelling API Calls ```ts const promise = client.sampleMethod(request); promise.cancel(); ``` ### Overriding Call Options ```ts const [response] = await client.sampleMethod(request, options); ``` ``` -------------------------------- ### Get Result of a Long-Running Operation Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Retrieve the final result of a long-running operation by awaiting its promise. This will poll the operation until it completes. ```typescript const [response] = await operation.promise(); // polls the operation until complete ``` -------------------------------- ### Configuring Client with Authentication Options Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Specify authentication credentials, email, key file path, or project ID when creating a client instance. Refer to google-auth-library for a full list of GoogleAuthOptions. ```typescript const options = { credentials: { client_email: "YOUR_CLIENT_EMAIL", private_key: "YOUR_PRIVATE_KEY" }, email: "YOUR_ACCOUNT_EMAIL", keyFilename: "/path/to/your/keyfile.json", projectId: "YOUR_PROJECT_ID" }; const client = new library.SampleClient(options); ``` -------------------------------- ### Initiate a Long-Running Operation Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Start a long-running operation and receive an `Operation` object. This object can be used to track the operation's status. ```typescript const [operation] = await client.sampleLongRunningMethod(request); ``` -------------------------------- ### Add jsdoc-region-tag Plugin to JSDoc Configuration Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/jsdoc-region-tag/README.md Configure your JSDoc setup to include the jsdoc-region-tag plugin by adding it to the plugins array in your .jsdoc.js file. ```javascript module.exports = { plugins: [ 'jsdoc-region-tag' ] } ``` -------------------------------- ### Creating a Default Client Instance Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Instantiate a client for a Google Cloud library with default settings. The library automatically determines credentials and uses gRPC transport. ```typescript const client = new library.SampleClient(); ``` -------------------------------- ### Create and Use a Logger Instance Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/logging-utils/README.md Create a logger for a specific system and use it to log messages with optional metadata and formatting. ```javascript const logger = log('test'); logger({other:{metadata: 'foo'}}, 'format string %j', {formatted: 'parameter'}); ``` -------------------------------- ### Get Token Information Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Retrieve information about an access token, such as its expiration date, original scopes, or audience. This method throws an error if the token is invalid. ```javascript // after acquiring an oAuth2Client... const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); // take a look at the scopes originally provisioned for the access token console.log(tokenInfo.scopes); ``` -------------------------------- ### Download Proto Definitions Source: https://github.com/googleapis/google-cloud-node-core/blob/main/generator/gapic-generator-typescript/README.md Download the proto files locally for use with the generator. This command is for Linux or macOS. ```sh $ curl -L https://github.com/googleapis/gapic-showcase/releases/download/v0.6.1/gapic-showcase-0.6.1-protos.tar.gz | tar xz ``` -------------------------------- ### Server Streaming with EventEmitter Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Uses a `*Stream` method to get an `EventEmitter` that emits `data` events for each response element. Handles errors and completion events. ```ts const stream = await client.samplePaginatedMethodStream(request); stream.on('data', (response) => { /* process response */ }); stream.on('error', (err) => { /* handle error */ }); stream.on('end', () => { /* API call completed */ }); ``` -------------------------------- ### Creating a Client Instance with Constructor Options Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Pass custom options to the client constructor to configure its behavior. This allows for setting authentication, service endpoints, or client configurations. ```typescript const options = {}; // set options const client = new library.SampleClient(options); ``` -------------------------------- ### Fetch ID Token for IAP Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Fetch an ID token for accessing protected Identity-Aware Proxy (IAP) resources. Pass the Client ID used during setup as the target audience. ```javascript // Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource const {GoogleAuth} = require('google-auth-library'); const targetAudience = 'iap-client-id'; const url = 'https://iap-url.com'; const auth = new GoogleAuth(); const client = await auth.getIdTokenClient(targetAudience); const res = await client.fetch(url); console.log(res.data); ``` -------------------------------- ### Run System Tests with npm Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/CONTRIBUTING.md Execute all system tests for the project with this npm command. ```bash # Run all system tests. npm run system-test ``` -------------------------------- ### Gaxios Instance with Defaults Source: https://context7.com/googleapis/google-cloud-node-core/llms.txt You can create a custom `Gaxios` instance with default configurations, including base URLs, headers, and retry logic. ```APIDOC ## Gaxios Instance ### Description Create a custom `Gaxios` instance with defaults for `baseURL`, `headers`, and `retryConfig`. This allows for consistent configuration across multiple requests. ### Method `new Gaxios()` ### Parameters - **options** (object, optional) - Configuration options for the instance. - **defaults** (object) - Default configuration to apply to requests made with this instance. - **baseURL** (string) - The base URL for requests. - **headers** (Headers) - Default headers to include in requests. - **retryConfig** (object) - Configuration for automatic retries. - **retry** (number) - The maximum number of retries. - **httpMethodsToRetry** (string[]) - HTTP methods to retry. - **statusCodesToRetry** (number[][]) - Status codes to retry. - **retryDelay** (number) - Delay between retries in milliseconds. - **onRetryAttempt** (function) - Callback function executed on each retry attempt. ### Request Example ```js import { Gaxios } from 'gaxios'; const client = new Gaxios(); client.defaults = { baseURL: 'https://api.example.com', headers: new Headers({ Authorization: 'Bearer TOKEN' }), retryConfig: { retry: 3, httpMethodsToRetry: ['GET', 'POST'], statusCodesToRetry: [[429, 429], [500, 599]], retryDelay: 200, onRetryAttempt: err => console.warn('Retrying...', err.message), }, }; try { const data = await client.request({ url: '/v1/resources' }); console.log(data.data); } catch (err) { console.error(err.message); } ``` ### Response #### Success Response (200) - **data** (any) - The parsed response body. #### Response Example ```json { "data": { "example": "response data" } } ``` ``` -------------------------------- ### Add JSDoc Generate Script to package.json Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/jsdoc-fresh/README.md Add this script to your project's package.json to easily generate documentation using jsdoc-fresh. Ensure the path to the jsdoc executable is correct for your project setup. ```json { "script": { "generate-docs": "node_modules/.bin/jsdoc --configure .jsdoc.json --verbose" } } ``` -------------------------------- ### Configure Executable-Sourced Credentials Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Use this command to generate a configuration file for executable-sourced credentials. Substitute the placeholder variables with your specific project and pool details. The `--executable-command` is mandatory and must be an absolute path to the program. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account=$SERVICE_ACCOUNT_EMAIL \ --subject-token-type=$SUBJECT_TOKEN_TYPE \ --executable-command=$EXECUTABLE_COMMAND \ --output-file /path/to/generated/config.json ``` -------------------------------- ### Initializing and Authenticating a Client Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/client-libraries.md Force client initialization and authentication immediately after creation to ensure the client is ready for the first request. ```typescript const client = new library.SampleClient(); await client.initialize(); // performs auth ``` -------------------------------- ### Run Unit Tests with npm Source: https://github.com/googleapis/google-cloud-node-core/blob/main/dev-packages/pack-n-play/CONTRIBUTING.md Execute unit tests for the project using this npm script. ```bash # Run unit tests. npm test ``` -------------------------------- ### Initialize ExternalAccountClient from JSON Configuration Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Initialize an ExternalAccountClient directly from a JSON configuration file. Ensure the client's scopes are set appropriately. ```javascript const {ExternalAccountClient} = require('google-auth-library'); const jsonConfig = require('/path/to/config.json'); const client = ExternalAccountClient.fromJSON(jsonConfig); client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; // List all buckets in a project. const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; const res = await client.fetch(url); console.log(res.data); ``` -------------------------------- ### Add Prefetch Script to package.json Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gax/test/README.md Add this 'prefetch' script to the scripts section of your package.json file. Ensure it is added in alphabetical order with existing scripts. ```json "prefetch": "rm -rf node_modules package-lock.json google-gax*.tgz gapic-tools*.tgz && cd ../.. && npm pack && mv google-gax*.tgz test/showcase-echo-client/google-gax.tgz && cd ../tools && npm install && npm pack && mv gapic-tools*.tgz ../gax/test/showcase-echo-client/gapic-tools.tgz" ``` -------------------------------- ### Automatically Choose Credential Type with GoogleAuth Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Instantiate GoogleAuth to automatically select the correct client type (JWT, OAuth2, Compute) based on the environment. Specify scopes if needed. This example demonstrates fetching a project ID and making an authenticated request to the DNS API. ```javascript const {GoogleAuth} = require('google-auth-library'); /** * Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc) * this library will automatically choose the right client based on the environment. */ const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const projectId = await auth.getProjectId(); const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; // The modern `fetch` and classic `request` APIs are available const res = await auth.fetch(url); console.log(res.data); ``` -------------------------------- ### Generate Credential Config (Default Behavior) Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/google-auth-library-nodejs/README.md Use this command to generate X.509 credential configuration files. The certificate configuration file will be created at a default location discoverable by client libraries. Substitute placeholders with your specific project details. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --output-file /path/to/config.json ``` -------------------------------- ### Fetch-Compatible API with gaxios Source: https://github.com/googleapis/google-cloud-node-core/blob/main/packages/gaxios/README.md Utilize the `fetch` compatible API provided by gaxios using the `instance.fetch` method. This allows for a familiar fetch interface. ```js import {instance} from 'gaxios'; const res = await instance.fetch('https://google.com/'); ```