1

I am using the following code to do a Post request to Google PubSub API:

  pushMessages = async function()
    {
      //const collection = context.services.get(`mongodb-atlas`).db(`billing`).collection(`projectdata`);
      var needle = require('needle');
      
       
    var postData = {
        "message": "hello world"
    }
      
      
     needle
      .post('https://pubsub.googleapis.com/v1/projects/topicname:publish', postData, { json: true },  
      function(err, resp) {
      if (err)
        console.log('Error: ' + JSON.stringify(err.message));
      else
        console.log('OK.'+ JSON.stringify(resp.body));
      });
}
  

and I keep getting:

{"error":{"code":400,"message":"Invalid JSON payload received. Unknown name \"message\": Cannot find field.","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"description":"Invalid JSON payload received. Unknown name \"message\": Cannot find field."}]}]}}. 

Any hint on how to solve this issue?

Wytrzymały Wiktor
  • 11,492
  • 5
  • 29
  • 37
OuterSpace
  • 365
  • 7
  • 22

1 Answers1

0

You need a base64-encoded string to publish into google pub/sub as show on the documentation page. So, not just making the data into a json will work, you also need to encode it.

Please take as reference the node.js client libraries for cloud pub/sub.

const data = JSON.stringify({foo: 'bar'});
const dataBuffer = Buffer.from(data);
const messageId = await pubSubClient.topic(topicName).publish(dataBuffer);
...

Also you can check the API rest/v1/projects.topics/publish details on this link.

Betjens
  • 1,353
  • 2
  • 4
  • 13