Class Topic (4.4.0)

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

Package

@google-cloud/pubsub

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});

Constructors

(constructor)(pubsub, name, options)

constructor(pubsub: PubSub, name: string, options?: PublishOptions);

Constructs a new instance of the Topic class

Parameters
Name Description
pubsub PubSub
name string
options PublishOptions

Properties

getSubscriptionsStream

getSubscriptionsStream: () => ObjectStream<Subscription>;

iam

iam: IAM;

metadata

metadata?: TopicMetadata;

name

name: string;

parent

parent: PubSub;

publisher

publisher: Publisher;

pubsub

pubsub: PubSub;

request

request: typeof PubSub.prototype.request;

Methods

create(gaxOpts)

create(gaxOpts?: CallOptions): Promise<CreateTopicResponse>;

Create a topic.

Parameter
Name Description
gaxOpts CallOptions

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

Returns
Type Description
Promise<CreateTopicResponse>

{Promise

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];
});

create(callback)

create(callback: CreateTopicCallback): void;
Parameter
Name Description
callback CreateTopicCallback
Returns
Type Description
void

create(gaxOpts, callback)

create(gaxOpts: CallOptions, callback: CreateTopicCallback): void;
Parameters
Name Description
gaxOpts CallOptions
callback CreateTopicCallback
Returns
Type Description
void

createSubscription(name, callback)

createSubscription(name: string, callback: CreateSubscriptionCallback): void;

Create a subscription to this topic.

Parameters
Name Description
name string

The name of the subscription.

callback CreateSubscriptionCallback

Callback function.

Returns
Type Description
void

{Promise

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];
});

createSubscription(name, options)

createSubscription(name: string, options?: CreateSubscriptionOptions): Promise<CreateSubscriptionResponse>;
Parameters
Name Description
name string
options CreateSubscriptionOptions
Returns
Type Description
Promise<CreateSubscriptionResponse>

createSubscription(name, options, callback)

createSubscription(name: string, options: CreateSubscriptionOptions, callback: CreateSubscriptionCallback): void;
Parameters
Name Description
name string
options CreateSubscriptionOptions
callback CreateSubscriptionCallback
Returns
Type Description
void

delete(callback)

delete(callback: EmptyCallback): void;

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

Parameter
Name Description
callback EmptyCallback

The callback function.

Returns
Type Description
void
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];
});

delete(gaxOpts)

delete(gaxOpts?: CallOptions): Promise<EmptyResponse>;
Parameter
Name Description
gaxOpts CallOptions
Returns
Type Description
Promise<EmptyResponse>

delete(gaxOpts, callback)

delete(gaxOpts: CallOptions, callback: EmptyCallback): void;
Parameters
Name Description
gaxOpts CallOptions
callback EmptyCallback
Returns
Type Description
void

exists()

exists(): Promise<ExistsResponse>;

Check if a topic exists.

Returns
Type Description
Promise<ExistsResponse>

{Promise

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];
});

exists(callback)

exists(callback: ExistsCallback): void;
Parameter
Name Description
callback ExistsCallback
Returns
Type Description
void

flowControlled()

flowControlled(): FlowControlledPublisher;

Creates a FlowControlledPublisher for this Topic.

FlowControlledPublisher is a helper that lets you control how many messages are simultaneously queued to send, to avoid ballooning memory usage on a low bandwidth connection to Pub/Sub.

Note that it's perfectly fine to create more than one on the same Topic. The actual flow control settings on the Topic will apply across all FlowControlledPublisher objects on that Topic.

Returns
Type Description
FlowControlledPublisher

{FlowControlledPublisher} The flow control helper.

flush()

flush(): Promise<void>;

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.

Returns
Type Description
Promise<void>

{Promise

flush(callback)

flush(callback: EmptyCallback): void;
Parameter
Name Description
callback EmptyCallback
Returns
Type Description
void

formatName_(projectId, name)

static formatName_(projectId: string, name: string): string;

Format the name of a topic. A Topic's full name is in the format of 'projects/{projectId}/topics/{topicName}'.

{string}

Parameters
Name Description
projectId string
name string
Returns
Type Description
string

get(callback)

get(callback: GetTopicCallback): void;

Get a topic if it exists.

Parameter
Name Description
callback GetTopicCallback

Callback function.

Returns
Type Description
void

{Promise

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];
});

get(gaxOpts)

get(gaxOpts?: GetTopicOptions): Promise<GetTopicResponse>;
Parameter
Name Description
gaxOpts GetTopicOptions
Returns
Type Description
Promise<GetTopicResponse>

get(gaxOpts, callback)

get(gaxOpts: GetTopicOptions, callback: GetTopicCallback): void;
Parameters
Name Description
gaxOpts GetTopicOptions
callback GetTopicCallback
Returns
Type Description
void

getMetadata(callback)

getMetadata(callback: GetTopicMetadataCallback): void;

Get the official representation of this topic from the API.

Parameter
Name Description
callback GetTopicMetadataCallback

Callback function.

Returns
Type Description
void

{Promise

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];
});

getMetadata(gaxOpts, callback)

getMetadata(gaxOpts: CallOptions, callback: GetTopicMetadataCallback): void;
Parameters
Name Description
gaxOpts CallOptions
callback GetTopicMetadataCallback
Returns
Type Description
void

getMetadata(gaxOpts)

getMetadata(gaxOpts?: CallOptions): Promise<GetTopicMetadataResponse>;
Parameter
Name Description
gaxOpts CallOptions
Returns
Type Description
Promise<GetTopicMetadataResponse>

getPublishOptionDefaults()

getPublishOptionDefaults(): PublishOptions;

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

Returns
Type Description
PublishOptions
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(callback)

getSubscriptions(callback: GetTopicSubscriptionsCallback): void;

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.

Parameter
Name Description
callback GetTopicSubscriptionsCallback

Callback function.

Returns
Type Description
void

{Promise

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];
});

getSubscriptions(options, callback)

getSubscriptions(options: PageOptions, callback: GetTopicSubscriptionsCallback): void;
Parameters
Name Description
options PageOptions
callback GetTopicSubscriptionsCallback
Returns
Type Description
void

getSubscriptions(options)

getSubscriptions(options?: PageOptions): Promise<GetTopicSubscriptionsResponse>;
Parameter
Name Description
options PageOptions
Returns
Type Description
Promise<GetTopicSubscriptionsResponse>

publish(data, attributes)

publish(data: Buffer, attributes?: Attributes): Promise<string>;

Publish the provided message.

Parameters
Name Description
data Buffer

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

attributes Attributes

Attributes for this message.

Returns
Type Description
Promise<string>

{Promise

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) => {});

publish(data, callback)

publish(data: Buffer, callback: PublishCallback): void;
Parameters
Name Description
data Buffer
callback PublishCallback
Returns
Type Description
void

publish(data, attributes, callback)

publish(data: Buffer, attributes: Attributes, callback: PublishCallback): void;
Parameters
Name Description
data Buffer
attributes Attributes
callback PublishCallback
Returns
Type Description
void

publishJSON(json, attributes)

publishJSON(json: object, attributes?: Attributes): Promise<string>;

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. objects will always return message data in the form of a Buffer, so any JSON published will require manual deserialization.

Parameters
Name Description
json object

The JSON data to publish.

attributes Attributes

Attributes for this message.

Returns
Type Description
Promise<string>

{Promise

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) => {});

publishJSON(json, callback)

publishJSON(json: object, callback: PublishCallback): void;
Parameters
Name Description
json object
callback PublishCallback
Returns
Type Description
void

publishJSON(json, attributes, callback)

publishJSON(json: object, attributes: Attributes, callback: PublishCallback): void;
Parameters
Name Description
json object
attributes Attributes
callback PublishCallback
Returns
Type Description
void

publishMessage(message)

publishMessage(message: MessageOptions): Promise<string>;

Publish the provided message.

Parameter
Name Description
message MessageOptions

Message object.

Returns
Type Description
Promise<string>

{Promise

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});

publishMessage(message, callback)

publishMessage(message: MessageOptions, callback: PublishCallback): void;
Parameters
Name Description
message MessageOptions
callback PublishCallback
Returns
Type Description
void

resumePublishing(orderingKey)

resumePublishing(orderingKey: string): void;

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.

Parameter
Name Description
orderingKey string

The ordering key in question.

Returns
Type Description
void
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(options, gaxOpts)

setMetadata(options: TopicMetadata, gaxOpts?: CallOptions): Promise<SetTopicMetadataResponse>;

Updates the topic.

Parameters
Name Description
options TopicMetadata
gaxOpts CallOptions

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

Returns
Type Description
Promise<SetTopicMetadataResponse>

{Promise

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];
});

setMetadata(options, callback)

setMetadata(options: TopicMetadata, callback: SetTopicMetadataCallback): void;
Parameters
Name Description
options TopicMetadata
callback SetTopicMetadataCallback
Returns
Type Description
void

setMetadata(options, gaxOpts, callback)

setMetadata(options: TopicMetadata, gaxOpts: CallOptions, callback: SetTopicMetadataCallback): void;
Parameters
Name Description
options TopicMetadata
gaxOpts CallOptions
callback SetTopicMetadataCallback
Returns
Type Description
void

setPublishOptions(options)

setPublishOptions(options: PublishOptions): void;

Set the publisher options.

Parameter
Name Description
options PublishOptions

The publisher options.

Returns
Type Description
void
Example

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

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

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

subscription(name, options)

subscription(name: string, options?: SubscriptionOptions): 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 Description
name string

Name of the subscription.

options SubscriptionOptions

Configuration object. {Subscription}

Returns
Type Description
Subscription
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.
});