googl云发布/订阅发布消息并确认订阅已收到

时间:2020-05-05 20:08:29

标签: node.js gcloud

尝试测试发布到一个主题是否通过了整个工作流程。工作流程为发布到主题A->云功能->发布到TopicB

使用ts,@ google-cloud / pubsub

运行以下代码时,它将立即通过,而没有任何错误或订阅消息验证。需要帮助修复此代码以使其起作用,因此仅在订阅消息与shouldBeMessage匹配时才通过,但当前无需等待订阅运行onMessage函数即可通过。

代码:

const filePath = path.join(__ dirname,“ file.json”); const file = JSON.parse(fs.readFileSync(filePath).toString());

// Publish to pub/sub topic
const topic = pubSubClient.topic(TopicA);
const publishMessageID = await topic.publish(Buffer.from(JSON.stringify(file)));
console.log(`Publish Message Id is : ${publishMessageID}`);

// Subscribe to the topic
await pubSubClient.subscription(TopicBSubscriptionName, function (err, subscription) {
  if(err){
    throw err;
  }
  function onError(err) {
    console.log(`Error is : ${err}`);
    throw err;
  }
  function onMessage(message) {
    console.log(`Received message ${message.id}:`);
    const parsedMessage = JSON.parse(message.data);
    console.log(`Parsed message.data : ${parsedMessage}`);
    console.log(`${shouldBeMessage.mappings}`)
    message.ack();
    return message;
  }
  subscription.on("error", onError);
  subscription.on("message", onMessage).then((value) =>{
    if(JSON.parse(value.data.mappings) === shouldBeMessage.mappings ){
      return console.log(`Mapping object successfully matched`);
    }
    else {throw "Mapping object didn't match";}
  });

  //Remove listers to stop pulling for messages
  setTimeout(() => {
    subscription.removeListener('message', onMessage);
    subscription.removeListener('error', onError);
  }, timeout * 1000);
});

0 个答案:

没有答案