Use pubsub in apollo server to send messages to third party tool

Viewed 79

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?

0 Answers
Related