Topic

Topic

A Topic object allows you to interact with a Cloud Pub/Sub topic.

Constructor

new Topic(pubsub, name, optionsopt)

Parameters:
Name Type Attributes Description
pubsub PubSub

PubSub object.

name string

Name of the topic.

options PublishOptions <optional>

Publisher configuration object.

Examples
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

To enable message ordering, set `enableMessageOrdering` to true. Please note that this does not persist to an actual topic.

const topic = pubsub.topic('ordered-topic', {enableMessageOrdering: true});

Members

iam

IAM (Identity and Access Management) allows you to set permissions on individual resources and offers a wider range of roles: editor, owner, publisher, subscriber, and viewer. This gives you greater flexibility and allows you to set more fine-grained access control.

The IAM access control features described in this document are Beta, including the API methods to get and set IAM policies, and to test IAM permissions. Cloud Pub/Sub's use of IAM features is not covered by any SLA or deprecation policy, and may be subject to backward-incompatible changes.

Mixes In:
See:
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

//-
// Get the IAM policy for your topic.
//-
topic.iam.getPolicy((err, policy) => {
  console.log(policy);
});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.iam.getPolicy().then((data) => {
  const policy = data[0];
  const apiResponse = data[1];
});

name

The fully qualified name of this topic.

parent

The parent PubSub instance of this topic instance.

pubsub

The parent PubSub instance of this topic instance.

Methods

create(gaxOptsopt, callbackopt) → {Promise.<CreateTopicResponse>}

Create a topic.

Parameters:
Name Type Attributes Description
gaxOpts object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.

callback CreateTopicCallback <optional>

Callback function.

Returns:
Type Description
Promise.<CreateTopicResponse>
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.create((err, topic, apiResponse) => {
  if (!err) {
    // The topic was created successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.create().then((data) => {
  const topic = data[0];
  const apiResponse = data[1];
});

createSubscription(name, optionsopt, callbackopt) → {Promise.<CreateSubscriptionResponse>}

Create a subscription to this topic.

Parameters:
Name Type Attributes Description
name string

The name of the subscription.

options CreateSubscriptionRequest <optional>

See a Subscription resource.

callback CreateSubscriptionCallback <optional>

Callback function.

Returns:
Type Description
Promise.<CreateSubscriptionResponse>
See:
Throws:

If subscription name is omitted.

Type
Error
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');
const callback = function(err, subscription, apiResponse) {};

// Without specifying any options.
topic.createSubscription('newMessages', callback);

// With options.
topic.createSubscription('newMessages', {
  ackDeadlineSeconds: 90
}, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.createSubscription('newMessages').then((data) => {
  const subscription = data[0];
  const apiResponse = data[1];
});

delete(gaxOptsopt, callbackopt)

Delete the topic. This will not delete subscriptions to this topic.

Parameters:
Name Type Attributes Description
gaxOpts object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.

callback function <optional>

The callback function.

Properties
Name Type Attributes Description
err error <nullable>

An error returned while making this request.

apiResponse object

Raw API response.

See:
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.delete((err, apiResponse) => {});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.delete().then((data) => {
  const apiResponse = data[0];
});

exists(callbackopt) → {Promise.<TopicExistsResponse>}

Check if a topic exists.

Parameters:
Name Type Attributes Description
callback TopicExistsCallback <optional>

Callback function.

Returns:
Type Description
Promise.<TopicExistsResponse>
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.exists((err, exists) => {});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.exists().then((data) => {
  const exists = data[0];
});

flush(callbackopt) → {Promise.<EmptyResponse>}

Immediately sends all remaining queued data. This is mostly useful if you are planning to call close() on the PubSub object that holds the server connections.

Parameters:
Name Type Attributes Description
callback EmptyCallback <optional>

Callback function.

Returns:
Type Description
Promise.<EmptyResponse>

get(gaxOptsopt, callbackopt) → {Promise.<GetTopicResponse>}

Get a topic if it exists.

Parameters:
Name Type Attributes Description
gaxOpts object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.

Properties
Name Type Attributes Default Description
autoCreate boolean <optional>
false

Automatically create the topic does not already exist.

callback GetTopicCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetTopicResponse>
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.get((err, topic, apiResponse) => {
  // The `topic` data has been populated.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.get().then((data) => {
  const topic = data[0];
  const apiResponse = data[1];
});

getMetadata(gaxOptsopt, callbackopt) → {Promise.<GetTopicMetadataResponse>}

Get the official representation of this topic from the API.

Parameters:
Name Type Attributes Description
gaxOpts object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.

callback GetTopicMetadataCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetTopicMetadataResponse>
See:
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.getMetadata((err, apiResponse) => {});

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.getMetadata().then((data) => {
  const apiResponse = data[0];
});

getPublishOptionDefaults()

Get the default publisher options. These may be modified and passed back into Topic#setPublishOptions.

Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

const defaults = topic.getPublishOptionDefaults();
defaults.batching.maxMilliseconds = 10;
topic.setPublishOptions(defaults);

getSubscriptions(queryopt, callbackopt) → {Promise.<GetSubscriptionsResponse>}

Get a list of the subscriptions registered to this topic. You may optionally provide a query object as the first argument to customize the response.

Your provided callback will be invoked with an error object if an API error occurred or an array of {module:pubsub/subscription} objects.

Parameters:
Name Type Attributes Description
query GetSubscriptionsRequest <optional>

Query object for listing subscriptions.

callback GetSubscriptionsCallback <optional>

Callback function.

Returns:
Type Description
Promise.<GetSubscriptionsResponse>
See:
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.getSubscriptions((err, subscriptions) => {
  // subscriptions is an array of `Subscription` objects.
});

// Customize the query.
topic.getSubscriptions({
  pageSize: 3
}, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
topic.getSubscriptions().then((data) => {
  const subscriptions = data[0];
});

publish(data, attributesopt, callbackopt) → {Promise.<PublishResponse>}

Publish the provided message.

Deprecated: Please use Topic#publishMessage.

Parameters:
Name Type Attributes Description
data buffer

The message data. This must come in the form of a Buffer object.

attributes object.<string, string> <optional>

Attributes for this message.

callback PublishCallback <optional>

Callback function.

Returns:
Type Description
Promise.<PublishResponse>
Throws:
  • If data is not a Buffer object.

    Type
    TypeError
  • If any value in attributes object is not a string.

    Type
    TypeError
Examples
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');
const data = Buffer.from('Hello, world!');

const callback = (err, messageId) => {
  if (err) {
    // Error handling omitted.
  }
};

topic.publish(data, callback);

Optionally you can provide an object containing attributes for the message. Note that all values in the object must be strings.

const attributes = {
  key: 'value'
};

topic.publish(data, attributes, callback);

If the callback is omitted, we'll return a Promise.

topic.publish(data).then((messageId) => {});

publishJSON(json, attributesopt, callbackopt) → {Promise.<PublishResponse>}

Publish the provided JSON. It should be noted that all messages published are done so in the form of a Buffer. This is simply a convenience method that will transform JSON into a Buffer before publishing. Subscription objects will always return message data in the form of a Buffer, so any JSON published will require manual deserialization.

Deprecated: Please use the `json` option via Topic#publishMessage.

Parameters:
Name Type Attributes Description
json object

The JSON data to publish.

attributes object <optional>

Attributes for this message.

callback PublishCallback <optional>

Callback function.

Returns:
Type Description
Promise.<PublishResponse>
Throws:

If non-object data is provided.

Type
Error
Examples
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topic = pubsub.topic('my-topic');

const data = {
  foo: 'bar'
};

const callback = (err, messageId) => {
  if (err) {
    // Error handling omitted.
  }
};

topic.publishJSON(data, callback);

Optionally you can provide an object containing attributes for the message. Note that all values in the object must be strings.

const attributes = {
  key: 'value'
};

topic.publishJSON(data, attributes, callback);

If the callback is omitted, we'll return a Promise.

topic.publishJSON(data).then((messageId) => {});

publishMessage(message, callbackopt) → {Promise.<PublishResponse>}

Publish the provided message.

Parameters:
Name Type Attributes Description
message MessageOptions

Message object.

callback PublishCallback <optional>

Callback function.

Returns:
Type Description
Promise.<PublishResponse>
Throws:
  • If data is not a Buffer object.

    Type
    TypeError
  • If any value in attributes object is not a string.

    Type
    TypeError
Examples
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topic = pubsub.topic('my-topic');

const data = Buffer.from('Hello, world!');

const callback = (err, messageId) => {
  if (err) {
    // Error handling omitted.
  }
};

topic.publishMessage({data}, callback);

Publish JSON message data.

const json = {foo: 'bar'};

topic.publishMessage({json}, callback);

To publish messages in order (this is still experimental), make sure message ordering is enabled and provide an ordering key

const topic = pubsub.topic('ordered-topic', {messageOrdering: true});
const orderingKey = 'my-key';

topic.publishMessage({data, orderingKey}, callback);

If the callback is omitted, we'll return a Promise.

const [messageId] = await topic.publishMessage({data});

resumePublishing(orderingKey)

In the event that the client fails to publish an ordered message, all subsequent publish calls using the same ordering key will fail. Calling this method will disregard the publish failure, allowing the supplied ordering key to be used again in the future.

Parameters:
Name Type Description
orderingKey string

The ordering key in question.

Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topic = pubsub.topic('my-topic', {messageOrdering: true});

const orderingKey = 'foo';
const data = Buffer.from('Hello, order!');

topic.publishMessage({data, orderingKey}, err => {
  if (err) {
    topic.resumePublishing(orderingKey);
  }
});

setMetadata(metadata, gaxOptsopt, callbackopt) → {Promise.<SetTopicMetadataResponse>}

Updates the topic.

Parameters:
Name Type Attributes Description
metadata object

The fields to update. This should be structured like a Topic object.

gaxOpts object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html.

callback SetTopicMetadataCallback <optional>

Callback function.

Returns:
Type Description
Promise.<SetTopicMetadataResponse>
See:
Examples
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');
const metadata = {
  labels: {foo: 'bar'}
};

topic.setMetadata(metadata, err => {
  if (err) {
    // Error handling omitted.
  }
});

If the callback is omitted, we'll return a Promise.

topic.setMetadata(metadata).then((data) => {
  const apiResponse = data[0];
});

setPublishOptions(options)

Set the publisher options.

Parameters:
Name Type Description
options PublishOptions

The publisher options.

Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');

topic.setPublishOptions({
  batching: {
    maxMilliseconds: 10
  }
});

subscription(name, optionsopt) → {Subscription}

Create a Subscription object. This command by itself will not run any API requests. You will receive a {module:pubsub/subscription} object, which will allow you to interact with a subscription.

Parameters:
Name Type Attributes Description
name string

Name of the subscription.

options SubscriberOptions <optional>

Configuration object.

Returns:
Type Description
Subscription
Throws:

If subscription name is omitted.

Type
Error
Example
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();

const topic = pubsub.topic('my-topic');
const subscription = topic.subscription('my-subscription');

// Register a listener for `message` events.
subscription.on('message', (message) => {
  // Called every time a message is received.
  // message.id = ID of the message.
  // message.ackId = ID used to acknowledge the message receival.
  // message.data = Contents of the message.
  // message.attributes = Attributes of the message.
  // message.publishTime = Timestamp when Pub/Sub received the message.
});