Bazinga_
Bazinga_

Reputation: 105

How do I provide real time update in nodejs?

I am working on an e-commerce site. There are times where a product would no longer be available but the user would have added it to the cart or added to their saved items. How do I implement the feature such that if the product has been updated, the user would be notified as soon as possible?

I thought about doing a cron job that would check the status of the product if it still available or has been recently updated. But I do not know if that is feasible. I am open to better ideas

Thanks

Similar images are included below something similar to thisand this

Upvotes: 1

Views: 1613

Answers (2)

tmarwen
tmarwen

Reputation: 16364

What you are trying to achieve falls into real-time updates category and technically there would be more than one option to achieve this.

The chosen solution would depend on your application architecture and requirements. Meanwhile, I can suggest looking into Ably SDK for Node.js which can offer a good starter.

Here down a sample implementation where on the back-end you will be publishing messages upon item's stock reaching its limit:

// create client
var client = new Ably.Realtime('your-api-key');
// get appropriate channel
var channel = client.channels.get('product');
// publish a named (may be the product type in your case) message (you can set the quantity as the message payload
channel.publish('some-product-type', 0);

On the subscriber side, which would be your web client, you can subscribe to messages and update your UI accordingly:

// create client using same API key
var client = new Ably.Realtime('your-api-key');
// get product channel
var channel = client.channels.get('product');
// subscribe to messages and update your UI
channel.subscribe(function (message) {
  const productName = message.name;
  const updatedQuantity = message.data;
  // update your UI or perform whatever action
});

Upvotes: 3

Lek
Lek

Reputation: 137

Did a live betting app once and of course live updates are the most important part.

I suggest taking a look into websockets. The idea is pretty straight forward. On backend you emit an event let's say itemGotDisabled and on frontend you just connect to your websocket and listen to events.

You can create a custom component that will handle the logic related to webscoket events in order to have a cleaner and more organized code an you can do any type of logic you want to updated to component as easy as yourFEWebsocketInstance.onmessage = (event) => {}.

Of course it's not the only way and I am sure there are packages that implements this in an even more easy to understand and straight forward way.

Upvotes: 2

Related Questions