Node.js

Initialize

Install Berlioz SDK:

$ npm install --save berlioz-sdk berlioz-gcp

Include Berlioz SDK:

const berlioz = require('berlioz-sdk');
berlioz.addon(require('berlioz-gcp'));

Accessing Pub/Sub Publisher Client

const PubSub = require('@google-cloud/pubsub');
berlioz.queue('<pubsub-name>').client('pubsub-publisher')

Wraps GCP Storage sdk and return instance of PublisherClient. All operations return Promise.

When accessing the publisher client the topic id would be automatically populated.

Accessing Pub/Sub Subscriber Client

const PubSub = require('@google-cloud/pubsub');
berlioz.queue('<pubsub-name>').client('pubsub-subscriber')

Wraps GCP Storage sdk and return instance of SubscriberClient. All operations return Promise.

When accessing the publisher client the subscription id would be automatically populated.

Examples

Publishing Message

const msgRequest = {
    messages: [
        {
            data: Buffer.from('Hello World!')
        }
    ]
};
berlioz.queue('jobs').client('pubsub-publisher')
    .publish(msgRequest);
});

Pulling Message

Once SubscriptionId is set, messages can be pulled.

berlioz.queue('jobs').client(PubSub, 'pubsub-subscriber').pull({ maxMessages: 5 })
    .then(responses => {
        console.log(responses);
        return Promise.all(responses.map(message => acknowledge(message)));
    })
    .catch(reason => {
        if (reason.code == 4) {
            // Pub/Sub returns DEADLINE_EXCEEDED error
            // if there are no messages inthe queue.
            return;
        }
        throw reason;
    })

Acknowledge Message

Message should be acknowledge once processing is complete.

var ackRequest = {
    ackIds: [message.ackId]
}
berlioz.queue('jobs').client('pubsub-subscriber').acknowledge(ackRequest);