3

I'm trying to setup a GCP PubSub service that will work with a push type subscription. However it's impossible to create one in the developement stage, while I have no accessible endpoints.

I assumed that the emulator would allow me to specify a local endpoint so that the service would run flawlessly in local.

However, after setting it up, I couldn't find a way in the Node.js pubsub library to create a subscription while specifying its options, there is no example for this.

This is the pretty simple way to create a simple, default, pull, subscription:

await pubsub.topic(topicName).createSubscription(subscriptionName);
Touko
  • 11,359
  • 16
  • 75
  • 105
Nicolò Gasparini
  • 2,228
  • 2
  • 24
  • 53

2 Answers2

6

Here is an example of how you would set up push subscription. It is the same as how you would set it up if you were running in the actual Pub/Sub environment. Specify ‘pushEndpoint’ as your local endpoint. When running on the emulator, it will not require authentication for your endpoint.

You can do something like the following:

 // Imports the Google Cloud client library
 const {PubSub} = require('@google-cloud/pubsub');

 // Creates a client
 const pubsub = new PubSub();

 const options = {
   pushConfig: {
     // Set to your local endpoint.
     pushEndpoint: `your-local-endpoint`,
   },
 };

 await pubsub.topic(topicName).createSubscription(subscriptionName, options);
Qiqi Wu
  • 421
  • 2
  • 7
  • It works with local endpoints! thank you, I missed the example – Nicolò Gasparini Sep 03 '19 at 08:17
  • 1
    Has this actually been verified to work correctly? How do you host "your-local-endpoint" to work around the fact that functions-framework is apparently broken when it comes to hosting PubSub event handlers.https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/41 – Myk Willis Mar 02 '20 at 01:03
0

You should have an environment variable named "PUBSUB_EMULATOR_HOST" that points the the emulator host.

my local pubsub emulator have the following url - http://pubsub:8085 so i am adding the following env variable to the service that connects it:

export PUBSUB_EMULATOR_HOST=http://pubsub:8085

The following code should work:

const projectId="your-project-id";

 // Creates a client. It will recognize the env variable automatically
const pubsub = new PubSub({
  projectId
});

pubsub.topic(topicName).createSubscription(subscriptionName);
Adi
  • 1,263
  • 1
  • 13
  • 24