I'm trying to use Google Cloud's Pub/Sub API to send messages to topic subscribers, but I'm having a problem where it's returning the message "If data is undefined, at least one attribute must be present.". I'm going to use it with Cloud Functions. I have the following code which is the same as the official Pub/Sub NodeJS documentation with minor changes:
exports.helloWorld = async (req, res) => {
const parse = require('url-parse');
const punycode = require('punycode');
const {PubSub} = require('@google-cloud/pubsub');
let message = req.query.message || req.body.message || 'Hello World!';
let referHeader = req.headers.referer;
let userIP = req.socket.remoteAddress;
let originHeader = req.headers.origin;
let userAgenteHeader = req.useragent;
let a = req.query.a;
let s = req.query.s;
let e = req.query.e;
try {
const pubSubClient = new PubSub({
project_id: 'my-project',
credentials: {
private_key: "my_private_key",
client_email: '[email protected]',
}
});
a = 123; //Change for test
let topicNameOrId = 'MY_TOPIC_ID';
const data = JSON.stringify({
"data": "analytics",
"attributes": {
"a": a
}
});
const dataBuffer = Buffer.from(data);
const messageId = await pubSubClient
.topic(topicNameOrId)
.publishMessage(dataBuffer);
res.status(200).send(`Message ${messageId} published.`);
} catch (error) {
console.error();
res.status(403).send(`${error.message}`);
process.exitCode = 1;
}
};
I've tried to do it with JSON.stringify, without it, directly in the function, but nothing worked, it always gives the same error and I'm passing the data parameter normally.
A bit late to this one, but I was scratching my head why this wasn't working. Since .publish has been deprecated, it isn't a viable solution anymore.
The documentation threw us this curveball:
const data = Buffer.from('Hello, world!');
const callback = (err, messageId) => {
if (err) {
// Error handling omitted.
}
};
topic.publishMessage({data}, callback);
Basically what {data} means here is {data: data}, therefore it's important to have the key named data
Changing the publishMessage line should fix it.
const messageId = await pubSubClient.topic(topicNameOrId).publishMessage({data: dataBuffer});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With