使用Apollo服务器中的PubSub将消息发送到第三方工具

发布于 2025-01-30 17:08:38 字数 623 浏览 3 评论 0原文

我还有另一项后端服务,该服务正在使用Nats PubSub订阅特定主题。我想通过在阿波罗服务器中发表特定解析器的消息来与该服务进行通信。推荐的方法是什么?

这是我用来发布消息的代码:

const { connect, StringCodec } = require("nats");

const host = `nats://localhost:4222`;

async function makeNats() {
  const nc = await connect({ servers: host });

  // create a codec
  const sc = StringCodec();

  nc.publish("hello", sc.encode("world"));
  nc.publish("hello", sc.encode("again"));
  await nc.drain();

}

makeNats();

我应该在解析器中调用它吗?我可以在index.js中启动NATS订阅并在上下文中通过它吗?在我需要发布时,我不希望该连接一直打开。

此外,如何订阅到单独服务的消息?我看到很多用于与前端客户端创建订阅的教程,但是有人可以演示如何与阿波罗服务器和另一个后端服务之间的pubsub通信吗?

I have another back-end service that is using NATS pubsub to subscribe to a particular subject. I want to communicate with that service by publishing a message from a particular resolver in apollo server. What is the recommended way to this?

This is the code that I am using to publish a message:

const { connect, StringCodec } = require("nats");

const host = `nats://localhost:4222`;

async function makeNats() {
  const nc = await connect({ servers: host });

  // create a codec
  const sc = StringCodec();

  nc.publish("hello", sc.encode("world"));
  nc.publish("hello", sc.encode("again"));
  await nc.drain();

}

makeNats();

Should I just call this in my resolver? Can I initiate the nats subscription in index.js and pass it in the context? I would not want the connection open all the time, just when I need to publish.

Additionally, how could I subscribe to messages to the separate service? I see lots of tutorials for creating a subscription with the front end client but can someone demonstrate how to communicate with pubsub between Apollo server and another back end service?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文