Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
If data is undefined, at least one attribute must be present pubsub

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_project@myemail.com',
            }
        });

        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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I tried your code and I was able to reproduce your error. After debugging your code, it was stuck when it uses publishMessage(). Apparently publishMessage() accepts a message object.

publishMessage(message: MessageOptions): Promise<[string]>;

Use publish() instead, it accepts buffer object.

publish(data: Buffer, attributes?: Attributes): Promise;

Apply publish() in your code, use the fix below:

const messageId = await pubSubClient.topic(topicNameOrId).publish(dataBuffer);

Cloud Function output:

enter image description here

Actual Pubsub message:

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda