PubSub

PubSub

Cloud Pub/Sub is a reliable, many-to-many, asynchronous messaging service from Cloud Platform.

Constructor

new PubSub(optionsopt)

Parameters:
Name Type Attributes Description
options ClientConfig <optional>

Configuration options.

See:
Examples
Import the client library
```
const {PubSub} = require('@google-cloud/pubsub');

```
Create a client that uses <a href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application Default Credentials (ADC)</a>:
```
const pubsub = new PubSub();

```
Create a client with <a href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit credentials</a>:
```
const pubsub = new PubSub({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'
});

```

Full quickstart example:

// 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!')});
}

Members

isEmulator

isIdResolved

Returns true if we have actually resolved the full project name.

v1

Reference to internal generated clients, advanced use only.

Properties:
Name Type Description
PublisherClient constructor

Reference to v1.PublisherClient.

SubscriberClient constructor

Reference to v1.SubscriberClient.

See:

Methods

(async) createSchema(schemaId, type, definition, optionsopt) → {Promise.<Schema>}

Create a schema in the project.

Parameters:
Name Type Attributes Description
schemaId string

The name or ID of the subscription.

type SchemaType

The type of the schema (Protobuf, Avro, etc).

definition string

The text describing the schema in terms of the type.

options object <optional>

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

Returns:
Type Description
Promise.<Schema>
See:
Throws:
  • If a schema ID or name is not provided.

    Type
    Error
  • If an invalid SchemaType is provided.

    Type
    Error
  • If an invalid schema definition is provided.

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

await pubsub.createSchema(
  'messageType',
  SchemaTypes.Avro,
  '{...avro definition...}'
);
```

(async) getClientConfig() → {Promise.<ClientConfig>}

Retrieve a client configuration, suitable for passing into a GAPIC 'v1' class constructor. This will fill out projectId, emulator URLs, and so forth.

Returns:
Type Description
Promise.<ClientConfig>

the filled client configuration.

(async) getSchemaClient() → {Promise.<SchemaServiceClient>}

Gets a schema client, creating one if needed. This is a shortcut for new v1.SchemaServiceClient(await pubsub.getClientConfig()).

Returns:
Type Description
Promise.<SchemaServiceClient>

getSnapshotsStream(optionsopt) → {ReadableStream}

Get a list of the Snapshot objects as a readable object stream.

Parameters:
Name Type Attributes Description
options GetSnapshotsRequest <optional>

Configuration object. See PubSub#getSnapshots for a complete list of options.

Returns:
Type Description
ReadableStream

A readable stream of Snapshot instances.

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

pubsub.getSnapshotsStream()
  .on('error', console.error)
  .on('data', function(snapshot) {
    // snapshot is a Snapshot object.
  })
  .on('end', function() {
    // All snapshots retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getSnapshotsStream()
  .on('data', function(snapshot) {
    this.end();
  });
```

getSubscriptionsStream(optionsopt) → {ReadableStream}

Get a list of the Subscription objects registered to all of your project's topics as a readable object stream.

Parameters:
Name Type Attributes Description
options GetSubscriptionsRequest <optional>

Configuration object. See PubSub#getSubscriptions for a complete list of options.

Returns:
Type Description
ReadableStream

A readable stream of Subscription instances.

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

pubsub.getSubscriptionsStream()
  .on('error', console.error)
  .on('data', function(subscription) {
    // subscription is a Subscription object.
  })
  .on('end', function() {
    // All subscriptions retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getSubscriptionsStream()
  .on('data', function(subscription) {
    this.end();
  });
```

getSubscriptionsStream(optionsopt) → {ReadableStream}

Get a list of the {module:pubsub/subscription} objects registered to this topic as a readable object stream.

Parameters:
Name Type Attributes Description
options GetSubscriptionsRequest <optional>

Configuration object. See PubSub#getSubscriptions for a complete list of options.

Returns:
Type Description
ReadableStream

A readable stream of Subscription instances.

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

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

topic.getSubscriptionsStream()
  .on('error', console.error)
  .on('data', (subscription) => {
    // subscription is a Subscription object.
  })
  .on('end', () => {
    // All subscriptions retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
topic.getSubscriptionsStream()
  .on('data', function(subscription) {
    this.end();
  });
```

getTopicsStream(optionsopt) → {ReadableStream}

Get a list of the {module:pubsub/topic} objects registered to your project as a readable object stream.

Parameters:
Name Type Attributes Description
options GetTopicsRequest <optional>

Configuration object. See PubSub#getTopics for a complete list of options.

Returns:
Type Description
ReadableStream

A readable stream of Topic instances.

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

pubsub.getTopicsStream()
  .on('error', console.error)
  .on('data', function(topic) {
    // topic is a Topic object.
  })
  .on('end', function() {
    // All topics retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
pubsub.getTopicsStream()
  .on('data', function(topic) {
    this.end();
  });
```

(async, generator) listSchemas(viewopt, optionsopt) → {AsyncIterable.<ISchema>}

Get a list of schemas associated with your project.

The returned AsyncIterable will resolve to google.pubsub.v1.ISchema objects.

This method returns an async iterable. These objects can be adapted to work in a Promise/then framework, as well as with callbacks, but this discussion is considered out of scope for these docs.

Parameters:
Name Type Attributes Description
view google.pubsub.v1.SchemaView <optional>

The type of schema objects requested, which should be an enum value from SchemaViews. Defaults to Full.

options object <optional>

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

Returns:
Type Description
AsyncIterable.<ISchema>
See:
Example
```
for await (const s of pubsub.listSchemas()) {
  const moreInfo = await s.get();
}
```

schema(name) → {Schema}

Create a Schema object, representing a schema within the project. See PubSub#createSchema or Schema#create to create a schema.

Parameters:
Name Type Description
name string

The ID or name of the schema.

Returns:
Type Description
Schema

A Schema instance.

Throws:

If a name is not provided.

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

const schema = pubsub.schema('my-schema');
```

snapshot(name) → {Snapshot}

Create a Snapshot object. See Subscription#createSnapshot to create a snapshot.

Parameters:
Name Type Description
name string

The name of the snapshot.

Returns:
Type Description
Snapshot

A Snapshot instance.

Throws:

If a name is not provided.

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

const snapshot = pubsub.snapshot('my-snapshot');
```

subscription(name, optionsopt) → {Subscription}

Create a Subscription object. This command by itself will not run any API requests. You will receive a 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

A Subscription instance.

Throws:

If subscription name is omitted.

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

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

// Register a listener for `message` events.
subscription.on('message', function(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 = Date when Pub/Sub received the message.
});
```

topic(name, optionsopt) → {Topic}

Create a Topic object. See PubSub#createTopic to create a topic.

Parameters:
Name Type Attributes Description
name string

The name of the topic.

options PublishOptions <optional>

Publisher configuration object.

Returns:
Type Description
Topic

A Topic instance.

Throws:

If a name is not provided.

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

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

(async) validateSchema(schema, optionsopt) → {Promise.<void>}

Validate a schema definition.

Parameters:
Name Type Attributes Description
schema ISchema

The schema definition you wish to validate.

options object <optional>

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

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

if the validation fails.

Type
Error