From faa885f706a28605ff05eadf4cfc4c3acc331da4 Mon Sep 17 00:00:00 2001 From: Megan Potter <57276408+feywind@users.noreply.github.com> Date: Fri, 17 Feb 2023 16:06:20 -0500 Subject: [PATCH] samples: add more TS samples (#1666) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * samples: work in progress on sample conversion to TS * chore: Enable requesting numeric enums in "transport=rest" responses for services supporting this (Java, Go, Python, PHP, TypeScript, C#, and Ruby), even if they do not yet turn on REST transport (#1663) * chore: Enable requesting numeric enums in "transport=rest" responses for services supporting this (Java, Go, Python, PHP, TypeScript, C#, and Ruby), even if they do not yet turn on REST transport chore: disallow "transport=rest" for services where numeric enums are not confirmed to be supported (except in PHP and Java) PiperOrigin-RevId: 493113566 Source-Link: https://github.com/googleapis/googleapis/commit/758f0d1217d9c7fe398aa5efb1057ce4b6409e55 Source-Link: https://github.com/googleapis/googleapis-gen/commit/78bd8f05e1276363eb14eae70e91fe4bc20703ab Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNzhiZDhmMDVlMTI3NjM2M2ViMTRlYWU3MGU5MWZlNGJjMjA3MDNhYiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot Co-authored-by: Megan Potter <57276408+feywind@users.noreply.github.com> * build: use typeless bot 1.2.0 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * build: also run fix before README generation * samples: add missing validateSchema.ts, and fix copyright dates in setTopicPolicy * build: use hermetic version of gts for owlbot * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: update copyright * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: manually update validateSchema since it's not technically sample snippet * chore: update typeless bot version * chore: linting updates * samples: update module export method for resumePublish.ts * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: gcf-owl-bot[bot] <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Owl Bot --- README.md | 3 +- owlbot.py | 20 ++- samples/README.md | 20 +++ samples/createAvroSchema.js | 4 + samples/createBigQuerySubscription.js | 80 +++++---- samples/createProtoSchema.js | 4 + samples/createPushSubscription.js | 69 ++++---- samples/createSubscription.js | 57 +++--- .../createSubscriptionWithDeadLetterPolicy.js | 89 ++++++---- ...eateSubscriptionWithExactlyOnceDelivery.js | 4 + samples/createSubscriptionWithFiltering.js | 4 + samples/createSubscriptionWithOrdering.js | 81 +++++---- samples/createTopic.js | 56 +++--- samples/createTopicWithSchema.js | 4 + samples/deleteSchema.js | 4 + samples/deleteSubscription.js | 51 +++--- samples/deleteTopic.js | 53 +++--- samples/detachSubscription.js | 69 ++++---- samples/getSchema.js | 4 + samples/getSubscriptionPolicy.js | 49 +++--- samples/getTopicPolicy.js | 51 +++--- samples/listAllTopics.js | 45 ++--- samples/listSchemas.js | 4 + samples/listSubscriptions.js | 36 ++-- samples/listTopicSubscriptions.js | 59 ++++--- samples/listenForAvroRecords.js | 4 + samples/listenForErrors.js | 97 +++++----- samples/listenForMessages.js | 88 +++++----- ...istenForMessagesWithExactlyOnceDelivery.js | 4 + samples/listenForProtobufMessages.js | 4 + samples/listenWithCustomAttributes.js | 88 +++++----- samples/modifyPushConfig.js | 69 ++++---- samples/publishAvroRecords.js | 4 + samples/publishBatchedMessages.js | 96 ++++++---- samples/publishMessage.js | 76 ++++---- samples/publishMessageWithCustomAttributes.js | 66 +++---- samples/publishOrderedMessage.js | 95 +++++----- samples/publishProtobufMessages.js | 4 + samples/publishWithFlowControl.js | 4 + samples/publishWithRetrySettings.js | 166 +++++++++--------- samples/quickstart.js | 6 +- samples/removeDeadLetterPolicy.js | 67 +++---- samples/resumePublish.js | 93 +++++----- samples/setSubscriptionPolicy.js | 79 +++++---- samples/setTopicPolicy.js | 79 +++++---- samples/subscribeWithFlowControlSettings.js | 120 +++++++------ samples/synchronousPull.js | 105 +++++------ .../synchronousPullWithDeliveryAttempts.js | 108 +++++++----- samples/testSubscriptionPermissions.js | 67 +++---- samples/testTopicPermissions.js | 69 ++++---- .../typescript/createBigQuerySubscription.ts | 77 ++++++++ samples/typescript/createPushSubscription.ts | 70 ++++++++ samples/typescript/createSubscription.ts | 63 +++++++ .../createSubscriptionWithDeadLetterPolicy.ts | 81 +++++++++ .../createSubscriptionWithOrdering.ts | 72 ++++++++ samples/typescript/createTopic.ts | 54 ++++++ samples/typescript/deleteSubscription.ts | 54 ++++++ samples/typescript/deleteTopic.ts | 59 +++++++ samples/typescript/detachSubscription.ts | 65 +++++++ samples/typescript/getSubscription.ts | 58 ++++++ samples/typescript/getSubscriptionPolicy.ts | 57 ++++++ samples/typescript/getTopicPolicy.ts | 56 ++++++ samples/typescript/listAllTopics.ts | 50 ++++++ samples/typescript/listSubscriptions.ts | 49 ++++++ samples/typescript/listTopicSubscriptions.ts | 60 +++++++ samples/typescript/listenForErrors.ts | 81 +++++++++ samples/typescript/listenForMessages.ts | 78 ++++++++ .../typescript/listenWithCustomAttributes.ts | 79 +++++++++ samples/typescript/modifyPushConfig.ts | 69 ++++++++ samples/typescript/publishBatchedMessages.ts | 91 ++++++++++ samples/typescript/publishMessage.ts | 71 ++++++++ .../publishMessageWithCustomAttributes.ts | 72 ++++++++ samples/typescript/publishOrderedMessage.ts | 90 ++++++++++ .../typescript/publishWithRetrySettings.ts | 122 +++++++++++++ samples/typescript/quickstart.ts | 60 +++++++ samples/typescript/removeDeadLetterPolicy.ts | 70 ++++++++ samples/typescript/resumePublish.ts | 90 ++++++++++ samples/typescript/setSubscriptionPolicy.ts | 73 ++++++++ samples/typescript/setTopicPolicy.ts | 72 ++++++++ .../subscribeWithFlowControlSettings.ts | 102 +++++++++++ samples/typescript/synchronousPull.ts | 96 ++++++++++ .../synchronousPullWithDeliveryAttempts.ts | 96 ++++++++++ .../typescript/testSubscriptionPermissions.ts | 62 +++++++ samples/typescript/testTopicPermissions.ts | 63 +++++++ samples/typescript/updateDeadLetterPolicy.ts | 71 ++++++++ samples/typescript/validateSchema.ts | 82 +++++++++ samples/updateDeadLetterPolicy.js | 69 ++++---- samples/validateSchema.js | 86 +++++++++ 88 files changed, 4161 insertions(+), 1187 deletions(-) create mode 100644 samples/typescript/createBigQuerySubscription.ts create mode 100644 samples/typescript/createPushSubscription.ts create mode 100644 samples/typescript/createSubscription.ts create mode 100644 samples/typescript/createSubscriptionWithDeadLetterPolicy.ts create mode 100644 samples/typescript/createSubscriptionWithOrdering.ts create mode 100644 samples/typescript/createTopic.ts create mode 100644 samples/typescript/deleteSubscription.ts create mode 100644 samples/typescript/deleteTopic.ts create mode 100644 samples/typescript/detachSubscription.ts create mode 100644 samples/typescript/getSubscription.ts create mode 100644 samples/typescript/getSubscriptionPolicy.ts create mode 100644 samples/typescript/getTopicPolicy.ts create mode 100644 samples/typescript/listAllTopics.ts create mode 100644 samples/typescript/listSubscriptions.ts create mode 100644 samples/typescript/listTopicSubscriptions.ts create mode 100644 samples/typescript/listenForErrors.ts create mode 100644 samples/typescript/listenForMessages.ts create mode 100644 samples/typescript/listenWithCustomAttributes.ts create mode 100644 samples/typescript/modifyPushConfig.ts create mode 100644 samples/typescript/publishBatchedMessages.ts create mode 100644 samples/typescript/publishMessage.ts create mode 100644 samples/typescript/publishMessageWithCustomAttributes.ts create mode 100644 samples/typescript/publishOrderedMessage.ts create mode 100644 samples/typescript/publishWithRetrySettings.ts create mode 100644 samples/typescript/quickstart.ts create mode 100644 samples/typescript/removeDeadLetterPolicy.ts create mode 100644 samples/typescript/resumePublish.ts create mode 100644 samples/typescript/setSubscriptionPolicy.ts create mode 100644 samples/typescript/setTopicPolicy.ts create mode 100644 samples/typescript/subscribeWithFlowControlSettings.ts create mode 100644 samples/typescript/synchronousPull.ts create mode 100644 samples/typescript/synchronousPullWithDeliveryAttempts.ts create mode 100644 samples/typescript/testSubscriptionPermissions.ts create mode 100644 samples/typescript/testTopicPermissions.ts create mode 100644 samples/typescript/updateDeadLetterPolicy.ts create mode 100644 samples/typescript/validateSchema.ts create mode 100644 samples/validateSchema.js diff --git a/README.md b/README.md index fc893e079..a475d792c 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ async function quickstart( }); // Send a message to the topic - topic.publish(Buffer.from('Test message!')); + topic.publishMessage({data: Buffer.from('Test message!')}); } ``` @@ -174,6 +174,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/nodejs-pubsub/tree | Test Subscription Permissions | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/testSubscriptionPermissions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/testSubscriptionPermissions.js,samples/README.md) | | Test Topic Permissions | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/testTopicPermissions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/testTopicPermissions.js,samples/README.md) | | Update Dead Letter Policy | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/updateDeadLetterPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/updateDeadLetterPolicy.js,samples/README.md) | +| Validate a schema definition | [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/validateSchema.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/validateSchema.js,samples/README.md) | diff --git a/owlbot.py b/owlbot.py index c0dc44db3..5e65c6ad7 100644 --- a/owlbot.py +++ b/owlbot.py @@ -17,19 +17,31 @@ # This code snippet can be used to manually update the typeless bot # to a different version than OwlBot has baked in, but this shouldn't # be needed once it's settled down. -""" import os from synthtool import shell from synthtool.log import logger old_path = os.getcwd() os.chdir("/synthtool") -logger.debug("Update typeless sample bot [1.1.0]") -shell.run(["npm", "i", "@google-cloud/typeless-sample-bot@1.1.0"]) +logger.debug("Update typeless sample bot [1.3.0]") +shell.run(["npm", "i", "@google-cloud/typeless-sample-bot@1.3.0"]) os.chdir(old_path) -""" node.typeless_samples_hermetic() +# We need to run this before the main owlbot processing, to make +# sure quickstart.js gets gts fixed before the README is generated. +# This needs to be worked out more properly, this is temporary. +logger.debug("Copy eslint config") +shell.run( + ["cp", "-r", f"/synthtool/node_modules", "."], + check=True, +) +logger.debug("Running fix...") +shell.run( + [f"/synthtool/node_modules/.bin/gts", "fix"], + check=False, +) + node.owlbot_main(templates_excludes=[ 'src/index.ts', '.github/PULL_REQUEST_TEMPLATE.md', diff --git a/samples/README.md b/samples/README.md index 111c5dc73..de1a34f62 100644 --- a/samples/README.md +++ b/samples/README.md @@ -71,6 +71,7 @@ guides. * [Test Subscription Permissions](#test-subscription-permissions) * [Test Topic Permissions](#test-topic-permissions) * [Update Dead Letter Policy](#update-dead-letter-policy) + * [Validate a schema definition](#validate-a-schema-definition) ## Before you begin @@ -1051,6 +1052,25 @@ __Usage:__ `node updateDeadLetterPolicy.js ` +----- + + + + +### Validate a schema definition + +Validates an Avro-based schema definition before creation (or other use). + +View the [source code](https://github.com/googleapis/nodejs-pubsub/blob/main/samples/validateSchema.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-pubsub&page=editor&open_in_editor=samples/validateSchema.js,samples/README.md) + +__Usage:__ + + +`node validateSchema.js ` + + diff --git a/samples/createAvroSchema.js b/samples/createAvroSchema.js index 81bd92362..5de29cd4d 100644 --- a/samples/createAvroSchema.js +++ b/samples/createAvroSchema.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/createBigQuerySubscription.js b/samples/createBigQuerySubscription.js index ec51f3d6b..fc1da43dc 100644 --- a/samples/createBigQuerySubscription.js +++ b/samples/createBigQuerySubscription.js @@ -1,4 +1,4 @@ -// Copyright 2019-2022 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,48 +24,58 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create BigQuery Subscription // description: Creates a new BigQuery subscription. // usage: node createBigQuerySubscription.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - bigqueryTableId = 'YOUR_TABLE_ID' -) { - // [START pubsub_create_bigquery_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const bigqueryTableId = 'YOUR_TABLE_ID'; +// [START pubsub_create_bigquery_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const bigqueryTableId = 'YOUR_TABLE_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function createBigQuerySubscription() { - const options = { - bigqueryConfig: { - table: bigqueryTableId, - writeMetadata: true, - }, - }; +async function createBigQuerySubscription( + topicNameOrId, + subscriptionNameOrId, + bigqueryTableId +) { + const options = { + bigqueryConfig: { + table: bigqueryTableId, + writeMetadata: true, + }, + }; - await pubSubClient - .topic(topicNameOrId) - .createSubscription(subscriptionNameOrId, options); - console.log(`Subscription ${subscriptionNameOrId} created.`); - } + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); - createBigQuerySubscription().catch(console.error); - // [END pubsub_create_bigquery_subscription] + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_bigquery_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + bigqueryTableId = 'YOUR_TABLE_ID' +) { + createBigQuerySubscription( + topicNameOrId, + subscriptionNameOrId, + bigqueryTableId + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/createProtoSchema.js b/samples/createProtoSchema.js index 0ceaa19b8..23fc341ba 100644 --- a/samples/createProtoSchema.js +++ b/samples/createProtoSchema.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/createPushSubscription.js b/samples/createPushSubscription.js index 3e78a2291..12afa91b5 100644 --- a/samples/createPushSubscription.js +++ b/samples/createPushSubscription.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,47 +24,48 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create Push Subscription // description: Creates a new push subscription. // usage: node createPushSubscription.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_create_push_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_create_push_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function createPushSubscription() { - const options = { - pushConfig: { - // Set to an HTTPS endpoint of your choice. If necessary, register - // (authorize) the domain on which the server is hosted. - pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, - }, - }; +async function createPushSubscription(topicNameOrId, subscriptionNameOrId) { + const options = { + pushConfig: { + // Set to an HTTPS endpoint of your choice. If necessary, register + // (authorize) the domain on which the server is hosted. + pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, + }, + }; - await pubSubClient - .topic(topicNameOrId) - .createSubscription(subscriptionNameOrId, options); - console.log(`Subscription ${subscriptionNameOrId} created.`); - } + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_push_subscription] - createPushSubscription().catch(console.error); - // [END pubsub_create_push_subscription] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + createPushSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/createSubscription.js b/samples/createSubscription.js index 6ef39db39..d0424fbf4 100644 --- a/samples/createSubscription.js +++ b/samples/createSubscription.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to create subscriptions with the * Google Cloud Pub/Sub API. @@ -20,40 +24,41 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create Subscription // description: Creates a new subscription. // usage: node createSubscription.js +// [START pubsub_create_pull_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createSubscription(topicNameOrId, subscriptionNameOrId) { + // Creates a new subscription + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId); + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_pull_subscription] + function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' ) { - // [START pubsub_create_pull_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function createSubscription() { - // Creates a new subscription - await pubSubClient - .topic(topicNameOrId) - .createSubscription(subscriptionNameOrId); - console.log(`Subscription ${subscriptionNameOrId} created.`); - } - - createSubscription().catch(console.error); - // [END pubsub_create_pull_subscription] + createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/createSubscriptionWithDeadLetterPolicy.js b/samples/createSubscriptionWithDeadLetterPolicy.js index efaae35c4..5839ec0ca 100644 --- a/samples/createSubscriptionWithDeadLetterPolicy.js +++ b/samples/createSubscriptionWithDeadLetterPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,52 +24,63 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create Subscription With Dead Letter Policy // description: Creates a new subscription With Dead Letter Policy. // usage: node createSubscriptionWithDeadLetterPolicy.js +// [START pubsub_dead_letter_create_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createSubscriptionWithDeadLetterPolicy( + topicNameOrId, + subscriptionNameOrId, + deadLetterTopicNameOrId +) { + // Creates a new subscription + const options = { + deadLetterPolicy: { + deadLetterTopic: pubSubClient.topic(deadLetterTopicNameOrId).name, + maxDeliveryAttempts: 10, + }, + }; + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); + console.log( + `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.` + ); + + console.log( + 'To process dead letter messages, remember to add a subscription to your dead letter topic.' + ); +} +// [END pubsub_dead_letter_create_subscription] + function main( topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID' ) { - // [START pubsub_dead_letter_create_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function createSubscriptionWithDeadLetterPolicy() { - // Creates a new subscription - await pubSubClient - .topic(topicNameOrId) - .createSubscription(subscriptionNameOrId, { - deadLetterPolicy: { - deadLetterTopic: pubSubClient.topic(deadLetterTopicNameOrId).name, - maxDeliveryAttempts: 10, - }, - }); - console.log( - `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.` - ); - console.log( - 'To process dead letter messages, remember to add a subscription to your dead letter topic.' - ); - } - - createSubscriptionWithDeadLetterPolicy().catch(console.error); - // [END pubsub_dead_letter_create_subscription] + createSubscriptionWithDeadLetterPolicy( + topicNameOrId, + subscriptionNameOrId, + deadLetterTopicNameOrId + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/createSubscriptionWithExactlyOnceDelivery.js b/samples/createSubscriptionWithExactlyOnceDelivery.js index 089c2387e..f28c0df91 100644 --- a/samples/createSubscriptionWithExactlyOnceDelivery.js +++ b/samples/createSubscriptionWithExactlyOnceDelivery.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/createSubscriptionWithFiltering.js b/samples/createSubscriptionWithFiltering.js index bc0f98797..9fddeadeb 100644 --- a/samples/createSubscriptionWithFiltering.js +++ b/samples/createSubscriptionWithFiltering.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. diff --git a/samples/createSubscriptionWithOrdering.js b/samples/createSubscriptionWithOrdering.js index 141490ac7..92e432ca1 100644 --- a/samples/createSubscriptionWithOrdering.js +++ b/samples/createSubscriptionWithOrdering.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,51 +24,54 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create Subscription with ordering enabled // description: Creates a new subscription with ordering enabled. // usage: node createSubscriptionWithOrdering.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_enable_subscription_ordering] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_enable_subscription_ordering] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +async function createSubscriptionWithOrdering( + topicNameOrId, + subscriptionNameOrId +) { + // Creates a new subscription + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, { + enableMessageOrdering: true, + }); + console.log( + `Created subscription ${subscriptionNameOrId} with ordering enabled.` + ); - async function createSubscriptionWithOrdering() { - // Creates a new subscription - await pubSubClient - .topic(topicNameOrId) - .createSubscription(subscriptionNameOrId, { - enableMessageOrdering: true, - }); - console.log( - `Created subscription ${subscriptionNameOrId} with ordering enabled.` - ); - console.log( - 'To process messages in order, remember to add an ordering key to your messages.' - ); - } + console.log( + 'To process messages in order, remember to add an ordering key to your messages.' + ); +} +// [END pubsub_enable_subscription_ordering] - createSubscriptionWithOrdering().catch(console.error); - // [END pubsub_enable_subscription_ordering] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + createSubscriptionWithOrdering(topicNameOrId, subscriptionNameOrId).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); } -process.on('unhandledRejection', err => { - console.error(err.message); - process.exitCode = 1; -}); main(...process.argv.slice(2)); diff --git a/samples/createTopic.js b/samples/createTopic.js index 0bf2da314..fe5308366 100644 --- a/samples/createTopic.js +++ b/samples/createTopic.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,37 +24,35 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Create Topic // description: Creates a new topic. // usage: node createTopic.js +// [START pubsub_create_topic] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createTopic(topicNameOrId) { + // Creates a new topic + await pubSubClient.createTopic(topicNameOrId); + console.log(`Topic ${topicNameOrId} created.`); +} +// [END pubsub_create_topic] + async function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_create_topic] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function createTopic() { - // Creates a new topic - await pubSubClient.createTopic(topicNameOrId); - console.log(`Topic ${topicNameOrId} created.`); - } - - createTopic(); - // [END pubsub_create_topic] + createTopic(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -main(...process.argv.slice(2)).catch(e => { - console.error(e); - process.exitCode = -1; -}); +main(...process.argv.slice(2)); diff --git a/samples/createTopicWithSchema.js b/samples/createTopicWithSchema.js index 5f07aa206..7639fc432 100644 --- a/samples/createTopicWithSchema.js +++ b/samples/createTopicWithSchema.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. diff --git a/samples/deleteSchema.js b/samples/deleteSchema.js index d23937f28..8fad88224 100644 --- a/samples/deleteSchema.js +++ b/samples/deleteSchema.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/deleteSubscription.js b/samples/deleteSubscription.js index 15624197c..5dd30682a 100644 --- a/samples/deleteSubscription.js +++ b/samples/deleteSubscription.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,34 +24,35 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Delete Subscription // description: Deletes an existing subscription from a topic. // usage: node deleteSubscription.js +// [START pubsub_delete_subscription] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function deleteSubscription(subscriptionNameOrId) { + // Deletes the subscription + await pubSubClient.subscription(subscriptionNameOrId).delete(); + console.log(`Subscription ${subscriptionNameOrId} deleted.`); +} +// [END pubsub_delete_subscription] + function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { - // [START pubsub_delete_subscription] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function deleteSubscription() { - // Deletes the subscription - await pubSubClient.subscription(subscriptionNameOrId).delete(); - console.log(`Subscription ${subscriptionNameOrId} deleted.`); - } - - deleteSubscription().catch(console.error); - // [END pubsub_delete_subscription] + deleteSubscription(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/deleteTopic.js b/samples/deleteTopic.js index 37381c85a..69f8419c7 100644 --- a/samples/deleteTopic.js +++ b/samples/deleteTopic.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,39 +24,40 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Delete Topic // description: Deletes an existing topic. // usage: node deleteTopic.js -function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_delete_topic] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// [START pubsub_delete_topic] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function deleteTopic() { - /** - * TODO(developer): Uncomment the following line to run the sample. - */ - // const topicName = 'my-topic'; +async function deleteTopic(topicNameOrId) { + /** + * TODO(developer): Uncomment the following line to run the sample. + */ + // const topicName = 'my-topic'; - // Deletes the topic - await pubSubClient.topic(topicNameOrId).delete(); - console.log(`Topic ${topicNameOrId} deleted.`); - } + // Deletes the topic + await pubSubClient.topic(topicNameOrId).delete(); + console.log(`Topic ${topicNameOrId} deleted.`); +} +// [END pubsub_delete_topic] - deleteTopic().catch(console.error); - // [END pubsub_delete_topic] +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + deleteTopic(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/detachSubscription.js b/samples/detachSubscription.js index 9ed3ab481..14b5c7bdc 100644 --- a/samples/detachSubscription.js +++ b/samples/detachSubscription.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to detach subscriptions with the * Google Cloud Pub/Sub API. @@ -20,51 +24,46 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Detach Subscription // description: Detaches a subscription from a topic. // usage: node detachSubscription.js -function main(subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID') { - // [START pubsub_detach_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_detach_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function detachSubscription() { - // Gets the status of the existing subscription - const sub = pubSubClient.subscription(subscriptionNameOrId); - const [detached] = await sub.detached(); - console.log( - `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}` - ); +async function detachSubscription(subscriptionNameOrId) { + // Gets the status of the existing subscription + const sub = pubSubClient.subscription(subscriptionNameOrId); + const [detached] = await sub.detached(); + console.log( + `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}` + ); - await pubSubClient.detachSubscription(subscriptionNameOrId); - console.log( - `Subscription ${subscriptionNameOrId} detach request was sent.` - ); + await pubSubClient.detachSubscription(subscriptionNameOrId); + console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`); - const [updatedDetached] = await sub.detached(); - console.log( - `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}` - ); - } + const [updatedDetached] = await sub.detached(); + console.log( + `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}` + ); +} +// [END pubsub_detach_subscription] - detachSubscription(); - // [END pubsub_detach_subscription] +function main(subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID') { + detachSubscription(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -process.on('unhandledRejection', err => { - console.error(err.message); - process.exitCode = 1; -}); main(...process.argv.slice(2)); diff --git a/samples/getSchema.js b/samples/getSchema.js index b7602ac1c..a2be2c32d 100644 --- a/samples/getSchema.js +++ b/samples/getSchema.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/getSubscriptionPolicy.js b/samples/getSubscriptionPolicy.js index 1ad46a065..23b1e64c8 100644 --- a/samples/getSubscriptionPolicy.js +++ b/samples/getSubscriptionPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,37 +24,38 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Get Subscription Policy // description: Gets the IAM policy for a subscription. // usage: node getSubscriptionPolicy.js -function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { - // [START pubsub_get_subscription_policy] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_get_subscription_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function getSubscriptionPolicy() { - // Retrieves the IAM policy for the subscription - const [policy] = await pubSubClient - .subscription(subscriptionNameOrId) - .iam.getPolicy(); +async function getSubscriptionPolicy(subscriptionNameOrId) { + // Retrieves the IAM policy for the subscription + const [policy] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.getPolicy(); - console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`); - } + console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`); +} +// [END pubsub_get_subscription_policy] - getSubscriptionPolicy().catch(console.error); - // [END pubsub_get_subscription_policy] +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + getSubscriptionPolicy(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/getTopicPolicy.js b/samples/getTopicPolicy.js index 832c6aad6..43307c576 100644 --- a/samples/getTopicPolicy.js +++ b/samples/getTopicPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,34 +24,35 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Get Topic Policy // description: Gets the IAM policy for a topic. // usage: node getTopicPolicy.js +// [START pubsub_get_topic_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function getTopicPolicy(topicNameOrId) { + // Retrieves the IAM policy for the topic + const [policy] = await pubSubClient.topic(topicNameOrId).iam.getPolicy(); + console.log('Policy for topic: %j.', policy.bindings); +} +// [END pubsub_get_topic_policy] + function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_get_topic_policy] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function getTopicPolicy() { - // Retrieves the IAM policy for the topic - const [policy] = await pubSubClient.topic(topicNameOrId).iam.getPolicy(); - console.log('Policy for topic: %j.', policy.bindings); - } - - getTopicPolicy().catch(console.error); - // [END pubsub_get_topic_policy] + getTopicPolicy(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/listAllTopics.js b/samples/listAllTopics.js index 1e413bbde..faaf2903f 100644 --- a/samples/listAllTopics.js +++ b/samples/listAllTopics.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,30 +24,31 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: List All Topics // description: Lists all topics in the current project. // usage: node listAllTopics.js +// [START pubsub_list_topics] +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listAllTopics() { + // Lists all topics in the current project + const [topics] = await pubSubClient.getTopics(); + console.log('Topics:'); + topics.forEach(topic => console.log(topic.name)); +} +// [END pubsub_list_topics] + function main() { - // [START pubsub_list_topics] - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function listAllTopics() { - // Lists all topics in the current project - const [topics] = await pubSubClient.getTopics(); - console.log('Topics:'); - topics.forEach(topic => console.log(topic.name)); - } - - listAllTopics().catch(console.error); - // [END pubsub_list_topics] + listAllTopics().catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -main(...process.argv.slice(2)); +main(); diff --git a/samples/listSchemas.js b/samples/listSchemas.js index 32f06c7d1..d7d340041 100644 --- a/samples/listSchemas.js +++ b/samples/listSchemas.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/listSubscriptions.js b/samples/listSubscriptions.js index 0a268b5c7..df80fd150 100644 --- a/samples/listSubscriptions.js +++ b/samples/listSubscriptions.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,30 +24,28 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: List Subscriptions // description: Lists all subscriptions in the current project. // usage: node listSubscriptions.js -function main() { - // [START pubsub_list_subscriptions] - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// [START pubsub_list_subscriptions] +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function listSubscriptions() { - // Lists all subscriptions in the current project - const [subscriptions] = await pubSubClient.getSubscriptions(); - console.log('Subscriptions:'); - subscriptions.forEach(subscription => console.log(subscription.name)); - } +async function listSubscriptions() { + // Lists all subscriptions in the current project + const [subscriptions] = await pubSubClient.getSubscriptions(); + console.log('Subscriptions:'); + subscriptions.forEach(subscription => console.log(subscription.name)); +} +// [END pubsub_list_subscriptions] +function main() { listSubscriptions().catch(console.error); - // [END pubsub_list_subscriptions] } -main(...process.argv.slice(2)); +main(); diff --git a/samples/listTopicSubscriptions.js b/samples/listTopicSubscriptions.js index 5a035bdd0..cd27e93a9 100644 --- a/samples/listTopicSubscriptions.js +++ b/samples/listTopicSubscriptions.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,38 +24,39 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: List Subscriptions On a Topic // description: Lists all subscriptions in the current project, filtering by a topic. // usage: node listTopicSubscriptions.js +// [START pubsub_list_topic_subscriptions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listTopicSubscriptions(topicNameOrId) { + // Lists all subscriptions for the topic + const [subscriptions] = await pubSubClient + .topic(topicNameOrId) + .getSubscriptions(); + + console.log(`Subscriptions for ${topicNameOrId}:`); + subscriptions.forEach(subscription => console.log(subscription.name)); +} +// [END pubsub_list_topic_subscriptions] + function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_list_topic_subscriptions] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function listTopicSubscriptions() { - // Lists all subscriptions for the topic - const [subscriptions] = await pubSubClient - .topic(topicNameOrId) - .getSubscriptions(); - - console.log(`Subscriptions for ${topicNameOrId}:`); - subscriptions.forEach(subscription => console.log(subscription.name)); - } - - listTopicSubscriptions().catch(console.error); - // [END pubsub_list_topic_subscriptions] + listTopicSubscriptions(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/listenForAvroRecords.js b/samples/listenForAvroRecords.js index 375526905..b0dbc7aee 100644 --- a/samples/listenForAvroRecords.js +++ b/samples/listenForAvroRecords.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. diff --git a/samples/listenForErrors.js b/samples/listenForErrors.js index 11a780d97..75f1c1bae 100644 --- a/samples/listenForErrors.js +++ b/samples/listenForErrors.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,67 +24,62 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Listen For Errors // description: Listens to messages and errors for a subscription. // usage: node listenForErrors.js [timeout-in-seconds] -async function main( - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 10 -) { - timeout = Number(timeout); - - // [START pubsub_subscriber_error_listener] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const timeout = 10; +// [START pubsub_subscriber_error_listener] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 10; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - function listenForErrors() { - // References an existing subscription - const subscription = pubSubClient.subscription(subscriptionNameOrId); +function listenForErrors(subscriptionNameOrId, timeout) { + // References an existing subscription + const subscription = pubSubClient.subscription(subscriptionNameOrId); - // Create an event handler to handle messages - const messageHandler = function (message) { - // Do something with the message - console.log(`Message: ${message}`); + // Create an event handler to handle messages + const messageHandler = message => { + // Do something with the message + console.log(`Message: ${message}`); - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; - // Create an event handler to handle errors - const errorHandler = function (error) { - // Do something with the error - console.error(`ERROR: ${error}`); - throw error; - }; + // Create an event handler to handle errors + const errorHandler = error => { + // Do something with the error + console.error(`ERROR: ${error}`); + throw error; + }; - // Listen for new messages/errors until timeout is hit - subscription.on('message', messageHandler); - subscription.on('error', errorHandler); + // Listen for new messages/errors until timeout is hit + subscription.on('message', messageHandler); + subscription.on('error', errorHandler); - setTimeout(() => { - subscription.removeListener('message', messageHandler); - subscription.removeListener('error', errorHandler); - }, timeout * 1000); - } + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.removeListener('message', messageHandler); + subscription.removeListener('error', errorHandler); + }, timeout * 1000); +} +// [END pubsub_subscriber_error_listener] - listenForErrors(); - // [END pubsub_subscriber_error_listener] +function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 10 +) { + timeout = Number(timeout); + listenForErrors(subscriptionNameOrId, timeout); } -main(...process.argv.slice(2)).catch(e => { - console.error(e); - process.exitCode = -1; -}); +main(...process.argv.slice(2)); diff --git a/samples/listenForMessages.js b/samples/listenForMessages.js index c0d411e94..3f3f35547 100644 --- a/samples/listenForMessages.js +++ b/samples/listenForMessages.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,61 +24,59 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Listen For Messages // description: Listens for messages from a subscription. // usage: node listenForMessages.js [timeout-in-seconds] -function main( - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 -) { - timeout = Number(timeout); - - // [START pubsub_subscriber_async_pull] - // [START pubsub_quickstart_subscriber] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const timeout = 60; +// [START pubsub_subscriber_async_pull] +// [START pubsub_quickstart_subscriber] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 60; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - function listenForMessages() { - // References an existing subscription - const subscription = pubSubClient.subscription(subscriptionNameOrId); +function listenForMessages(subscriptionNameOrId, timeout) { + // References an existing subscription + const subscription = pubSubClient.subscription(subscriptionNameOrId); - // Create an event handler to handle messages - let messageCount = 0; - const messageHandler = message => { - console.log(`Received message ${message.id}:`); - console.log(`\tData: ${message.data}`); - console.log(`\tAttributes: ${message.attributes}`); - messageCount += 1; + // Create an event handler to handle messages + let messageCount = 0; + const messageHandler = message => { + console.log(`Received message ${message.id}:`); + console.log(`\tData: ${message.data}`); + console.log(`\tAttributes: ${message.attributes}`); + messageCount += 1; - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; - // Listen for new messages until timeout is hit - subscription.on('message', messageHandler); + // Listen for new messages until timeout is hit + subscription.on('message', messageHandler); - setTimeout(() => { - subscription.removeListener('message', messageHandler); - console.log(`${messageCount} message(s) received.`); - }, timeout * 1000); - } + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.removeListener('message', messageHandler); + console.log(`${messageCount} message(s) received.`); + }, timeout * 1000); +} +// [END pubsub_subscriber_async_pull] +// [END pubsub_quickstart_subscriber] - listenForMessages(); - // [END pubsub_subscriber_async_pull] - // [END pubsub_quickstart_subscriber] +function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 60 +) { + timeout = Number(timeout); + listenForMessages(subscriptionNameOrId, timeout); } main(...process.argv.slice(2)); diff --git a/samples/listenForMessagesWithExactlyOnceDelivery.js b/samples/listenForMessagesWithExactlyOnceDelivery.js index 849c39e4a..1027761a0 100644 --- a/samples/listenForMessagesWithExactlyOnceDelivery.js +++ b/samples/listenForMessagesWithExactlyOnceDelivery.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * schemas with the Google Cloud Pub/Sub API. diff --git a/samples/listenForProtobufMessages.js b/samples/listenForProtobufMessages.js index 0bf7e9dd7..933797fb2 100644 --- a/samples/listenForProtobufMessages.js +++ b/samples/listenForProtobufMessages.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. diff --git a/samples/listenWithCustomAttributes.js b/samples/listenWithCustomAttributes.js index 0af728980..b231d431f 100644 --- a/samples/listenWithCustomAttributes.js +++ b/samples/listenWithCustomAttributes.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,61 +24,57 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Listen For Messages With Custom Attributes // description: Demonstrates how to receive and process custom attributes on messages. // usage: node listenWithCustomAttributes.js [timeout-in-seconds] -async function main( - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', - timeout = 60 -) { - timeout = Number(timeout); - - // [START pubsub_subscriber_async_pull_custom_attributes] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const timeout = 60; +// [START pubsub_subscriber_async_pull_custom_attributes] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 60; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function listenWithCustomAttributes() { - // References an existing subscription, e.g. "my-subscription" - const subscription = pubSubClient.subscription(subscriptionNameOrId); +async function listenWithCustomAttributes(subscriptionNameOrId, timeout) { + // References an existing subscription, e.g. "my-subscription" + const subscription = pubSubClient.subscription(subscriptionNameOrId); - // Create an event handler to handle messages - const messageHandler = message => { - console.log( - `Received message: id ${message.id}, data ${ - message.data - }, attributes: ${JSON.stringify(message.attributes)}` - ); + // Create an event handler to handle messages + const messageHandler = message => { + console.log( + `Received message: id ${message.id}, data ${ + message.data + }, attributes: ${JSON.stringify(message.attributes)}` + ); - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; - // Listen for new messages until timeout is hit - subscription.on('message', messageHandler); - setTimeout(() => { - subscription.removeListener('message', messageHandler); - }, timeout * 1000); - } + // Wait a while for the subscription to run. (Part of the sample only.) + subscription.on('message', messageHandler); + setTimeout(() => { + subscription.removeListener('message', messageHandler); + }, timeout * 1000); +} +// [END pubsub_subscriber_async_pull_custom_attributes] - listenWithCustomAttributes(); - // [END pubsub_subscriber_async_pull_custom_attributes] +async function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 60 +) { + timeout = Number(timeout); + listenWithCustomAttributes(subscriptionNameOrId, timeout).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -process.on('unhandledRejection', err => { - console.error(err.message); - process.exitCode = 1; -}); main(...process.argv.slice(2)); diff --git a/samples/modifyPushConfig.js b/samples/modifyPushConfig.js index 036347421..df35aa7d9 100644 --- a/samples/modifyPushConfig.js +++ b/samples/modifyPushConfig.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,48 +24,47 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Modify Push Configuration // description: Modifies the configuration of an existing push subscription. // usage: node modifyPushConfig.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_update_push_configuration] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_update_push_configuration] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function modifyPushConfig() { - const options = { - // Set to an HTTPS endpoint of your choice. If necessary, register - // (authorize) the domain on which the server is hosted. - pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, - }; +async function modifyPushConfig(topicNameOrId, subscriptionNameOrId) { + const options = { + // Set to an HTTPS endpoint of your choice. If necessary, register + // (authorize) the domain on which the server is hosted. + pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, + }; - await pubSubClient - .topic(topicNameOrId) - .subscription(subscriptionNameOrId) - .modifyPushConfig(options); - console.log( - `Modified push config for subscription ${subscriptionNameOrId}.` - ); - } + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .modifyPushConfig(options); + console.log(`Modified push config for subscription ${subscriptionNameOrId}.`); +} +// [END pubsub_update_push_configuration] - modifyPushConfig().catch(console.error); - // [END pubsub_update_push_configuration] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + modifyPushConfig(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/publishAvroRecords.js b/samples/publishAvroRecords.js index c81cfb37c..a4460b3c1 100644 --- a/samples/publishAvroRecords.js +++ b/samples/publishAvroRecords.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. diff --git a/samples/publishBatchedMessages.js b/samples/publishBatchedMessages.js index 513960c81..0a45a0880 100644 --- a/samples/publishBatchedMessages.js +++ b/samples/publishBatchedMessages.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,58 +24,72 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Publish Batched Messages // description: Publishes messages to a topic using custom batching settings. // usage: node publishBatchedMessages.js [max-messages [max-wait-in-seconds]] -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}), - maxMessages = 10, - maxWaitTime = 10 -) { - maxMessages = Number(maxMessages); - maxWaitTime = Number(maxWaitTime); - - // [START pubsub_publisher_batch_settings] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicName = 'YOUR_TOPIC_NAME'; - // const data = JSON.stringify({foo: 'bar'}); - // const maxMessages = 10; - // const maxWaitTime = 10; +// [START pubsub_publisher_batch_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicName = 'YOUR_TOPIC_NAME'; +// const data = JSON.stringify({foo: 'bar'}); +// const maxMessages = 10; +// const maxWaitTime = 10; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function publishBatchedMessages() { - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); +async function publishBatchedMessages( + topicNameOrId, + data, + maxMessages, + maxWaitTime +) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); - const batchPublisher = pubSubClient.topic(topicNameOrId, { - batching: { - maxMessages: maxMessages, - maxMilliseconds: maxWaitTime * 1000, - }, - }); + const publishOptions = { + batching: { + maxMessages: maxMessages, + maxMilliseconds: maxWaitTime * 1000, + }, + }; + const batchPublisher = pubSubClient.topic(topicNameOrId, publishOptions); - for (let i = 0; i < 10; i++) { + const promises = []; + for (let i = 0; i < 10; i++) { + promises.push( (async () => { - const messageId = await batchPublisher.publish(dataBuffer); + const messageId = await batchPublisher.publishMessage({ + data: dataBuffer, + }); console.log(`Message ${messageId} published.`); - })(); - } + })() + ); } + await Promise.all(promises); +} +// [END pubsub_publisher_batch_settings] - publishBatchedMessages().catch(console.error); - // [END pubsub_publisher_batch_settings] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + maxMessages = 10, + maxWaitTime = 10 +) { + maxMessages = Number(maxMessages); + maxWaitTime = Number(maxWaitTime); + publishBatchedMessages(topicNameOrId, data, maxMessages, maxWaitTime).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); } main(...process.argv.slice(2)); diff --git a/samples/publishMessage.js b/samples/publishMessage.js index 062e3c7a2..beccf0fd4 100644 --- a/samples/publishMessage.js +++ b/samples/publishMessage.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,53 +24,51 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Publish Message // description: Publishes a message to a topic. // usage: node publishMessage.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) -) { - // [START pubsub_publish_with_error_handler] - // [START pubsub_quickstart_publisher] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const data = JSON.stringify({foo: 'bar'}); +// [START pubsub_publish_with_error_handler] +// [START pubsub_quickstart_publisher] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function publishMessage() { - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); +async function publishMessage(topicNameOrId, data) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); - try { - const messageId = await pubSubClient - .topic(topicNameOrId) - .publishMessage({data: dataBuffer}); - console.log(`Message ${messageId} published.`); - } catch (error) { - console.error(`Received error while publishing: ${error.message}`); - process.exitCode = 1; - } + try { + const messageId = await pubSubClient + .topic(topicNameOrId) + .publishMessage({data: dataBuffer}); + console.log(`Message ${messageId} published.`); + } catch (error) { + console.error(`Received error while publishing: ${error.message}`); + + process.exitCode = 1; } +} +// [END pubsub_publish_with_error_handler] +// [END pubsub_quickstart_publisher] - publishMessage(); - // [END pubsub_publish_with_error_handler] - // [END pubsub_quickstart_publisher] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishMessage(topicNameOrId, data).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -process.on('unhandledRejection', err => { - console.error(err.message); - process.exitCode = 1; -}); main(...process.argv.slice(2)); diff --git a/samples/publishMessageWithCustomAttributes.js b/samples/publishMessageWithCustomAttributes.js index b523f2cc2..3c2e6b43a 100644 --- a/samples/publishMessageWithCustomAttributes.js +++ b/samples/publishMessageWithCustomAttributes.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,48 +24,46 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Publish Message With Custom Attributes // description: Publishes a message with custom attributes to a topic. // usage: node publishMessageWithCustomAttributes.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) -) { - // [START pubsub_publish_custom_attributes] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const data = JSON.stringify({foo: 'bar'}); +// [START pubsub_publish_custom_attributes] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function publishMessageWithCustomAttributes() { - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); +async function publishMessageWithCustomAttributes(topicNameOrId, data) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); - // Add two custom attributes, origin and username, to the message - const customAttributes = { - origin: 'nodejs-sample', - username: 'gcp', - }; + // Add two custom attributes, origin and username, to the message + const customAttributes = { + origin: 'nodejs-sample', + username: 'gcp', + }; - const messageId = await pubSubClient - .topic(topicNameOrId) - .publish(dataBuffer, customAttributes); - console.log(`Message ${messageId} published.`); - } + const messageId = await pubSubClient + .topic(topicNameOrId) + .publishMessage({data: dataBuffer, attributes: customAttributes}); + console.log(`Message ${messageId} published.`); +} +// [END pubsub_publish_custom_attributes] - publishMessageWithCustomAttributes().catch(console.error); - // [END pubsub_publish_custom_attributes] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishMessageWithCustomAttributes(topicNameOrId, data).catch(console.error); } main(...process.argv.slice(2)); diff --git a/samples/publishOrderedMessage.js b/samples/publishOrderedMessage.js index b96403db7..bb4e0cc4d 100644 --- a/samples/publishOrderedMessage.js +++ b/samples/publishOrderedMessage.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,8 +24,6 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Publish Ordered Message // description: Demonstrates how to publish messages to a topic @@ -30,56 +32,59 @@ // messages with proper ordering. // usage: node publishOrderedMessage.js -async function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' -) { - // [START pubsub_publish_with_ordering_keys] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const data = JSON.stringify({foo: 'bar'}); - // const orderingKey = 'key1'; +// [START pubsub_publish_with_ordering_keys] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); +// const orderingKey = 'key1'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub({ - // Sending messages to the same region ensures they are received in order - // even when multiple publishers are used. - apiEndpoint: 'us-east1-pubsub.googleapis.com:443', - }); +// Creates a client; cache this for further use +const pubSubClient = new PubSub({ + // Sending messages to the same region ensures they are received in order + // even when multiple publishers are used. + apiEndpoint: 'us-east1-pubsub.googleapis.com:443', +}); - async function publishOrderedMessage() { - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); +async function publishOrderedMessage(topicNameOrId, data, orderingKey) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); - // Be sure to set an ordering key that matches other messages - // you want to receive in order, relative to each other. - const message = { - data: dataBuffer, - orderingKey: orderingKey, - }; + // Be sure to set an ordering key that matches other messages + // you want to receive in order, relative to each other. + const message = { + data: dataBuffer, + orderingKey: orderingKey, + }; - // Publishes the message - const messageId = await pubSubClient - .topic(topicNameOrId, {enableMessageOrdering: true}) - .publishMessage(message); + const publishOptions = { + messageOrdering: true, + }; - console.log(`Message ${messageId} published.`); + // Publishes the message + const messageId = await pubSubClient + .topic(topicNameOrId, publishOptions) + .publishMessage(message); - return messageId; - } + console.log(`Message ${messageId} published.`); - return await publishOrderedMessage(); - // [END pubsub_publish_with_ordering_keys] + return messageId; +} +// [END pubsub_publish_with_ordering_keys] + +async function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + orderingKey = 'key1' +) { + await publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } -process.on('unhandledRejection', err => { - console.error(err.message); - process.exitCode = 1; -}); main(...process.argv.slice(2)); diff --git a/samples/publishProtobufMessages.js b/samples/publishProtobufMessages.js index 18a94719e..9ef309359 100644 --- a/samples/publishProtobufMessages.js +++ b/samples/publishProtobufMessages.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. diff --git a/samples/publishWithFlowControl.js b/samples/publishWithFlowControl.js index 058deee89..7e1193f79 100644 --- a/samples/publishWithFlowControl.js +++ b/samples/publishWithFlowControl.js @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. diff --git a/samples/publishWithRetrySettings.js b/samples/publishWithRetrySettings.js index c7d2212e5..3c50b5a99 100644 --- a/samples/publishWithRetrySettings.js +++ b/samples/publishWithRetrySettings.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,98 +24,98 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Publish With Retry Settings // description: Publishes a message to a topic with retry settings. // usage: node publishWithRetrySettings.js -function main( - projectId = 'YOUR_PROJECT_ID', - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}) -) { - // [START pubsub_publisher_retry_settings] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const projectId = 'YOUR_PROJECT_ID' - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const data = JSON.stringify({foo: 'bar'}); - - // Imports the Google Cloud client library. v1 is for the lower level - // proto access. - const {v1} = require('@google-cloud/pubsub'); +// [START pubsub_publisher_retry_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID' +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); - // Creates a publisher client. - const publisherClient = new v1.PublisherClient({ - // optional auth parameters - }); +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +const {v1} = require('@google-cloud/pubsub'); - async function publishWithRetrySettings() { - const formattedTopic = publisherClient.projectTopicPath( - projectId, - topicNameOrId - ); +// Creates a publisher client. +const publisherClient = new v1.PublisherClient({ + // optional auth parameters +}); +async function publishWithRetrySettings(projectId, topicNameOrId, data) { + const formattedTopic = publisherClient.projectTopicPath( + projectId, + topicNameOrId + ); - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); - const messagesElement = { - data: dataBuffer, - }; - const messages = [messagesElement]; + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + const messagesElement = { + data: dataBuffer, + }; + const messages = [messagesElement]; - // Build the request - const request = { - topic: formattedTopic, - messages: messages, - }; + // Build the request + const request = { + topic: formattedTopic, + messages: messages, + }; - // Retry settings control how the publisher handles retryable failures. Default values are shown. - // The `retryCodes` array determines which grpc errors will trigger an automatic retry. - // The `backoffSettings` object lets you specify the behaviour of retries over time. - const retrySettings = { - retryCodes: [ - 10, // 'ABORTED' - 1, // 'CANCELLED', - 4, // 'DEADLINE_EXCEEDED' - 13, // 'INTERNAL' - 8, // 'RESOURCE_EXHAUSTED' - 14, // 'UNAVAILABLE' - 2, // 'UNKNOWN' - ], - backoffSettings: { - // The initial delay time, in milliseconds, between the completion - // of the first failed request and the initiation of the first retrying request. - initialRetryDelayMillis: 100, - // The multiplier by which to increase the delay time between the completion - // of failed requests, and the initiation of the subsequent retrying request. - retryDelayMultiplier: 1.3, - // The maximum delay time, in milliseconds, between requests. - // When this value is reached, retryDelayMultiplier will no longer be used to increase delay time. - maxRetryDelayMillis: 60000, - // The initial timeout parameter to the request. - initialRpcTimeoutMillis: 5000, - // The multiplier by which to increase the timeout parameter between failed requests. - rpcTimeoutMultiplier: 1.0, - // The maximum timeout parameter, in milliseconds, for a request. When this value is reached, - // rpcTimeoutMultiplier will no longer be used to increase the timeout. - maxRpcTimeoutMillis: 600000, - // The total time, in milliseconds, starting from when the initial request is sent, - // after which an error will be returned, regardless of the retrying attempts made meanwhile. - totalTimeoutMillis: 600000, - }, - }; + // Retry settings control how the publisher handles retryable failures. Default values are shown. + // The `retryCodes` array determines which grpc errors will trigger an automatic retry. + // The `backoffSettings` object lets you specify the behaviour of retries over time. + const retrySettings = { + retryCodes: [ + 10, // 'ABORTED' + 1, // 'CANCELLED', + 4, // 'DEADLINE_EXCEEDED' + 13, // 'INTERNAL' + 8, // 'RESOURCE_EXHAUSTED' + 14, // 'UNAVAILABLE' + 2, // 'UNKNOWN' + ], + backoffSettings: { + // The initial delay time, in milliseconds, between the completion + // of the first failed request and the initiation of the first retrying request. + initialRetryDelayMillis: 100, + // The multiplier by which to increase the delay time between the completion + // of failed requests, and the initiation of the subsequent retrying request. + retryDelayMultiplier: 1.3, + // The maximum delay time, in milliseconds, between requests. + // When this value is reached, retryDelayMultiplier will no longer be used to increase delay time. + maxRetryDelayMillis: 60000, + // The initial timeout parameter to the request. + initialRpcTimeoutMillis: 5000, + // The multiplier by which to increase the timeout parameter between failed requests. + rpcTimeoutMultiplier: 1.0, + // The maximum timeout parameter, in milliseconds, for a request. When this value is reached, + // rpcTimeoutMultiplier will no longer be used to increase the timeout. + maxRpcTimeoutMillis: 600000, + // The total time, in milliseconds, starting from when the initial request is sent, + // after which an error will be returned, regardless of the retrying attempts made meanwhile. + totalTimeoutMillis: 600000, + }, + }; - const [response] = await publisherClient.publish(request, { - retry: retrySettings, - }); - console.log(`Message ${response.messageIds} published.`); - } + const [response] = await publisherClient.publish(request, { + retry: retrySettings, + }); + console.log(`Message ${response.messageIds} published.`); +} +// [END pubsub_publisher_retry_settings] - publishWithRetrySettings().catch(console.error); - // [END pubsub_publisher_retry_settings] +function main( + projectId = 'YOUR_PROJECT_ID', + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishWithRetrySettings(projectId, topicNameOrId, data).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/quickstart.js b/samples/quickstart.js index 9ef357afe..a5beb94bb 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -1,4 +1,4 @@ -// Copyright 2017 Google LLC +// Copyright 2017-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. 'use strict'; // sample-metadata: @@ -51,7 +53,7 @@ async function quickstart( }); // Send a message to the topic - topic.publish(Buffer.from('Test message!')); + topic.publishMessage({data: Buffer.from('Test message!')}); } // [END pubsub_quickstart_create_topic] diff --git a/samples/removeDeadLetterPolicy.js b/samples/removeDeadLetterPolicy.js index b3f8a379c..3268678ab 100644 --- a/samples/removeDeadLetterPolicy.js +++ b/samples/removeDeadLetterPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,47 +24,48 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Remove Dead Letter Policy // description: Remove Dead Letter Policy from subscription. // usage: node removeDeadLetterPolicy.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_dead_letter_remove] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_dead_letter_remove] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function removeDeadLetterPolicy() { - const metadata = { - deadLetterPolicy: null, - }; +async function removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId) { + const metadata = { + deadLetterPolicy: null, + }; - await pubSubClient - .topic(topicNameOrId) - .subscription(subscriptionNameOrId) - .setMetadata(metadata); + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .setMetadata(metadata); - console.log( - `Removed dead letter topic from ${subscriptionNameOrId} subscription.` - ); - } + console.log( + `Removed dead letter topic from ${subscriptionNameOrId} subscription.` + ); +} +// [END pubsub_dead_letter_remove] - removeDeadLetterPolicy().catch(console.error); - // [END pubsub_dead_letter_remove] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/resumePublish.js b/samples/resumePublish.js index 241af1880..3dbe4b242 100644 --- a/samples/resumePublish.js +++ b/samples/resumePublish.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,65 +24,66 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Resume Publish // description: Demonstrates how to resume publishing on an ordering key if // publishing fails for a message. // usage: node resumePublish.js -async function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - data = JSON.stringify({foo: 'bar'}), - orderingKey = 'key1' -) { - // [START pubsub_resume_publish_with_ordering_keys] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const data = JSON.stringify({foo: 'bar'}); - // const orderingKey = 'key1'; +// [START pubsub_resume_publish_with_ordering_keys] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); +// const orderingKey = 'key1'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +async function resumePublish(topicNameOrId, data, orderingKey) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); - async function resumePublish() { - // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) - const dataBuffer = Buffer.from(data); + const publishOptions = { + messageOrdering: true, + }; - // Publishes the message - const publisher = pubSubClient.topic(topicNameOrId, { - enableMessageOrdering: true, - }); - try { - const message = { - data: dataBuffer, - orderingKey: orderingKey, - }; - const messageId = await publisher.publishMessage(message); - console.log(`Message ${messageId} published.`); + // Publishes the message + const publisher = pubSubClient.topic(topicNameOrId, publishOptions); + try { + const message = { + data: dataBuffer, + orderingKey: orderingKey, + }; + const messageId = await publisher.publishMessage(message); + console.log(`Message ${messageId} published.`); - return messageId; - } catch (e) { - console.log(`Could not publish: ${e}`); - publisher.resumePublishing(orderingKey); - return null; - } + return messageId; + } catch (e) { + console.log(`Could not publish: ${e}`); + publisher.resumePublishing(orderingKey); + return null; } +} +// [END pubsub_resume_publish_with_ordering_keys] - return await resumePublish(); - // [END pubsub_resume_publish_with_ordering_keys] +async function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + orderingKey = 'key1' +) { + return await resumePublish(topicNameOrId, data, orderingKey).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } // This needs to be exported directly so that the system tests can find it. -module.exports = { - resumePublish: main, -}; +module.exports.resumePublishFunc = resumePublish; if (require.main === module) { main(...process.argv.slice(2)).catch(console.error); diff --git a/samples/setSubscriptionPolicy.js b/samples/setSubscriptionPolicy.js index 2521020c2..4cabd7b20 100644 --- a/samples/setSubscriptionPolicy.js +++ b/samples/setSubscriptionPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,53 +24,54 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Set Subscription IAM Policy // description: Sets the IAM policy for a subscription. // usage: node setSubscriptionPolicy.js -function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { - // [START pubsub_set_subscription_policy] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_set_subscription_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function setSubscriptionPolicy() { - // The new IAM policy - const newPolicy = { - bindings: [ - { - // Add a group as editors - role: 'roles/pubsub.editor', - members: ['group:cloud-logs@google.com'], - }, - { - // Add all users as viewers - role: 'roles/pubsub.viewer', - members: ['allUsers'], - }, - ], - }; +async function setSubscriptionPolicy(subscriptionNameOrId) { + // The new IAM policy + const newPolicy = { + bindings: [ + { + // Add a group as editors + role: 'roles/pubsub.editor', + members: ['group:cloud-logs@google.com'], + }, + { + // Add all users as viewers + role: 'roles/pubsub.viewer', + members: ['allUsers'], + }, + ], + }; - // Updates the IAM policy for the subscription - const [updatedPolicy] = await pubSubClient - .subscription(subscriptionNameOrId) - .iam.setPolicy(newPolicy); + // Updates the IAM policy for the subscription + const [updatedPolicy] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.setPolicy(newPolicy); - console.log('Updated policy for subscription: %j', updatedPolicy.bindings); - } + console.log('Updated policy for subscription: %j', updatedPolicy.bindings); +} +// [END pubsub_set_subscription_policy] - setSubscriptionPolicy().catch(console.error); - // [END pubsub_set_subscription_policy] +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + setSubscriptionPolicy(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/setTopicPolicy.js b/samples/setTopicPolicy.js index ef447ddb9..133af5e83 100644 --- a/samples/setTopicPolicy.js +++ b/samples/setTopicPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,52 +24,53 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Set Topic IAM Policy // description: Sets the IAM policy for a topic. // usage: node setTopicPolicy.js -function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_set_topic_policy] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// [START pubsub_set_topic_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function setTopicPolicy() { - // The new IAM policy - const newPolicy = { - bindings: [ - { - // Add a group as editors - role: 'roles/pubsub.editor', - members: ['group:cloud-logs@google.com'], - }, - { - // Add all users as viewers - role: 'roles/pubsub.viewer', - members: ['allUsers'], - }, - ], - }; +async function setTopicPolicy(topicNameOrId) { + // The new IAM policy + const newPolicy = { + bindings: [ + { + // Add a group as editors + role: 'roles/pubsub.editor', + members: ['group:cloud-logs@google.com'], + }, + { + // Add all users as viewers + role: 'roles/pubsub.viewer', + members: ['allUsers'], + }, + ], + }; - // Updates the IAM policy for the topic - const [updatedPolicy] = await pubSubClient - .topic(topicNameOrId) - .iam.setPolicy(newPolicy); - console.log('Updated policy for topic: %j', updatedPolicy.bindings); - } + // Updates the IAM policy for the topic + const [updatedPolicy] = await pubSubClient + .topic(topicNameOrId) + .iam.setPolicy(newPolicy); + console.log('Updated policy for topic: %j', updatedPolicy.bindings); +} +// [END pubsub_set_topic_policy] - setTopicPolicy().catch(console.error); - // [END pubsub_set_topic_policy] +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + setTopicPolicy(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/subscribeWithFlowControlSettings.js b/samples/subscribeWithFlowControlSettings.js index 7f537c6ce..367d701c2 100644 --- a/samples/subscribeWithFlowControlSettings.js +++ b/samples/subscribeWithFlowControlSettings.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,8 +24,6 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Subscribe With Flow Control Settings // description: Listen to messages with flow control settings, which are @@ -29,6 +31,60 @@ // usage: node subscribeWithFlowControlSettings.js // [max-in-progress [timeout-in-seconds]] +// [START pubsub_subscriber_flow_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const maxInProgress = 5; +// const timeout = 10; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function subscribeWithFlowControlSettings( + subscriptionNameOrId, + maxInProgress, + timeout +) { + const subscriberOptions = { + flowControl: { + maxMessages: maxInProgress, + }, + }; + + // References an existing subscription. + // Note that flow control settings are not persistent across subscribers. + const subscription = pubSubClient.subscription( + subscriptionNameOrId, + subscriberOptions + ); + + console.log( + `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` + ); + + const messageHandler = message => { + console.log(`Received message: ${message.id}`); + console.log(`\tData: ${message.data}`); + console.log(`\tAttributes: ${message.attributes}`); + + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; + + subscription.on('message', messageHandler); + + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.close(); + }, timeout * 1000); +} +// [END pubsub_subscriber_flow_settings] + function main( subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', maxInProgress = 1, @@ -37,56 +93,14 @@ function main( maxInProgress = Number(maxInProgress); timeout = Number(timeout); - // [START pubsub_subscriber_flow_settings] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // const maxInProgress = 5; - // const timeout = 10; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function subscribeWithFlowControlSettings() { - const subscriberOptions = { - flowControl: { - maxMessages: maxInProgress, - }, - }; - - // References an existing subscription. - // Note that flow control settings are not persistent across subscribers. - const subscription = pubSubClient.subscription( - subscriptionNameOrId, - subscriberOptions - ); - - console.log( - `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` - ); - - const messageHandler = message => { - console.log(`Received message: ${message.id}`); - console.log(`\tData: ${message.data}`); - console.log(`\tAttributes: ${message.attributes}`); - - // "Ack" (acknowledge receipt of) the message - message.ack(); - }; - - subscription.on('message', messageHandler); - - setTimeout(() => { - subscription.close(); - }, timeout * 1000); - } - - // [END pubsub_subscriber_flow_settings] - subscribeWithFlowControlSettings().catch(console.error); + subscribeWithFlowControlSettings( + subscriptionNameOrId, + maxInProgress, + timeout + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/synchronousPull.js b/samples/synchronousPull.js index 2f7698af2..755143ebe 100644 --- a/samples/synchronousPull.js +++ b/samples/synchronousPull.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,71 +24,74 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Synchronous Pull // description: Receive messages synchronously. // usage: node synchronousPull.js -function main( - projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_subscriber_sync_pull] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const projectId = 'YOUR_PROJECT_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_subscriber_sync_pull] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library. v1 is for the lower level - // proto access. - const {v1} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +const {v1} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use. - const subClient = new v1.SubscriberClient(); +// Creates a client; cache this for further use. +const subClient = new v1.SubscriberClient(); - async function synchronousPull() { - // The low level API client requires a name only. - const formattedSubscription = - subscriptionNameOrId.indexOf('/') >= 0 - ? subscriptionNameOrId - : subClient.subscriptionPath(projectId, subscriptionNameOrId); +async function synchronousPull(projectId, subscriptionNameOrId) { + // The low level API client requires a name only. + const formattedSubscription = + subscriptionNameOrId.indexOf('/') >= 0 + ? subscriptionNameOrId + : subClient.subscriptionPath(projectId, subscriptionNameOrId); - // The maximum number of messages returned for this request. - // Pub/Sub may return fewer than the number specified. - const request = { - subscription: formattedSubscription, - maxMessages: 10, - }; + // The maximum number of messages returned for this request. + // Pub/Sub may return fewer than the number specified. + const request = { + subscription: formattedSubscription, + maxMessages: 10, + }; - // The subscriber pulls a specified number of messages. - const [response] = await subClient.pull(request); + // The subscriber pulls a specified number of messages. + const [response] = await subClient.pull(request); - // Process the messages. - const ackIds = []; - for (const message of response.receivedMessages) { - console.log(`Received message: ${message.message.data}`); + // Process the messages. + const ackIds = []; + for (const message of response.receivedMessages || []) { + console.log(`Received message: ${message.message.data}`); + if (message.ackId) { ackIds.push(message.ackId); } + } - if (ackIds.length !== 0) { - // Acknowledge all of the messages. You could also acknowledge - // these individually, but this is more efficient. - const ackRequest = { - subscription: formattedSubscription, - ackIds: ackIds, - }; - - await subClient.acknowledge(ackRequest); - } + if (ackIds.length !== 0) { + // Acknowledge all of the messages. You could also acknowledge + // these individually, but this is more efficient. + const ackRequest = { + subscription: formattedSubscription, + ackIds: ackIds, + }; - console.log('Done.'); + await subClient.acknowledge(ackRequest); } - synchronousPull().catch(console.error); - // [END pubsub_subscriber_sync_pull] + console.log('Done.'); +} +// [END pubsub_subscriber_sync_pull] + +function main( + projectId = 'YOUR_PROJECT_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + synchronousPull(projectId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/synchronousPullWithDeliveryAttempts.js b/samples/synchronousPullWithDeliveryAttempts.js index 33687a849..40c76bdc1 100644 --- a/samples/synchronousPullWithDeliveryAttempts.js +++ b/samples/synchronousPullWithDeliveryAttempts.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,69 +24,77 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Synchronous Pull with delivery attempt. // description: Receive messages synchronously with delivery attempt. // usage: node synchronousPullWithDeliveryAttempts.js -function main( - projectId = 'YOUR_PROJECT_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_dead_letter_delivery_attempt] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const projectId = 'YOUR_PROJECT_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_dead_letter_delivery_attempt] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library. v1 is for the lower level - // proto access. - const {v1} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +const {v1} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use. - const subClient = new v1.SubscriberClient(); +// Creates a client; cache this for further use. +const subClient = new v1.SubscriberClient(); - async function synchronousPullWithDeliveryAttempts() { - // The low level API client requires a name only. - const formattedSubscription = - subscriptionNameOrId.indexOf('/') >= 0 - ? subscriptionNameOrId - : subClient.subscriptionPath(projectId, subscriptionNameOrId); +async function synchronousPullWithDeliveryAttempts( + projectId, + subscriptionNameOrId +) { + // The low level API client requires a name only. + const formattedSubscription = + subscriptionNameOrId.indexOf('/') >= 0 + ? subscriptionNameOrId + : subClient.subscriptionPath(projectId, subscriptionNameOrId); - // The maximum number of messages returned for this request. - // Pub/Sub may return fewer than the number specified. - const request = { - subscription: formattedSubscription, - maxMessages: 10, - }; + // The maximum number of messages returned for this request. + // Pub/Sub may return fewer than the number specified. + const request = { + subscription: formattedSubscription, + maxMessages: 10, + }; - // The subscriber pulls a specified number of messages. - const [response] = await subClient.pull(request); + // The subscriber pulls a specified number of messages. + const [response] = await subClient.pull(request); - // Process the messages. - const ackIds = []; - for (const message of response.receivedMessages) { - console.log(`Received message: ${message.message.data}`); - console.log(`Delivery Attempt: ${message.deliveryAttempt}`); + // Process the messages. + const ackIds = []; + for (const message of response.receivedMessages || []) { + console.log(`Received message: ${message.message.data}`); + console.log(`Delivery Attempt: ${message.deliveryAttempt}`); + if (message.ackId) { ackIds.push(message.ackId); } + } - // Acknowledge all of the messages. You could also acknowledge - // these individually, but this is more efficient. - const ackRequest = { - subscription: formattedSubscription, - ackIds: ackIds, - }; - await subClient.acknowledge(ackRequest); + // Acknowledge all of the messages. You could also acknowledge + // these individually, but this is more efficient. + const ackRequest = { + subscription: formattedSubscription, + ackIds: ackIds, + }; + await subClient.acknowledge(ackRequest); - console.log('Done.'); - } + console.log('Done.'); +} +// [END pubsub_dead_letter_delivery_attempt] - synchronousPullWithDeliveryAttempts().catch(console.error); - // [END pubsub_dead_letter_delivery_attempt] +function main( + projectId = 'YOUR_PROJECT_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + synchronousPullWithDeliveryAttempts(projectId, subscriptionNameOrId).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); } main(...process.argv.slice(2)); diff --git a/samples/testSubscriptionPermissions.js b/samples/testSubscriptionPermissions.js index b5ffda9ff..caa74e88f 100644 --- a/samples/testSubscriptionPermissions.js +++ b/samples/testSubscriptionPermissions.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,42 +24,43 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Test Subscription Permissions // description: Tests the permissions for a subscription. // usage: node testSubscriptionPermissions.js +// [START pubsub_test_subscription_permissions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function testSubscriptionPermissions(subscriptionNameOrId) { + const permissionsToTest = [ + 'pubsub.subscriptions.consume', + 'pubsub.subscriptions.update', + ]; + + // Tests the IAM policy for the specified subscription + const [permissions] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.testPermissions(permissionsToTest); + + console.log('Tested permissions for subscription: %j', permissions); +} +// [END pubsub_test_subscription_permissions] + function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { - // [START pubsub_test_subscription_permissions] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function testSubscriptionPermissions() { - const permissionsToTest = [ - 'pubsub.subscriptions.consume', - 'pubsub.subscriptions.update', - ]; - - // Tests the IAM policy for the specified subscription - const [permissions] = await pubSubClient - .subscription(subscriptionNameOrId) - .iam.testPermissions(permissionsToTest); - - console.log('Tested permissions for subscription: %j', permissions); - } - - testSubscriptionPermissions().catch(console.error); - // [END pubsub_test_subscription_permissions] + testSubscriptionPermissions(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/testTopicPermissions.js b/samples/testTopicPermissions.js index eacac900b..d68cac864 100644 --- a/samples/testTopicPermissions.js +++ b/samples/testTopicPermissions.js @@ -1,4 +1,4 @@ -// Copyright 2019-2020 Google LLC +// Copyright 2019-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This sample demonstrates how to perform basic operations on topics with * the Google Cloud Pub/Sub API. @@ -20,43 +24,44 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Test Topic Permissions // description: Tests the permissions for a topic. // usage: node testTopicPermissions.js +// [START pubsub_test_topic_permissions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function testTopicPermissions(topicNameOrId) { + const permissionsToTest = [ + 'pubsub.topics.attachSubscription', + 'pubsub.topics.publish', + 'pubsub.topics.update', + ]; + + // Tests the IAM policy for the specified topic + const [permissions] = await pubSubClient + .topic(topicNameOrId) + .iam.testPermissions(permissionsToTest); + + console.log('Tested permissions for topic: %j', permissions); +} +// [END pubsub_test_topic_permissions] + function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { - // [START pubsub_test_topic_permissions] - /** - * TODO(developer): Uncomment this variable before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); - - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); - - async function testTopicPermissions() { - const permissionsToTest = [ - 'pubsub.topics.attachSubscription', - 'pubsub.topics.publish', - 'pubsub.topics.update', - ]; - - // Tests the IAM policy for the specified topic - const [permissions] = await pubSubClient - .topic(topicNameOrId) - .iam.testPermissions(permissionsToTest); - - console.log('Tested permissions for topic: %j', permissions); - } - - testTopicPermissions().catch(console.error); - // [END pubsub_test_topic_permissions] + testTopicPermissions(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/typescript/createBigQuerySubscription.ts b/samples/typescript/createBigQuerySubscription.ts new file mode 100644 index 000000000..6b109e5e7 --- /dev/null +++ b/samples/typescript/createBigQuerySubscription.ts @@ -0,0 +1,77 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create BigQuery Subscription +// description: Creates a new BigQuery subscription. +// usage: node createBigQuerySubscription.js + +// [START pubsub_create_bigquery_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const bigqueryTableId = 'YOUR_TABLE_ID'; + +// Imports the Google Cloud client library +import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createBigQuerySubscription( + topicNameOrId: string, + subscriptionNameOrId: string, + bigqueryTableId: string +) { + const options: CreateSubscriptionOptions = { + bigqueryConfig: { + table: bigqueryTableId, + writeMetadata: true, + }, + }; + + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); + + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_bigquery_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + bigqueryTableId = 'YOUR_TABLE_ID' +) { + createBigQuerySubscription( + topicNameOrId, + subscriptionNameOrId, + bigqueryTableId + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/createPushSubscription.ts b/samples/typescript/createPushSubscription.ts new file mode 100644 index 000000000..a1a0f31e8 --- /dev/null +++ b/samples/typescript/createPushSubscription.ts @@ -0,0 +1,70 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create Push Subscription +// description: Creates a new push subscription. +// usage: node createPushSubscription.js + +// [START pubsub_create_push_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createPushSubscription( + topicNameOrId: string, + subscriptionNameOrId: string +) { + const options: CreateSubscriptionOptions = { + pushConfig: { + // Set to an HTTPS endpoint of your choice. If necessary, register + // (authorize) the domain on which the server is hosted. + pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, + }, + }; + + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_push_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + createPushSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/createSubscription.ts b/samples/typescript/createSubscription.ts new file mode 100644 index 000000000..c531c3608 --- /dev/null +++ b/samples/typescript/createSubscription.ts @@ -0,0 +1,63 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to create subscriptions with the + * Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create Subscription +// description: Creates a new subscription. +// usage: node createSubscription.js + +// [START pubsub_create_pull_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createSubscription( + topicNameOrId: string, + subscriptionNameOrId: string +) { + // Creates a new subscription + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId); + console.log(`Subscription ${subscriptionNameOrId} created.`); +} +// [END pubsub_create_pull_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + createSubscription(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts b/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts new file mode 100644 index 000000000..e2f8f12f3 --- /dev/null +++ b/samples/typescript/createSubscriptionWithDeadLetterPolicy.ts @@ -0,0 +1,81 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create Subscription With Dead Letter Policy +// description: Creates a new subscription With Dead Letter Policy. +// usage: node createSubscriptionWithDeadLetterPolicy.js + +// [START pubsub_dead_letter_create_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createSubscriptionWithDeadLetterPolicy( + topicNameOrId: string, + subscriptionNameOrId: string, + deadLetterTopicNameOrId: string +) { + // Creates a new subscription + const options: CreateSubscriptionOptions = { + deadLetterPolicy: { + deadLetterTopic: pubSubClient.topic(deadLetterTopicNameOrId).name, + maxDeliveryAttempts: 10, + }, + }; + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, options); + console.log( + `Created subscription ${subscriptionNameOrId} with dead letter topic ${deadLetterTopicNameOrId}.` + ); + console.log( + 'To process dead letter messages, remember to add a subscription to your dead letter topic.' + ); +} +// [END pubsub_dead_letter_create_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + deadLetterTopicNameOrId = 'YOUR_DEAD_LETTER_TOPIC_NAME_OR_ID' +) { + createSubscriptionWithDeadLetterPolicy( + topicNameOrId, + subscriptionNameOrId, + deadLetterTopicNameOrId + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/createSubscriptionWithOrdering.ts b/samples/typescript/createSubscriptionWithOrdering.ts new file mode 100644 index 000000000..51bc67f9a --- /dev/null +++ b/samples/typescript/createSubscriptionWithOrdering.ts @@ -0,0 +1,72 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create Subscription with ordering enabled +// description: Creates a new subscription with ordering enabled. +// usage: node createSubscriptionWithOrdering.js + +// [START pubsub_enable_subscription_ordering] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createSubscriptionWithOrdering( + topicNameOrId: string, + subscriptionNameOrId: string +) { + // Creates a new subscription + await pubSubClient + .topic(topicNameOrId) + .createSubscription(subscriptionNameOrId, { + enableMessageOrdering: true, + }); + console.log( + `Created subscription ${subscriptionNameOrId} with ordering enabled.` + ); + console.log( + 'To process messages in order, remember to add an ordering key to your messages.' + ); +} +// [END pubsub_enable_subscription_ordering] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + createSubscriptionWithOrdering(topicNameOrId, subscriptionNameOrId).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/createTopic.ts b/samples/typescript/createTopic.ts new file mode 100644 index 000000000..04e26baf3 --- /dev/null +++ b/samples/typescript/createTopic.ts @@ -0,0 +1,54 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Create Topic +// description: Creates a new topic. +// usage: node createTopic.js + +// [START pubsub_create_topic] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function createTopic(topicNameOrId: string) { + // Creates a new topic + await pubSubClient.createTopic(topicNameOrId); + console.log(`Topic ${topicNameOrId} created.`); +} +// [END pubsub_create_topic] + +async function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + createTopic(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/deleteSubscription.ts b/samples/typescript/deleteSubscription.ts new file mode 100644 index 000000000..bfaad1d60 --- /dev/null +++ b/samples/typescript/deleteSubscription.ts @@ -0,0 +1,54 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Delete Subscription +// description: Deletes an existing subscription from a topic. +// usage: node deleteSubscription.js + +// [START pubsub_delete_subscription] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function deleteSubscription(subscriptionNameOrId: string) { + // Deletes the subscription + await pubSubClient.subscription(subscriptionNameOrId).delete(); + console.log(`Subscription ${subscriptionNameOrId} deleted.`); +} +// [END pubsub_delete_subscription] + +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + deleteSubscription(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/deleteTopic.ts b/samples/typescript/deleteTopic.ts new file mode 100644 index 000000000..1253e88f1 --- /dev/null +++ b/samples/typescript/deleteTopic.ts @@ -0,0 +1,59 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Delete Topic +// description: Deletes an existing topic. +// usage: node deleteTopic.js + +// [START pubsub_delete_topic] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function deleteTopic(topicNameOrId: string) { + /** + * TODO(developer): Uncomment the following line to run the sample. + */ + // const topicName = 'my-topic'; + + // Deletes the topic + await pubSubClient.topic(topicNameOrId).delete(); + console.log(`Topic ${topicNameOrId} deleted.`); +} +// [END pubsub_delete_topic] + +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + deleteTopic(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/detachSubscription.ts b/samples/typescript/detachSubscription.ts new file mode 100644 index 000000000..6f391273d --- /dev/null +++ b/samples/typescript/detachSubscription.ts @@ -0,0 +1,65 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to detach subscriptions with the + * Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Detach Subscription +// description: Detaches a subscription from a topic. +// usage: node detachSubscription.js + +// [START pubsub_detach_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function detachSubscription(subscriptionNameOrId: string) { + // Gets the status of the existing subscription + const sub = pubSubClient.subscription(subscriptionNameOrId); + const [detached] = await sub.detached(); + console.log( + `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}` + ); + + await pubSubClient.detachSubscription(subscriptionNameOrId); + console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`); + + const [updatedDetached] = await sub.detached(); + console.log( + `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}` + ); +} +// [END pubsub_detach_subscription] + +function main(subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID') { + detachSubscription(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/getSubscription.ts b/samples/typescript/getSubscription.ts new file mode 100644 index 000000000..cf77b5654 --- /dev/null +++ b/samples/typescript/getSubscription.ts @@ -0,0 +1,58 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Get Subscription +// description: Gets the metadata for a subscription. +// usage: node getSubscription.js + +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function getSubscription(subscriptionNameOrId: string) { + // Gets the metadata for the subscription, as google.pubsub.v1.ISubscription + const [metadata] = await pubSubClient + .subscription(subscriptionNameOrId) + .getMetadata(); + + console.log(`Subscription: ${metadata.name}`); + console.log(`Topic: ${metadata.topic}`); + console.log(`Push config: ${metadata.pushConfig?.pushEndpoint}`); + console.log(`Ack deadline: ${metadata.ackDeadlineSeconds}s`); +} + +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + getSubscription(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/getSubscriptionPolicy.ts b/samples/typescript/getSubscriptionPolicy.ts new file mode 100644 index 000000000..344fd99d4 --- /dev/null +++ b/samples/typescript/getSubscriptionPolicy.ts @@ -0,0 +1,57 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Get Subscription Policy +// description: Gets the IAM policy for a subscription. +// usage: node getSubscriptionPolicy.js + +// [START pubsub_get_subscription_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, Policy} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function getSubscriptionPolicy(subscriptionNameOrId: string) { + // Retrieves the IAM policy for the subscription + const [policy]: [Policy] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.getPolicy(); + + console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`); +} +// [END pubsub_get_subscription_policy] + +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + getSubscriptionPolicy(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/getTopicPolicy.ts b/samples/typescript/getTopicPolicy.ts new file mode 100644 index 000000000..ba95cf3fc --- /dev/null +++ b/samples/typescript/getTopicPolicy.ts @@ -0,0 +1,56 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Get Topic Policy +// description: Gets the IAM policy for a topic. +// usage: node getTopicPolicy.js + +// [START pubsub_get_topic_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, Policy} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function getTopicPolicy(topicNameOrId: string) { + // Retrieves the IAM policy for the topic + const [policy]: [Policy] = await pubSubClient + .topic(topicNameOrId) + .iam.getPolicy(); + console.log('Policy for topic: %j.', policy.bindings); +} +// [END pubsub_get_topic_policy] + +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + getTopicPolicy(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/listAllTopics.ts b/samples/typescript/listAllTopics.ts new file mode 100644 index 000000000..2e5cefe02 --- /dev/null +++ b/samples/typescript/listAllTopics.ts @@ -0,0 +1,50 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: List All Topics +// description: Lists all topics in the current project. +// usage: node listAllTopics.js + +// [START pubsub_list_topics] +// Imports the Google Cloud client library +import {PubSub, Topic} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listAllTopics() { + // Lists all topics in the current project + const [topics] = await pubSubClient.getTopics(); + console.log('Topics:'); + topics.forEach((topic: Topic) => console.log(topic.name)); +} +// [END pubsub_list_topics] + +function main() { + listAllTopics().catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(); diff --git a/samples/typescript/listSubscriptions.ts b/samples/typescript/listSubscriptions.ts new file mode 100644 index 000000000..b1b1a4bde --- /dev/null +++ b/samples/typescript/listSubscriptions.ts @@ -0,0 +1,49 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: List Subscriptions +// description: Lists all subscriptions in the current project. +// usage: node listSubscriptions.js + +// [START pubsub_list_subscriptions] +// Imports the Google Cloud client library +import {PubSub, Subscription} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listSubscriptions() { + // Lists all subscriptions in the current project + const [subscriptions] = await pubSubClient.getSubscriptions(); + console.log('Subscriptions:'); + subscriptions.forEach((subscription: Subscription) => + console.log(subscription.name) + ); +} +// [END pubsub_list_subscriptions] + +function main() { + listSubscriptions().catch(console.error); +} + +main(); diff --git a/samples/typescript/listTopicSubscriptions.ts b/samples/typescript/listTopicSubscriptions.ts new file mode 100644 index 000000000..d21e7578f --- /dev/null +++ b/samples/typescript/listTopicSubscriptions.ts @@ -0,0 +1,60 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: List Subscriptions On a Topic +// description: Lists all subscriptions in the current project, filtering by a topic. +// usage: node listTopicSubscriptions.js + +// [START pubsub_list_topic_subscriptions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, Subscription} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listTopicSubscriptions(topicNameOrId: string) { + // Lists all subscriptions for the topic + const [subscriptions] = await pubSubClient + .topic(topicNameOrId) + .getSubscriptions(); + + console.log(`Subscriptions for ${topicNameOrId}:`); + subscriptions.forEach((subscription: Subscription) => + console.log(subscription.name) + ); +} +// [END pubsub_list_topic_subscriptions] + +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + listTopicSubscriptions(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/listenForErrors.ts b/samples/typescript/listenForErrors.ts new file mode 100644 index 000000000..970a64641 --- /dev/null +++ b/samples/typescript/listenForErrors.ts @@ -0,0 +1,81 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Listen For Errors +// description: Listens to messages and errors for a subscription. +// usage: node listenForErrors.js [timeout-in-seconds] + +// [START pubsub_subscriber_error_listener] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 10; + +// Imports the Google Cloud client library +import {Message, PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +function listenForErrors(subscriptionNameOrId: string, timeout: number) { + // References an existing subscription + const subscription = pubSubClient.subscription(subscriptionNameOrId); + + // Create an event handler to handle messages + const messageHandler = (message: Message) => { + // Do something with the message + console.log(`Message: ${message}`); + + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; + + // Create an event handler to handle errors + const errorHandler = (error: Error) => { + // Do something with the error + console.error(`ERROR: ${error}`); + throw error; + }; + + // Listen for new messages/errors until timeout is hit + subscription.on('message', messageHandler); + subscription.on('error', errorHandler); + + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.removeListener('message', messageHandler); + subscription.removeListener('error', errorHandler); + }, timeout * 1000); +} +// [END pubsub_subscriber_error_listener] + +function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 10 +) { + timeout = Number(timeout); + listenForErrors(subscriptionNameOrId, timeout); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/listenForMessages.ts b/samples/typescript/listenForMessages.ts new file mode 100644 index 000000000..72cb468df --- /dev/null +++ b/samples/typescript/listenForMessages.ts @@ -0,0 +1,78 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Listen For Messages +// description: Listens for messages from a subscription. +// usage: node listenForMessages.js [timeout-in-seconds] + +// [START pubsub_subscriber_async_pull] +// [START pubsub_quickstart_subscriber] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 60; + +// Imports the Google Cloud client library +import {PubSub, Message} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +function listenForMessages(subscriptionNameOrId: string, timeout: number) { + // References an existing subscription + const subscription = pubSubClient.subscription(subscriptionNameOrId); + + // Create an event handler to handle messages + let messageCount = 0; + const messageHandler = (message: Message) => { + console.log(`Received message ${message.id}:`); + console.log(`\tData: ${message.data}`); + console.log(`\tAttributes: ${message.attributes}`); + messageCount += 1; + + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; + + // Listen for new messages until timeout is hit + subscription.on('message', messageHandler); + + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.removeListener('message', messageHandler); + console.log(`${messageCount} message(s) received.`); + }, timeout * 1000); +} +// [END pubsub_subscriber_async_pull] +// [END pubsub_quickstart_subscriber] + +function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 60 +) { + timeout = Number(timeout); + listenForMessages(subscriptionNameOrId, timeout); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/listenWithCustomAttributes.ts b/samples/typescript/listenWithCustomAttributes.ts new file mode 100644 index 000000000..4d4455140 --- /dev/null +++ b/samples/typescript/listenWithCustomAttributes.ts @@ -0,0 +1,79 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Listen For Messages With Custom Attributes +// description: Demonstrates how to receive and process custom attributes on messages. +// usage: node listenWithCustomAttributes.js [timeout-in-seconds] + +// [START pubsub_subscriber_async_pull_custom_attributes] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const timeout = 60; + +// Imports the Google Cloud client library +import {Message, PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function listenWithCustomAttributes( + subscriptionNameOrId: string, + timeout: number +) { + // References an existing subscription, e.g. "my-subscription" + const subscription = pubSubClient.subscription(subscriptionNameOrId); + + // Create an event handler to handle messages + const messageHandler = (message: Message) => { + console.log( + `Received message: id ${message.id}, data ${ + message.data + }, attributes: ${JSON.stringify(message.attributes)}` + ); + + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; + + // Wait a while for the subscription to run. (Part of the sample only.) + subscription.on('message', messageHandler); + setTimeout(() => { + subscription.removeListener('message', messageHandler); + }, timeout * 1000); +} +// [END pubsub_subscriber_async_pull_custom_attributes] + +async function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + timeout = 60 +) { + timeout = Number(timeout); + listenWithCustomAttributes(subscriptionNameOrId, timeout).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/modifyPushConfig.ts b/samples/typescript/modifyPushConfig.ts new file mode 100644 index 000000000..bb26dfdb1 --- /dev/null +++ b/samples/typescript/modifyPushConfig.ts @@ -0,0 +1,69 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Modify Push Configuration +// description: Modifies the configuration of an existing push subscription. +// usage: node modifyPushConfig.js + +// [START pubsub_update_push_configuration] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, CreateSubscriptionOptions} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function modifyPushConfig( + topicNameOrId: string, + subscriptionNameOrId: string +) { + const options: CreateSubscriptionOptions = { + // Set to an HTTPS endpoint of your choice. If necessary, register + // (authorize) the domain on which the server is hosted. + pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`, + }; + + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .modifyPushConfig(options); + console.log(`Modified push config for subscription ${subscriptionNameOrId}.`); +} +// [END pubsub_update_push_configuration] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + modifyPushConfig(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/publishBatchedMessages.ts b/samples/typescript/publishBatchedMessages.ts new file mode 100644 index 000000000..5f7f76cbc --- /dev/null +++ b/samples/typescript/publishBatchedMessages.ts @@ -0,0 +1,91 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Publish Batched Messages +// description: Publishes messages to a topic using custom batching settings. +// usage: node publishBatchedMessages.js [max-messages [max-wait-in-seconds]] + +// [START pubsub_publisher_batch_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicName = 'YOUR_TOPIC_NAME'; +// const data = JSON.stringify({foo: 'bar'}); +// const maxMessages = 10; +// const maxWaitTime = 10; + +// Imports the Google Cloud client library +import {PublishOptions, PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function publishBatchedMessages( + topicNameOrId: string, + data: string, + maxMessages: number, + maxWaitTime: number +) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + + const publishOptions: PublishOptions = { + batching: { + maxMessages: maxMessages, + maxMilliseconds: maxWaitTime * 1000, + }, + }; + const batchPublisher = pubSubClient.topic(topicNameOrId, publishOptions); + + const promises: Promise[] = []; + for (let i = 0; i < 10; i++) { + promises.push( + (async () => { + const messageId = await batchPublisher.publishMessage({ + data: dataBuffer, + }); + console.log(`Message ${messageId} published.`); + })() + ); + } + await Promise.all(promises); +} +// [END pubsub_publisher_batch_settings] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + maxMessages = 10, + maxWaitTime = 10 +) { + maxMessages = Number(maxMessages); + maxWaitTime = Number(maxWaitTime); + publishBatchedMessages(topicNameOrId, data, maxMessages, maxWaitTime).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/publishMessage.ts b/samples/typescript/publishMessage.ts new file mode 100644 index 000000000..86b9e7562 --- /dev/null +++ b/samples/typescript/publishMessage.ts @@ -0,0 +1,71 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Publish Message +// description: Publishes a message to a topic. +// usage: node publishMessage.js + +// [START pubsub_publish_with_error_handler] +// [START pubsub_quickstart_publisher] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function publishMessage(topicNameOrId: string, data: string) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + + try { + const messageId = await pubSubClient + .topic(topicNameOrId) + .publishMessage({data: dataBuffer}); + console.log(`Message ${messageId} published.`); + } catch (error) { + console.error( + `Received error while publishing: ${(error as Error).message}` + ); + process.exitCode = 1; + } +} +// [END pubsub_publish_with_error_handler] +// [END pubsub_quickstart_publisher] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishMessage(topicNameOrId, data).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/publishMessageWithCustomAttributes.ts b/samples/typescript/publishMessageWithCustomAttributes.ts new file mode 100644 index 000000000..9b6619377 --- /dev/null +++ b/samples/typescript/publishMessageWithCustomAttributes.ts @@ -0,0 +1,72 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Publish Message With Custom Attributes +// description: Publishes a message with custom attributes to a topic. +// usage: node publishMessageWithCustomAttributes.js + +// [START pubsub_publish_custom_attributes] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +interface Attributes { + [k: string]: string; +} + +async function publishMessageWithCustomAttributes( + topicNameOrId: string, + data: string +) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + + // Add two custom attributes, origin and username, to the message + const customAttributes: Attributes = { + origin: 'nodejs-sample', + username: 'gcp', + }; + + const messageId = await pubSubClient + .topic(topicNameOrId) + .publishMessage({data: dataBuffer, attributes: customAttributes}); + console.log(`Message ${messageId} published.`); +} +// [END pubsub_publish_custom_attributes] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishMessageWithCustomAttributes(topicNameOrId, data).catch(console.error); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/publishOrderedMessage.ts b/samples/typescript/publishOrderedMessage.ts new file mode 100644 index 000000000..30187a0c2 --- /dev/null +++ b/samples/typescript/publishOrderedMessage.ts @@ -0,0 +1,90 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Publish Ordered Message +// description: Demonstrates how to publish messages to a topic +// with ordering. Please see "Create Subscription With Ordering" for +// information on setting up a subscription that will receive the +// messages with proper ordering. +// usage: node publishOrderedMessage.js + +// [START pubsub_publish_with_ordering_keys] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); +// const orderingKey = 'key1'; + +// Imports the Google Cloud client library +import {PublishOptions, PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub({ + // Sending messages to the same region ensures they are received in order + // even when multiple publishers are used. + apiEndpoint: 'us-east1-pubsub.googleapis.com:443', +}); + +async function publishOrderedMessage( + topicNameOrId: string, + data: string, + orderingKey: string +) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + + // Be sure to set an ordering key that matches other messages + // you want to receive in order, relative to each other. + const message = { + data: dataBuffer, + orderingKey: orderingKey, + }; + + const publishOptions: PublishOptions = { + messageOrdering: true, + }; + + // Publishes the message + const messageId = await pubSubClient + .topic(topicNameOrId, publishOptions) + .publishMessage(message); + + console.log(`Message ${messageId} published.`); + + return messageId; +} +// [END pubsub_publish_with_ordering_keys] + +async function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + orderingKey = 'key1' +) { + await publishOrderedMessage(topicNameOrId, data, orderingKey).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/publishWithRetrySettings.ts b/samples/typescript/publishWithRetrySettings.ts new file mode 100644 index 000000000..1add95d3d --- /dev/null +++ b/samples/typescript/publishWithRetrySettings.ts @@ -0,0 +1,122 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Publish With Retry Settings +// description: Publishes a message to a topic with retry settings. +// usage: node publishWithRetrySettings.js + +// [START pubsub_publisher_retry_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID' +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); + +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +import {v1} from '@google-cloud/pubsub'; + +// Creates a publisher client. +const publisherClient = new v1.PublisherClient({ + // optional auth parameters +}); + +async function publishWithRetrySettings( + projectId: string, + topicNameOrId: string, + data: string +) { + const formattedTopic = publisherClient.projectTopicPath( + projectId, + topicNameOrId + ); + + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + const messagesElement = { + data: dataBuffer, + }; + const messages = [messagesElement]; + + // Build the request + const request = { + topic: formattedTopic, + messages: messages, + }; + + // Retry settings control how the publisher handles retryable failures. Default values are shown. + // The `retryCodes` array determines which grpc errors will trigger an automatic retry. + // The `backoffSettings` object lets you specify the behaviour of retries over time. + const retrySettings = { + retryCodes: [ + 10, // 'ABORTED' + 1, // 'CANCELLED', + 4, // 'DEADLINE_EXCEEDED' + 13, // 'INTERNAL' + 8, // 'RESOURCE_EXHAUSTED' + 14, // 'UNAVAILABLE' + 2, // 'UNKNOWN' + ], + backoffSettings: { + // The initial delay time, in milliseconds, between the completion + // of the first failed request and the initiation of the first retrying request. + initialRetryDelayMillis: 100, + // The multiplier by which to increase the delay time between the completion + // of failed requests, and the initiation of the subsequent retrying request. + retryDelayMultiplier: 1.3, + // The maximum delay time, in milliseconds, between requests. + // When this value is reached, retryDelayMultiplier will no longer be used to increase delay time. + maxRetryDelayMillis: 60000, + // The initial timeout parameter to the request. + initialRpcTimeoutMillis: 5000, + // The multiplier by which to increase the timeout parameter between failed requests. + rpcTimeoutMultiplier: 1.0, + // The maximum timeout parameter, in milliseconds, for a request. When this value is reached, + // rpcTimeoutMultiplier will no longer be used to increase the timeout. + maxRpcTimeoutMillis: 600000, + // The total time, in milliseconds, starting from when the initial request is sent, + // after which an error will be returned, regardless of the retrying attempts made meanwhile. + totalTimeoutMillis: 600000, + }, + }; + + const [response] = await publisherClient.publish(request, { + retry: retrySettings, + }); + console.log(`Message ${response.messageIds} published.`); +} +// [END pubsub_publisher_retry_settings] + +function main( + projectId = 'YOUR_PROJECT_ID', + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}) +) { + publishWithRetrySettings(projectId, topicNameOrId, data).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/quickstart.ts b/samples/typescript/quickstart.ts new file mode 100644 index 000000000..ff81eb791 --- /dev/null +++ b/samples/typescript/quickstart.ts @@ -0,0 +1,60 @@ +// Copyright 2017-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +// sample-metadata: +// title: Quickstart +// description: A quick introduction to using the Pub/Sub client library. +// usage: node quickstart.js + +// [START pubsub_quickstart_create_topic] +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +async function quickstart( + projectId = 'your-project-id', // Your Google Cloud Platform project ID + topicNameOrId = 'my-topic', // Name for the new topic to create + subscriptionName = 'my-sub' // Name for the new subscription to create +) { + // Instantiates a client + const pubsub = new PubSub({projectId}); + + // Creates a new topic + const [topic] = await pubsub.createTopic(topicNameOrId); + console.log(`Topic ${topic.name} created.`); + + // Creates a subscription on that new topic + const [subscription] = await topic.createSubscription(subscriptionName); + + // Receive callbacks for new messages on the subscription + subscription.on('message', message => { + console.log('Received message:', message.data.toString()); + process.exit(0); + }); + + // Receive callbacks for errors on the subscription + subscription.on('error', error => { + console.error('Received error:', error); + process.exit(1); + }); + + // Send a message to the topic + topic.publishMessage({data: Buffer.from('Test message!')}); +} +// [END pubsub_quickstart_create_topic] + +process.on('unhandledRejection', err => { + console.error((err as Error).message); + process.exitCode = 1; +}); +quickstart(...process.argv.slice(2)); diff --git a/samples/typescript/removeDeadLetterPolicy.ts b/samples/typescript/removeDeadLetterPolicy.ts new file mode 100644 index 000000000..b7c11401b --- /dev/null +++ b/samples/typescript/removeDeadLetterPolicy.ts @@ -0,0 +1,70 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Remove Dead Letter Policy +// description: Remove Dead Letter Policy from subscription. +// usage: node removeDeadLetterPolicy.js + +// [START pubsub_dead_letter_remove] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, SubscriptionMetadata} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function removeDeadLetterPolicy( + topicNameOrId: string, + subscriptionNameOrId: string +) { + const metadata: SubscriptionMetadata = { + deadLetterPolicy: null, + }; + + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .setMetadata(metadata); + + console.log( + `Removed dead letter topic from ${subscriptionNameOrId} subscription.` + ); +} +// [END pubsub_dead_letter_remove] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + removeDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/resumePublish.ts b/samples/typescript/resumePublish.ts new file mode 100644 index 000000000..ca1e929b3 --- /dev/null +++ b/samples/typescript/resumePublish.ts @@ -0,0 +1,90 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Resume Publish +// description: Demonstrates how to resume publishing on an ordering key if +// publishing fails for a message. +// usage: node resumePublish.js + +// [START pubsub_resume_publish_with_ordering_keys] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const data = JSON.stringify({foo: 'bar'}); +// const orderingKey = 'key1'; + +// Imports the Google Cloud client library +import {PublishOptions, PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function resumePublish( + topicNameOrId: string, + data: string, + orderingKey: string +) { + // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject) + const dataBuffer = Buffer.from(data); + + const publishOptions: PublishOptions = { + messageOrdering: true, + }; + + // Publishes the message + const publisher = pubSubClient.topic(topicNameOrId, publishOptions); + try { + const message = { + data: dataBuffer, + orderingKey: orderingKey, + }; + const messageId = await publisher.publishMessage(message); + console.log(`Message ${messageId} published.`); + + return messageId; + } catch (e) { + console.log(`Could not publish: ${e}`); + publisher.resumePublishing(orderingKey); + return null; + } +} +// [END pubsub_resume_publish_with_ordering_keys] + +async function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + data = JSON.stringify({foo: 'bar'}), + orderingKey = 'key1' +) { + return await resumePublish(topicNameOrId, data, orderingKey).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +// This needs to be exported directly so that the system tests can find it. +module.exports.resumePublishFunc = resumePublish; + +if (require.main === module) { + main(...process.argv.slice(2)).catch(console.error); +} diff --git a/samples/typescript/setSubscriptionPolicy.ts b/samples/typescript/setSubscriptionPolicy.ts new file mode 100644 index 000000000..915ae4dd0 --- /dev/null +++ b/samples/typescript/setSubscriptionPolicy.ts @@ -0,0 +1,73 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Set Subscription IAM Policy +// description: Sets the IAM policy for a subscription. +// usage: node setSubscriptionPolicy.js + +// [START pubsub_set_subscription_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, Policy} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function setSubscriptionPolicy(subscriptionNameOrId: string) { + // The new IAM policy + const newPolicy: Policy = { + bindings: [ + { + // Add a group as editors + role: 'roles/pubsub.editor', + members: ['group:cloud-logs@google.com'], + }, + { + // Add all users as viewers + role: 'roles/pubsub.viewer', + members: ['allUsers'], + }, + ], + }; + + // Updates the IAM policy for the subscription + const [updatedPolicy] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.setPolicy(newPolicy); + + console.log('Updated policy for subscription: %j', updatedPolicy.bindings); +} +// [END pubsub_set_subscription_policy] + +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + setSubscriptionPolicy(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/setTopicPolicy.ts b/samples/typescript/setTopicPolicy.ts new file mode 100644 index 000000000..31b2a1a21 --- /dev/null +++ b/samples/typescript/setTopicPolicy.ts @@ -0,0 +1,72 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Set Topic IAM Policy +// description: Sets the IAM policy for a topic. +// usage: node setTopicPolicy.js + +// [START pubsub_set_topic_policy] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, Policy} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function setTopicPolicy(topicNameOrId: string) { + // The new IAM policy + const newPolicy: Policy = { + bindings: [ + { + // Add a group as editors + role: 'roles/pubsub.editor', + members: ['group:cloud-logs@google.com'], + }, + { + // Add all users as viewers + role: 'roles/pubsub.viewer', + members: ['allUsers'], + }, + ], + }; + + // Updates the IAM policy for the topic + const [updatedPolicy] = await pubSubClient + .topic(topicNameOrId) + .iam.setPolicy(newPolicy); + console.log('Updated policy for topic: %j', updatedPolicy.bindings); +} +// [END pubsub_set_topic_policy] + +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + setTopicPolicy(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/subscribeWithFlowControlSettings.ts b/samples/typescript/subscribeWithFlowControlSettings.ts new file mode 100644 index 000000000..d9be8dd66 --- /dev/null +++ b/samples/typescript/subscribeWithFlowControlSettings.ts @@ -0,0 +1,102 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Subscribe With Flow Control Settings +// description: Listen to messages with flow control settings, which are +// properties of the client/listener instance. +// usage: node subscribeWithFlowControlSettings.js +// [max-in-progress [timeout-in-seconds]] + +// [START pubsub_subscriber_flow_settings] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// const maxInProgress = 5; +// const timeout = 10; + +// Imports the Google Cloud client library +import {Message, PubSub, SubscriberOptions} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function subscribeWithFlowControlSettings( + subscriptionNameOrId: string, + maxInProgress: number, + timeout: number +) { + const subscriberOptions: SubscriberOptions = { + flowControl: { + maxMessages: maxInProgress, + }, + }; + + // References an existing subscription. + // Note that flow control settings are not persistent across subscribers. + const subscription = pubSubClient.subscription( + subscriptionNameOrId, + subscriberOptions + ); + + console.log( + `Subscriber to subscription ${subscription.name} is ready to receive messages at a controlled volume of ${maxInProgress} messages.` + ); + + const messageHandler = (message: Message) => { + console.log(`Received message: ${message.id}`); + console.log(`\tData: ${message.data}`); + console.log(`\tAttributes: ${message.attributes}`); + + // "Ack" (acknowledge receipt of) the message + message.ack(); + }; + + subscription.on('message', messageHandler); + + // Wait a while for the subscription to run. (Part of the sample only.) + setTimeout(() => { + subscription.close(); + }, timeout * 1000); +} +// [END pubsub_subscriber_flow_settings] + +function main( + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID', + maxInProgress = 1, + timeout = 10 +) { + maxInProgress = Number(maxInProgress); + timeout = Number(timeout); + + subscribeWithFlowControlSettings( + subscriptionNameOrId, + maxInProgress, + timeout + ).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/synchronousPull.ts b/samples/typescript/synchronousPull.ts new file mode 100644 index 000000000..0f6d5807e --- /dev/null +++ b/samples/typescript/synchronousPull.ts @@ -0,0 +1,96 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Synchronous Pull +// description: Receive messages synchronously. +// usage: node synchronousPull.js + +// [START pubsub_subscriber_sync_pull] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +import {v1} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use. +const subClient = new v1.SubscriberClient(); + +async function synchronousPull( + projectId: string, + subscriptionNameOrId: string +) { + // The low level API client requires a name only. + const formattedSubscription = + subscriptionNameOrId.indexOf('/') >= 0 + ? subscriptionNameOrId + : subClient.subscriptionPath(projectId, subscriptionNameOrId); + + // The maximum number of messages returned for this request. + // Pub/Sub may return fewer than the number specified. + const request = { + subscription: formattedSubscription, + maxMessages: 10, + }; + + // The subscriber pulls a specified number of messages. + const [response] = await subClient.pull(request); + + // Process the messages. + const ackIds: string[] = []; + for (const message of response.receivedMessages ?? []) { + console.log(`Received message: ${message.message?.data}`); + if (message.ackId) { + ackIds.push(message.ackId); + } + } + + if (ackIds.length !== 0) { + // Acknowledge all of the messages. You could also acknowledge + // these individually, but this is more efficient. + const ackRequest = { + subscription: formattedSubscription, + ackIds: ackIds, + }; + + await subClient.acknowledge(ackRequest); + } + + console.log('Done.'); +} +// [END pubsub_subscriber_sync_pull] + +function main( + projectId = 'YOUR_PROJECT_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + synchronousPull(projectId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/synchronousPullWithDeliveryAttempts.ts b/samples/typescript/synchronousPullWithDeliveryAttempts.ts new file mode 100644 index 000000000..0cf650e6c --- /dev/null +++ b/samples/typescript/synchronousPullWithDeliveryAttempts.ts @@ -0,0 +1,96 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Synchronous Pull with delivery attempt. +// description: Receive messages synchronously with delivery attempt. +// usage: node synchronousPullWithDeliveryAttempts.js + +// [START pubsub_dead_letter_delivery_attempt] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const projectId = 'YOUR_PROJECT_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library. v1 is for the lower level +// proto access. +import {v1} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use. +const subClient = new v1.SubscriberClient(); + +async function synchronousPullWithDeliveryAttempts( + projectId: string, + subscriptionNameOrId: string +) { + // The low level API client requires a name only. + const formattedSubscription = + subscriptionNameOrId.indexOf('/') >= 0 + ? subscriptionNameOrId + : subClient.subscriptionPath(projectId, subscriptionNameOrId); + + // The maximum number of messages returned for this request. + // Pub/Sub may return fewer than the number specified. + const request = { + subscription: formattedSubscription, + maxMessages: 10, + }; + + // The subscriber pulls a specified number of messages. + const [response] = await subClient.pull(request); + + // Process the messages. + const ackIds: string[] = []; + for (const message of response.receivedMessages ?? []) { + console.log(`Received message: ${message.message?.data}`); + console.log(`Delivery Attempt: ${message.deliveryAttempt}`); + if (message.ackId) { + ackIds.push(message.ackId); + } + } + + // Acknowledge all of the messages. You could also acknowledge + // these individually, but this is more efficient. + const ackRequest = { + subscription: formattedSubscription, + ackIds: ackIds, + }; + await subClient.acknowledge(ackRequest); + + console.log('Done.'); +} +// [END pubsub_dead_letter_delivery_attempt] + +function main( + projectId = 'YOUR_PROJECT_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + synchronousPullWithDeliveryAttempts(projectId, subscriptionNameOrId).catch( + err => { + console.error(err.message); + process.exitCode = 1; + } + ); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/testSubscriptionPermissions.ts b/samples/typescript/testSubscriptionPermissions.ts new file mode 100644 index 000000000..73ae2e0e8 --- /dev/null +++ b/samples/typescript/testSubscriptionPermissions.ts @@ -0,0 +1,62 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Test Subscription Permissions +// description: Tests the permissions for a subscription. +// usage: node testSubscriptionPermissions.js + +// [START pubsub_test_subscription_permissions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function testSubscriptionPermissions(subscriptionNameOrId: string) { + const permissionsToTest = [ + 'pubsub.subscriptions.consume', + 'pubsub.subscriptions.update', + ]; + + // Tests the IAM policy for the specified subscription + const [permissions] = await pubSubClient + .subscription(subscriptionNameOrId) + .iam.testPermissions(permissionsToTest); + + console.log('Tested permissions for subscription: %j', permissions); +} +// [END pubsub_test_subscription_permissions] + +function main(subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID') { + testSubscriptionPermissions(subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/testTopicPermissions.ts b/samples/typescript/testTopicPermissions.ts new file mode 100644 index 000000000..991729615 --- /dev/null +++ b/samples/typescript/testTopicPermissions.ts @@ -0,0 +1,63 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Test Topic Permissions +// description: Tests the permissions for a topic. +// usage: node testTopicPermissions.js + +// [START pubsub_test_topic_permissions] +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function testTopicPermissions(topicNameOrId: string) { + const permissionsToTest = [ + 'pubsub.topics.attachSubscription', + 'pubsub.topics.publish', + 'pubsub.topics.update', + ]; + + // Tests the IAM policy for the specified topic + const [permissions] = await pubSubClient + .topic(topicNameOrId) + .iam.testPermissions(permissionsToTest); + + console.log('Tested permissions for topic: %j', permissions); +} +// [END pubsub_test_topic_permissions] + +function main(topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID') { + testTopicPermissions(topicNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/updateDeadLetterPolicy.ts b/samples/typescript/updateDeadLetterPolicy.ts new file mode 100644 index 000000000..18ba8501f --- /dev/null +++ b/samples/typescript/updateDeadLetterPolicy.ts @@ -0,0 +1,71 @@ +// Copyright 2020-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This application demonstrates how to perform basic operations on + * subscriptions with the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Update Dead Letter Policy +// description: Update Dead Letter Policy in subscription. +// usage: node updateDeadLetterPolicy.js + +// [START pubsub_dead_letter_update_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; + +// Imports the Google Cloud client library +import {PubSub, SubscriptionMetadata} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function updateDeadLetterPolicy( + topicNameOrId: string, + subscriptionNameOrId: string +) { + const metadata: SubscriptionMetadata = { + deadLetterPolicy: { + deadLetterTopic: pubSubClient.topic(topicNameOrId).name, + maxDeliveryAttempts: 15, + }, + }; + + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .setMetadata(metadata); + + console.log('Max delivery attempts updated successfully.'); +} +// [END pubsub_dead_letter_update_subscription] + +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/typescript/validateSchema.ts b/samples/typescript/validateSchema.ts new file mode 100644 index 000000000..bb5c7ea58 --- /dev/null +++ b/samples/typescript/validateSchema.ts @@ -0,0 +1,82 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// sample-metadata: +// title: Validate a schema definition +// description: Validates an Avro-based schema definition before creation (or other use). +// usage: node validateSchema.js + +// (No tag, currently - this sample is non-canonical) +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const schemaText = 'YOUR_SCHEMA_TEXT'; + +// Imports the Google Cloud client library +import {PubSub, SchemaTypes} from '@google-cloud/pubsub'; + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function validateSchema(schemaText: string) { + try { + await pubSubClient.validateSchema({ + type: SchemaTypes.Avro, + definition: schemaText, + }); + console.log('Validated with no error.'); + } catch (e) { + console.log('Received error:', e); + } +} +// (No tag, currently - this sample is non-canonical) + +// Just a sample AVSC definition to try. +const sampleAvsc = ` +{ + "type":"record", + "name":"Province", + "namespace":"utilities", + "doc":"A list of provinces in Canada.", + "fields":[ + { + "name":"name", + "type":"string", + "doc":"The common name of the province." + }, + { + "name":"post_abbr", + "type":"string", + "doc":"The postal code abbreviation of the province." + } + ] +} +`; + +function main(schemaText = sampleAvsc) { + validateSchema(schemaText).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2)); diff --git a/samples/updateDeadLetterPolicy.js b/samples/updateDeadLetterPolicy.js index 2fe4c8fcf..b3d782d00 100644 --- a/samples/updateDeadLetterPolicy.js +++ b/samples/updateDeadLetterPolicy.js @@ -1,4 +1,4 @@ -// Copyright 2020 Google LLC +// Copyright 2020-2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,6 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +// This is a generated sample, using the typeless sample bot. Please +// look for the source TypeScript sample (.ts) for modifications. +'use strict'; + /** * This application demonstrates how to perform basic operations on * subscriptions with the Google Cloud Pub/Sub API. @@ -20,48 +24,49 @@ * at https://cloud.google.com/pubsub/docs. */ -'use strict'; - // sample-metadata: // title: Update Dead Letter Policy // description: Update Dead Letter Policy in subscription. // usage: node updateDeadLetterPolicy.js -function main( - topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', - subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' -) { - // [START pubsub_dead_letter_update_subscription] - /** - * TODO(developer): Uncomment these variables before running the sample. - */ - // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; - // const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; +// [START pubsub_dead_letter_update_subscription] +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID'; +// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID'; - // Imports the Google Cloud client library - const {PubSub} = require('@google-cloud/pubsub'); +// Imports the Google Cloud client library +const {PubSub} = require('@google-cloud/pubsub'); - // Creates a client; cache this for further use - const pubSubClient = new PubSub(); +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); - async function updateDeadLetterPolicy() { - const metadata = { - deadLetterPolicy: { - deadLetterTopic: pubSubClient.topic(topicNameOrId).name, - maxDeliveryAttempts: 15, - }, - }; +async function updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId) { + const metadata = { + deadLetterPolicy: { + deadLetterTopic: pubSubClient.topic(topicNameOrId).name, + maxDeliveryAttempts: 15, + }, + }; - await pubSubClient - .topic(topicNameOrId) - .subscription(subscriptionNameOrId) - .setMetadata(metadata); + await pubSubClient + .topic(topicNameOrId) + .subscription(subscriptionNameOrId) + .setMetadata(metadata); - console.log('Max delivery attempts updated successfully.'); - } + console.log('Max delivery attempts updated successfully.'); +} +// [END pubsub_dead_letter_update_subscription] - updateDeadLetterPolicy().catch(console.error); - // [END pubsub_dead_letter_update_subscription] +function main( + topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID', + subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID' +) { + updateDeadLetterPolicy(topicNameOrId, subscriptionNameOrId).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); } main(...process.argv.slice(2)); diff --git a/samples/validateSchema.js b/samples/validateSchema.js new file mode 100644 index 000000000..bd4201ec6 --- /dev/null +++ b/samples/validateSchema.js @@ -0,0 +1,86 @@ +// Copyright 2019-2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// 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. + +/** + * This sample demonstrates how to perform basic operations on topics with + * the Google Cloud Pub/Sub API. + * + * For more information, see the README.md under /pubsub and the documentation + * at https://cloud.google.com/pubsub/docs. + */ + +// This is a generated sample. Please see typescript/README.md for more info. + +'use strict'; + +// sample-metadata: +// title: Validate a schema definition +// description: Validates an Avro-based schema definition before creation (or other use). +// usage: node validateSchema.js + +// (No tag, currently - this sample is non-canonical) +/** + * TODO(developer): Uncomment this variable before running the sample. + */ +// const schemaText = 'YOUR_SCHEMA_TEXT'; + +// Imports the Google Cloud client library +const {PubSub, SchemaTypes} = require('@google-cloud/pubsub'); + +// Creates a client; cache this for further use +const pubSubClient = new PubSub(); + +async function validateSchema(schemaText) { + try { + await pubSubClient.validateSchema({ + type: SchemaTypes.Avro, + definition: schemaText, + }); + console.log('Validated with no error.'); + } catch (e) { + console.log('Received error:', e); + } +} +// (No tag, currently - this sample is non-canonical) + +// Just a sample AVSC definition to try. +const sampleAvsc = ` +{ + "type":"record", + "name":"Province", + "namespace":"utilities", + "doc":"A list of provinces in Canada.", + "fields":[ + { + "name":"name", + "type":"string", + "doc":"The common name of the province." + }, + { + "name":"post_abbr", + "type":"string", + "doc":"The postal code abbreviation of the province." + } + ] +} +`; + +function main(schemaText = sampleAvsc) { + validateSchema(schemaText).catch(err => { + console.error(err.message); + process.exitCode = 1; + }); +} + +main(...process.argv.slice(2));