- [Narrator] We just posted feedback to the queue.
Now let's consume it in the feedback service.
So open the feedback service and in there
I first start with npn installing amqplib here as well.
Save.
And then head over to service chest,
because I will implement this consumer right away here.
And I start with bringing in amqplib.
Constant amqplib equals require.
Amqplib.
And done down there after feedback and log
was instantiated.
I will now add const q
equals feedback,
so that's similar.
But we did before, we of course have to post
to the same queue.
And now I will use this regular promise syntax,
because we're not in a async function,
I also want to show you how this would look like.
Using promises and not async await so I add
emqplib, then I connect as before.
I connect it to amqp
local host.
And then I get the connection back
and on this connection
I call create channel.
And then I get channel
back on this channel
I call assert queue q.
And then I put this next then directly here
into the same scope and there I will now add
channel dot consume,
q
and this will give us
a message in its callback.
And we see already that async-await really
simplifies things a lot, so this code is already
pretty convoluted.
In the body I say if message
is not now,
I will first do a log dot debug,
got message.
And we get the content of the message
msg dot content.
And we have to call to string, because
it's now a buffer again.
And, next I want to get this
queued message and parse
it into JSON so I add const q, m equals JSON parse,
message dot content to string.
Now all that is left to do is adding feedback dot add entry
And there a parse now in the name,
dot, title.
And the message from the parsed JSON.
And when this is done, I will now add then,
that handles that, so when this promise returns
I can safely do a channel dot
ack message which tells
rabbitmq that we successfully processed the message.
And at the very end I will also add a little catch,
block, catch.
Error log
dot fatal error.
So this should be it, let's start the application now.
Npm start.
And we see right away that we just got this message
and we processed it.
This means it was already in the queue and we now
processed it asynchronously.
Let's now look at the website, and I reload
the feedback page and we see that we
get this queued message one back.
Let's try a little bit more, so I add...
and let's say
message two.
Another test and let's save that.
And we see that it even instantly shows up now
on the feedback page, but this is not a must.
So it might happen that the message gets processed
and when this page reloads the message is not yet available
on the feedback service.
So in real life scenarios you have to handle
this asynchrony in some way, maybe by using web sockets
or simply by changing the message to the user,
that tells that the feedback will show after a short while.