DEV Community

Discussion on: Data Streaming for Microservices using NATS Streaming - Part 2

Collapse
 
ldco2016 profile image
Daniel Cortes

In my opinion, as someone that has set up NATS Streaming Server, before we request the reader drop in a whole bunch of code, we should remind them and instruct them to test things out first, so before we drop in something like this:

subscription.on("message", async (msg: Message) => {
const parsedData = JSON.parse(msg.getData().toString("utf-8"));
console.log("EVENT RECEIVED WITH THE DATA BELOW :");
console.table(parsedData);

  const mongoClient = await MongoClient.connect(
    "mongodb://localhost:27017/statistic-service"
  );

  const db = mongoClient.db();
  const dunkCollection = db.collection("dunks");
  await dunkCollection.insertOne(parsedData);

  const dunkStatistic = await dunkCollection
    .aggregate([
      {
        $group: {
          _id: "$PLAYER_NAME",
          TOTAL_DUNK: { $count: {} },
          TOTAL_POINT: { $sum: "$DUNK_POINT" },
        },
      },
      { $sort: { TOTAL_POINT: -1 } },
    ])
    .toArray();

  console.log("\x1b[36m%s\x1b[0m", "DUNK CONTEST STATISTIC :");
  console.table(dunkStatistic);
  mongoClient.close();

  msg.ack();
});
Enter fullscreen mode Exit fullscreen mode

});

How about we first do something like this:

subscription.on('message', (msg) => {
console.log('Message received');
});

Right away, if we are working in TypeScript and we should be, TypeScript will consider msg argument as any and we don't want that, so we can solve that by adding Message from the node-nats-streaming library, which you do mention in your post, which is an interface that will describe the type of the msg argument, so like so:

subscription.on('message', (msg: Message) => {
console.log('Message received');
});

And then we want to encourage the reader to go inside the type definition file of that Message type to see what methods are available to the person wanting to learn from this blog post.

And no the npm documentation on node-nats-streaming is not going to educate the reader on the methods available to them on the type of Message.

For example, getSubject() returns the name of the channel that the message just came out of. But more relevant may be getSquence() and getData() which you use in your code you are asking others to just paste without explanation.

getSequence() is going to return the number of this event, in NATS all events starts out as number 1, 2, 3 and so on.

getData() returns the actual data included inside the Message or event.

You may also want to mention that with this here: msg.getData(), you are going to get back a Buffer and not a string and thats why you are doing JSON.parse(). I mean lets keep in mind the wide variety of skill level of developers that may be reading this article, from the most novice on up.