Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda