Mini Microservices App | Microservices With Node JS And React

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] now that we've seen some notes on how we handle communication with micro services it's time to actually start writing some code so in this video we're going to take a look at a mock-up of the application we're going to build to better understand these asynchronous communication patterns before we look at the mock-up just a couple of quick notes first off the goal of this application is to really just get a taste of microservices architecture we're going to work on a much larger more comprehensive project later on inside the course this first project is really just meant to get your feet wet and help just kind of expose you to some of these critical issues we're also going to have a goal inside this project of building as much as possible from scratch so we're going to build out every last service by hand we're going to build out the event broker by hand we're going to build out as much as we can by hand just to get a really good idea of what is going on because of that because we're building this stuff from scratch i would not recommend using this project as a template for future micro services projects the reason for that is that usually we're going to use a lot of packages to implement a lot of this stuff as opposed to doing it by hand so on real projects you're going to want to use some packages as opposed to these kind of manual implementations that we're going to do again we're going to work on a very large project later on that's going to be a very serious professional grade project so you are going to see how to use those with other packages and whatnot okay so enough of that what are we going to build so we're going to make a very simple little application that's all about making posts kind of like blog posts or something similar and allowing users to comment on them so when user first comes to our application we're going to show a form like this where a user can create some kind of post we're going to say that our posts only have titles there's not going to be any kind of body or anything like that so a user might type inside of here my post and then hit submit once they do so we're then going to display the post they just created down here at the bottom of the screen that would be the post that was just created we'll show the title of the post we'll show the number of comments that was associated with it and we'll also have a little form right here to add some comments to that individual post so for example i might type inside of here i'm a comment and then click on submit and if i did so i should see this post counter right here or the comment counter incremented by one and i should also see the comment listed out right underneath the actual title and then of course we can add in as many posts as we want so we could go back up here to the top put in post number two hit submit and then we should see post number two down here up here and of course we should be able to add in comments like i'm a comment to that one as well hit submit and see that comment up here right there so in total this application is pretty straightforward but i think that you're going to be kind of surprised at the level of complexity that we're going to encounter even for this very simple and straightforward application all right so now we've got an idea of what we're going to build let's start to break this thing down and consider some of the different technical aspects of it so the first thing that we need to think about is what services we are going to create for this part of the course and for a little bit going on into the future right now we're going to say that for every different unique resource that we have inside of our application we're going to create a separate service so in our application i would say that we have two different types of resources we have posts which are these things we're creating down here the big blue boxes and then we have comments which are the things right here it's the bullet points that are tied to individual posts so in total we really have two different resources so we're going to think about creating two different services we're going to have a post service that is in charge of storing all the different posts we have and retrieving them giving them back to us and we'll have a comment service that is going to be in charge of handling comment creation and listing all the different comments out when we start to think about these different services the first thing we want to really do is really picture the different goals or responsibility of each service so like i just said with a post service we probably want the ability to create a post and to list all posts and for comments we'd probably want the ability to create a comment and list all comments now there's already some hidden complexity inside of here the post service is going to be pretty straightforward but if you really start to think about this and really drill down the comment service is going to probably be a little bit more challenging than you might think at first glance the reason for that is that the comment service whenever we create a comment we're going to really be tying a comment to a post so there's going to kind of be a dependency of sort between creating a comment and having some knowledge of what posts exist so we're going to have to apply one of those asynchronous or synchronous communication patterns we just discussed to make sure that users can only create comments that are tied to a very specific post in addition whenever we try to list out some comments we probably don't want to just get all the comments that exist in the universe instead we probably want to somehow retrieve just comments that are associated with some very particular post so in other words if we retrieve the top 10 most popular posts inside of our application for example we probably only want to get comments tied to those specific top 10 posts so even though i say right here list all comments well once again there's probably going to be some kind of dependency inside of here where the comments that we're retrieving need to somehow be tied to the actual post that we're retrieving as well if none of that makes sense right now that's totally fine all i mean to say is that this application is going to be a little bit deceptively challenging even though it looks like it's really simple and straightforward in nature okay so now we've got an idea of what we're going to build and it's clear that we're going to run into some challenges along the way click pause right here and we'll start to write some code in the next video all right after a whole bunch of lecturing it is finally time to actually write some code and whatnot so in this video let's do a quick overview of some of the setup that we're going to go through rather quickly all right so here's the general architecture of what we're going to initially try to build what's running inside of our browser is going to be a react application this react application is going to communicate via network requests to a post service and a comments service both the post service and the comment service are going to be express based applications we're not going to worry about any databases or anything like that instead we're going to store all of our data in memory for this very first project again this first project is just about giving you an idea of how this stuff works together as opposed to really focusing on the nitty gritty details of implementation so let me tell you about the setup we're going to do in this video we're going to first generate a new project using create react app that's going to handle our react application we're then going to scaffold out or put together a little bit of code for an express based project for the post service and the same thing for the comments service as well so in total we're going to go through three things setting up each of these is going to take a little bit of time so we might start by generating the react application and then while that's initializing and installing itself we'll probably go over and quickly set up the post and comment service as well so i'm going to get started by going over to my terminal i'm inside of a workspace directory of sorts this can be anywhere on your computer and inside of here i'm going to make a new folder called blog so that's going to be where i'm going to generate my entire set of different projects or services that's going to create the totality of our project inside of this blog directory i'm then going to generate a new react application using npx create react app and i'm going to call this simply client to say hey this is our web client that's going to take a couple of minutes to install while that's running i'm going to open up a second terminal window and i'm once again inside my blog project directory so now inside of here i'm going to create a folder for first my post service so i'll say make dur create new folder called posts i'm going to change into that directory and then inside of here i'm going to generate a new package.json file and then install a couple of dependencies into it i'm going to do an npm init dash y that's going to generate my package.json file i'll then do an npm install and we're going to get four different packages we're going to get express we're going to get another package called cores i'll tell you why we are going to use that in just a moment something called axios again i'll tell you why we're using that on the server in just a moment and then finally to actually run our project all the code inside of it we're going to use nodemon as well okay so that's my post project now we're going to repeat that same process for comments as well i'm going to create a third terminal window i'm going to change back out to my workspace directory then once again inside of blog and there's my client and post folders inside of here i'm going to make a third project called comments i'll change into comments i'll do an npm init-y once again and then we're going to install the same four dependencies that we just installed into the post project so i'll do an npm install we'll get axios ors express and nodemon alright there we go now after just a moment comments will be all set up yep there we go i'm going to go back over to my second terminal window which is where i installed posts so it looks like the four dependencies for the post project were installed successfully as well and then finally if i go back to the first project window or the first terminal window i should see the create react app all finished installing on the first journal window i'm gonna make sure that i change into that client directory okay so now in total i've got three terminal windows one for client i've got one for our post service and one for our comments service as well i can tell you right away that one of the most confusing things inside this course is going to be the number of terminal windows that we're running at any given time and i can really apologize in advance because well i'm going to be changing between these terminal windows quite a bit hopefully at some point in time i'll figure out a better way to present these things to you well you'll probably see the next video i'll probably tile these windows so you can see all of them at the same time very easily but i just want you to be aware that we're going to be working between multiple terminal windows quite a bit and so it's really important for you to just be aware of what window we are in at any given time okay so that's it for our initial project setup so quick pause right here going to start writing some code in just a minute we've now done some initial setup and now it's time to actually start writing out our services for this initial implementation we're not going to worry too much about anything microservicy or anything like that we're really just going to put together some very basic functionality for the posts and comment service so in other words some very basic express js code to manipulate or deal with some very basic resources we're going to first begin with our post service whenever you start designing a service or putting it together it really is worth the time to think very critically about exactly what you want your service to do so in our case we know that we want to create a post and list all posts but let's get a little bit deeper technical detail here and really truly understand what this thing needs to do so here's my thought for the post service i think that we need to have a single route that's going to be in charge of retrieving all the different posts that have ever been created i think we also need one distinct route that is going to be in charge of creating a brand new post so we're going to have one route of posts if we make a get request to it we'll get all of our posts we'll have another one of slash posts if we make a post to it with somebody that has a title that is a string we're going to create a new post so that's what we're going to use as our guide for implementing our post service so let's open up our code editor inside the posts project directory right now we're going to start to build out a very small express application that's going to implement these two routes so back at my terminal you'll notice i've redone my layout here just so you can see these different terminal windows a little bit more easily i'm going to find my post terminal window and open up my code editor inside there and then once inside there i'm going to do a initial file i'm going to make right away of index dot js so we're going to write out just about all the code for application inside this one single file at the very top we're going to get access to express we're going to create a new express application we're going to set up those two different route handlers that we just discussed it's all going to be some pretty straightforward express related stuff okay so let's get to it a little bit of typing here so first off we will require in express i'll create a new app and then i'm going to associate those two different routes with the app we just created so we'll do an app get to slash posts and i'll put in my route handler and then if we ever make a post request to slash posts and we'll put in rec and res as well then at the bottom right away i'm going to make sure that my express application listens on a very specific port so i'm going to put in here app.listen we're going to have this first service listen on port 4000 and then inside that callback i'll say console.log listening on 4000. all right simple enough okay so now let's start to implement these two different route handlers i mentioned in passing just a moment ago in previous video that we're not going to worry about any database or anything like that with these different services so we're going to store all these different resources in memory the downside to this approach is that any time that we restart a service we're going to lose all of our data but that's totally okay for this initial little toy project that we're putting together right after i create my express application i'm going to make a little object that's going to be in charge of storing all the different posts that get created they'll say const posts is an empty object like so this object is where we're going to store every post that we create now that we've got this kind of repository for all the different posts we're going to store we can start to implement the first route handle right here that's going to retrieve all the different posts that have been created very easily you can just say inside that route handler let's send all of our posts but now if anyone makes a git request to slash posts we're going to send back all the posts that have been created the next thing we have to do is make sure that we implement the ability to create a new post so we have to add in some implementation for the post request handler to slash posts remember that we probably want to eventually have some id associated with every post that gets created right now we don't really have any ability to create a id of any sort so let's add in a little bit of code to randomly generate an id whenever someone makes a post request to slash post right here with the intent to create a post we're going to randomly generate an id assign it to the object that the user just sent to us and then store that entire thing that's a little bit confusing for me to say so let me just show you exactly what we're going to do at the very top of the file i'm going to add in an additional require statement i'm going to require in random bytes from the crypto package we're going to use random bytes right here to generate a new id that we're going to assign to the post that the user is trying to create so down inside the post request handler i'm going to say const id and we're going to generate our random id right here and we'll do that by using the random bytes function we'll say random bytes i want four bytes of random data so this is just to get a random string for us that's all we're doing here we'll say two string x so that's going to give us a nice random looking id it'll look something like that it'll be actually hexadecimal so we won't have like k's in there and h's and whatnot but you get the idea that's pretty much what we're going to have for our id so now the next thing we're going to do is take a look at the request that we just received from the user remember we're making the assumption here that whenever a user makes a post request to this route they're going to send along a body that has a title property inside of it so we're going to pull out that title we're going to generate that or take that randomly generated id and then store them all together inside of our posts object up here that we just created so let's get access to the title that the user just sent to us we'll say rec.body we'll then add in a new key at the id that we just generated on our posts object and i'll assign to that the id and the title and then finally down here at the bottom after we add in that brand new post let's send back a response to the user to let them know that hey we have now created a new post for you it's all good to go i'll do a res i'm going to set a manual status here of 201 which indicates we just created a resource and then i'll send back posts at id which again is the post that we just created all right so this is looking pretty good there's one last little thing we have to do we need to make sure that we add in a body parser to make sure that whenever user sends us some json data and the body of a request actually gets parsed and so it actually shows up appropriately inside of a request handler so just a little bit of administration work with express.js at the very top of the file i'm going to add in a require statement for body parser and then right after we generate our app we'll do an app.use bodyparser.json like so okay and that should be it so the code that we have here should be good to go it implements both of these different features or these routes that we just discussed the last thing we should do is add in a script to our package.json file to start this project up we can then take a quick break and then do some testing this thing in the next video so inside my package.json file i'm going to find the script section i'm going to remove the default script inside there and i'll replace it with a start script that will run nodemon like so i'll then save that and then finally i'm going to go back over to my terminal i'll find my posts terminal window and i'll do an npm start inside there and i should see something that says listening on 4000 very good okay so now that we've got this thing up and running our first little service quick pause right here and we'll do a quick test of this thing in the next video just to make sure that it's working as expected we've now finished up our first post service it's time to now test this thing out now later on inside the course we're going to eventually start to write some automated tests to make sure that all of our services work as expected this is a really important aspect of micro services and we're going to go into great detail on it over time but for this very first service we're going to test it out manually to test out our service manually we're going to use a very simple api client so i'm going to go to postman.com and find the postman api client tester now this is a very small desktop application that you can use to make arbitrary api requests to any given endpoint we're going to use postman to test out this personal service or two that we put together just to save ourselves a little bit of time if you do not want to download and install postman that's totally okay this step is really optional i just want to make sure that our services are working as expected so go ahead and download the application if you have not already once you download the app you can open it up and you'll see a window like this right here inside of this window we're going to open up a new tab on the top left hand side and we'll customize a request that we're going to issue to our post api i'm going to first get started by attempting to create a new post so i'll change the method of the request that we're going to make to post and i'll make a request to localhost colon 4000 slash posts i'll then go to the headers tab i'm going to specify a header here with a key of content dash type i'll give that a value of application json and then of course we need to add in a body to the request and specify the title of the post that we're trying to make i'll go over to the body tab i'm going to select raw and i'll make sure that over here on the right hand side this drop down is set to json we're then going to write out a little bit of json data to send to our api i'll put down a set of curly braces i'm going to put in a key inside of double quotes because this is json that we're writing right here not javascript code i'll give it a title of first post like so once i've got that all put together i'll then send the request off and then down here at the bottom i should see a status in the response of 201 created and i should see the id and title of the post that we just made okay so that looks pretty good so now let's do another quick test we're going to make sure that we can retrieve all the posts that have been created so i'm going to make a new tab inside of postman i'll make sure that i'm going to make a get request i'll enter in a request url of localhost 4000 posts i'll go to headers i'll put in content type of application json and then in this case because we're making a get request no body required let's go ahead and send right away and there we go so we can now see our post coming back to us in the form of one big giant object let's say this thing looks like it's working correctly now as a quick reminder if we make any change to our code inside of our project that's going to restart our server and because we are storing all of our post and memory all of our posts will be automatically dumped so if i go back over to my editor right now and i just add in say some comment right here and save the file i've now restarted my server automatically because we're making you some nodemon so if i go back over to postman and make another get request i will no longer have any posts so just something to be aware of at some point in time if you make any change you're going to start to dump a lot of data okay so i'd say that our post service is working correctly now we're not going to do a lot of testing like this throughout the course manual testing is what i mean we are going to do a lot of testing automated testing so we're going to now take a break we're going to come back next video we're going to start to put together our comment service and i'm probably going to leave it to you to do a test with postman really quickly to make sure that our comment service works as expected as well we finished up our post service so now we're going to put together an initial implementation of our comments service as well just as we did before it's going to very much be worth our time to really hash out exactly what we want our comment service to do so i took a quick stab at how we might want to implement this comment service i think that we're going to have two different route handlers once again we're going to have one route handler that's going to allow us to create a new comment that is associated with some very particular post so you'll notice that inside the path right here we're going to make a request to post slash and then the id of the post that we're going to associate this comment with when we make a post request we're going to have a body that has a content that is some string so content is going to be the actual text of the comment itself we're then going to have a second route handler that's going to give us all of the different comments that are associated with some very particular post id so we'll make a get request to that route that will give us all the comments associated with some given post id so pretty straightforward but we are going to have just a little bit more complexity on this service i'll tell you why in just a moment right now let's open up our code editor and start to put this thing together so i'm going to flip back over to my terminal i'm going to open up my code editor inside of my comments directory inside of here right away i'll make an index.js file and at the very top we'll write out a little bit of boilerplate very similar to what we ended up with inside of our post service just a moment ago so i'll get express i'll get a body parser and i'll get that random bytes function that we're using to just generate random ids next up i'm going to create my express application i'll associate the body parser middleware with it and i'll put together our two route handlers so we want to have a route handler that will deal with a get request to posts id comments and of course make sure that you've got that colon right before id right there and we could do something very similar to handle post requests as well so we're going to look for a post request to post pull in id comments very good and then finally let's make sure that our express application listens on some port so we'll say app.listen and remember we already have another service listing on port 4000 on our computer so we have to put in another unique port right here in my case i'm going to put in 4001 like so and then once i start listening on there i'll do a console log of listening on 4001. okay so good start so now the next thing we need to do is add in some actual implementation or getting all the posts with some given id and all the seeming all the comments associated with some post id and creating a new comment as well let's first begin with creating a new comment just as we had back on our post micro service we're going to store all of our comments inside of an in-memory data structure so just like we had previously i'm going to create a new object right here called comments by host id and i'll make that an object so you'll notice i'm calling this thing by post id the reason for that is that we really want this data structure to be optimized for looking up all of the different comments associated with a given post so we're gonna have a slightly more complicated data structure right here than what we had back on our post service let me show you a diagram to help you understand what this object is going to really look like all right so here's the idea here's what we're going to do that comments by post id is going to look like this diagram right here it's going to have some keys of course because it is an object and those keys are going to be the ids of a post that has been created inside of our application then for each of those keys we're going to have an array of comments so here's comment number one comment number two and so on so this is going to make it really really easy and straightforward to look up all the comments associated with some given post by the post's id all we have to do is reach into the comments by post id object look up the given id of the post and that will give us back an array of all the comments that are associated with that post pretty straightforward to do that lookup okay so now we have a better idea of what this object right here is going to look like let's start making use of it inside of our post request handler so inside of here the first thing i'm going to do is generate a new comment id so this is going to be just a random id so we can identify this comment at some point in the future if we need to so i'll say comment id is going to be that random bytes function we're going to call it and get a or random bytes generated and then convert that to a string that is a hexadecimal string so again just a randomly generated id next up we'll pull out the content property that is provided by the user inside of our incoming request because remember we had said that anytime someone makes a post request we're going to have a body that is a content that is some string so i'll get content from rec.body now next up we're going to take a look at our comments by id by post id object right here we're going to check to see if we've already got some array inside there for the given post id so let's say const comments is going to be comments by post id and it will look up the post id that was provided inside the url we'll do rec rams.id and that will give us either an array or undefined it will give us undefined if we've never had a comment us created that is associated with this post before this might be undefined right here so to guard against that i'll say if this results in undefined then just give me by default an empty array so now we're going to push in the new comment that we're trying to create into this comments array we'll say comments dot push and i want to push in an id of comment id and the content that the user just provided and i'll make sure that i assign this comments array back to the given post inside of our comments by post id object so we'll say comments by host id at rec brands id equals comments and that should be it now the last thing that we can do right here we'll send back just the entire array of comments we could send back just the comment that was created but what the heck let's just send back the entire array of comments i'll do a res dot status 201 and i'll send back the entire array of comments okay so there's our post request handler now we'll put together our get request handler which is going to be way easier so up here we'll do a res.send we're going to look inside of our comments by post id object i'm going to look up inside there the id that was provided inside the path so we'll do a rec params id and then once again if that results in undefined let's guard against that and i'll just put in an or empty array like so so that no matter what we always send back an array to whoever is making this request okay so that looks good so i'm going to save this file the last thing i'm going to do is open up my package.json file we're going to define a script inside of there as well for starting up our project with nodemon so here's my package.json file i'm going to replace the start script or create a start script i should say and we'll do a nodemon index.js well that should be it for our comment service so once again let's take a quick pause right here we'll come back to the next video and just do a very quick little manual test with postman post or assuming host man not nodemon postman to make sure that this is all working as expected our comment service is all complete so let's very quickly do a quick test using postman i'm going to flip back over to my terminal to get started i'm going to find my terminal window that is inside that comments project directory and i'll run npm start inside there now i want you to recall that we now have two separate services two separate express applications running on our machine one is listing on port 4000 the other is listing on port 4001 so if we want to communicate with our common service we need to make a request to localhost 4001. all right so now that that is running let's flip over to postman i'm going to open up a new request tab right here i'm going to make a post request because i want to try to create a comment just to get started so i'm going to put in my localhost 4001 again 4001 because we want to reach out to our comments service and we'll make a request to slash posts the idea of a post so we want to add a comment to now our comment service right now doesn't really have any idea of what valid host ids are so we can put in any post id right here that we want to any string whatsoever so i'm going to put in just one two three that's going to be the id of the post that we're going to imagine actually exists and then slash comments next up i'll go to headers i'm going to put in a content type of application json i'll then go to body i'll select raw i'm going to make sure the drop down is set to json and we'll enter in some json right here remember a comment must have a content property so i'll give my comment some content of something like i am a comment i'll go ahead and send this thing off and there we go i've got a 201 created and you'll notice inside of our response we've got an array of comments that are associated presumably with post that has id123 okay so that looks good so now let's make sure that we can retrieve all of our comments with some given post as well i'm going to open up another request tab i'm going to make a get request to localhost and one posts and i wanna get all the comments that are associated with post one two three slash comments then once again on the headers tab content type of application json we don't need a body because we are making a get request so i'll go ahead and send i get a 200 okay and there is my array of comments right there just to make sure this is all working correctly let's try to add in just one more comment make sure that we don't overwrite any comment or anything like that so i'm going to go back over to my post request tab right here i'll change the content to second comment i'll send it off i can now see inside the response that i've got two comments here one that says i'm a comment the other says second comment and if i go to my get request tab i can make the get request again and yeah there we go very good all right so that is it for the very basic very simple express js stuff that's all we're going to really write as far as like simple express stuff goes so we're now going to take a pause we're going to come back the next video and start working on that react application and once we finish that thing up very quickly we're then going to start to see some really big issues start to crop up with our current design there's some really kind of hidden nasty stuff inside of here maybe it's not the worst stuff in the world but it's definitely not very efficient so we're going to start to put that react application together we're going to start to see some problems with our implementation and then we're going to start to figure out how we can solve these things with a micro services style approach so quick pause see you in just a minute we've now got our two services put together so now it's time to start working on our react application before we start working on the react app just a quick note if you don't know react or if you don't want to work with it at all that is not a problem just skip the videos we're about to go through that focus on this react application and you can download all the completed react code in just a couple videos now at some point in time this application i will ask you to make a couple changes to this react project but in general it'll be a small set of changes so it shouldn't be too bad okay so with that in mind let's get started the first thing we're going to do is come up with a general component design for our react application so on the left-hand side i've got a mock-up of our app on the right-hand side i've got a component hierarchy that i think we should try to implement so at the very top is going to be our classic app component we're then going to have a post create component the post create component as you'd guess is going to show that form right there we'll then also have a post list component the post list component is going to render everything on the bottom half of the page so post list is going to be in chart of showing the actual posts themselves and for every post we'll also show a comment list and a comment create component comment list is going to be in charge of rendering out a list of comments that have already been associated with the post so right now in this mockup there's only one comment listed but we could easily have 5 10 20. however many comments listed right there and then comment create as you would guess is going to be this form down here at the very bottom and so comment create will be in charge of creating an actual comment and associating it with a given post all right so that's our component design so let's now flip on over to our terminal we're going to start up our code editor inside of our react project directory we're going to start up our react application and start doing a little bit of initial setup all right so i'll flip back over to my terminal here's my client project directory so that's where my react project is i'm going to open up my code editor inside there and then i'll flip back over to my terminal we're going to do a very quick npm install here we're going to get the axios module just so we can make requests over to our express api in a little bit so i'll do a quick npm install and then after that is complete i'll make sure i do an npm start to start my project up and come on come on there we go so npm start all right so that's going to start up our react application hopefully on port 3000 yup there it is right there all right so i'm not going to open up my editor inside of our react project so make sure you're inside of your client directory inside of your editor i'm then going to open up my src directory and i'm going to delete everything inside there the reason for that is that every now and then the react boilerplate changes just a little bit there's a ton of pre-generated code inside there that we really don't need so it's a lot easier to just start off from scratch then inside my src folder i'll make an index.js file i'll also make a app.js file so our app.js file as you'd guess is going to be our app component we're going to create the component inside of here we're then going to import it into the index.js file and then render it into some actual dom element let's first start inside of app.js at the very top i will import react from react i'll then do an export default and for right now i'll just return a div that says host app or how about blog app doesn't really make a difference i'll then save this file i'm going to change back over to the index.js file that we just created i'm going to import react from react and react dom from react dash dom i'll then get my app component and then finally we'll do a react dom dot render i'm going to try to show an instance of my app component i want to render it into my index.html file if i go into my public directory find that file just as a quick reminder we are given this div right here with an id of root which is traditionally where we're going to render our root component to so as a second argument to react on.render we'll pass in a reference to that root element like so okay so let's save this i'm then going to go back over to my browser it's going to refresh the page looks like the entire process crashed because we deleted that index.js file no problem i'll go back to my terminal and restart the development server so once that is restarted there we go blog app all right so humble beginnings we still have a lot of components to put together so quick pause start working on that entire component hierarchy in just a moment let's continue working on some of these different components next we're going to work on is our post create component so again that's in charge of the content at the very top all we have to do is show a very simple form whenever user submits the form we're going to take that title and use it as the title for a new blog post i'm going to flip back to my editor inside of my src directory i'll make a new file called host create.js inside of here right away we'll import react from react and i'll create and export a functional component inside of here i'm going to return a div inside of that div we're going to add in a pretty good amount of markup so a little bit of typing here a couple different elements we need to add in first off i'm going to put in a form inside the form i'm going to put in a div with the class name of form dash group the reason for that class name is just a little bit of styling that we're going to add in to make sure that this application is not hideous to look at inside of that div we'll do a label that says title i'll put in an input with the class name of form dash control and then after the div so make sure you've got the closing div right there right after it i'll put in a button with the class name of btn btn primary let me close my sidebar here and i'll give the button some text like submit okay let's save this and then make sure that we can display it inside of our app.js file or the app component so i'll change back over to the app component that we created just a moment ago at the very top i'll import close to create from post create and then inside the div i'm going to remove that text right there i'm going to give this thing a little header i'll put in h1 that says create post just like we saw inside of our mock-up and it'll show the post create component all right gonna save this flip back over and i should get something like this right here well like i said this doesn't look too great it would be nice to have just a tiny bit of styling here you'll notice we added in a couple of different class names so we're going to make use of bootstrap just to make this thing look a little bit better let's very quickly hook up bootstrap to our application just the css side of it so that our application is not totally hideous to add in bootstrap to our project i'll open up a new browser tab and navigate to gitbootstrap.com once here i'll find the download link and then we're not going to actually download bootstrap we're going to instead just link to the cdn so if we scroll down a little bit we'll see bootstrap cdn i'll copy the link and script tags you see right here i'll then flip back over to my editor inside my public directory i'll find the index.html file and then anywhere inside of the head element we're going to paste in those two tags that we just copied you'll notice that one of the tags we just copied was a script tag that has all the javascript code associated with the bootstrap project we don't actually want any of that javascript code we just want the styling from bootstrap so i'm going to delete the script tag that was just copied in i'm going to delete that script tag entirely and i'm just left with the link for bootstrapcdn.com we should be able to save this file i'll once again confirm that i've got just that link tag for bootstrap added in i'm going to close this file i'll then go back over to my browser and just confirm that yep everything looks good much better than what we had before the last quick change i'm going to make here i'm going to wrap that div inside of our app component i'm going to give that div a class name of container which is just going to constrain the edges here on the left and right hand sides so if i flip back over find my app component here's that div i was talking about i'll give it a class name of container save that flip back over and there we go we've now got a little bit better kind of gutter on the left and right hand sides okay well this looks pretty reasonable but let's keep going on our post create component so we've got that component put together but it doesn't have any functionality tied to it just yet let's open up the post create component once again we're going to add in an event handler to watch for anytime a user types into that input and then eventually anytime a user clicks on that submit button and tries to actually submit the form when that occurs we're going to make a post request over to not our comment service but our post service so we're gonna make a post request over to the post endpoint at our post service and attempt to create a new blog post with a given title so let's do that right away inside of my post create component here's post create right here at the very top i'm going to add in some imports first i'm going to get the use state hook from react i'll get axios from axios to make our actual request then inside the component itself i'm going to declare a new piece of state using the use state hook so we'll say const title and set title is use state we'll initialize that to be an empty string and we'll make sure that we use that title property and the setter along with our input element right here to make sure that we've just got that reference to the title of the blog post we're trying to create so i'm going to assign this thing's value to come from title and i'll add on an onchange event handler as well make sure that we say anytime an event occurs which i'll abbreviate simply as e we will want to call set title with e target dot value and i'll save this so you can see that whole line so this is just a little bit of classic two-way property bonding right here now that we got that put together we are tracking the value of that input inside this title variable so now we can add on an event listener to the form itself and watch for a submission event and of course anytime that occurs we'll make that actual post request over to that api so on the form element i'll add in on submit anytime that submit you occurs we'll run a little function that we're going to define inside of here called nothing too fancy we're just going to call it on submit so let's define a on submit function like so and so once again this function is going to execute any time user submits that form we'll make sure that we prevent the default action that occurs whenever user submits a form in a browser by default the browser is going to try to submit that form itself that's not what we want so we'll receive that event object and call prevent default on it then inside of here right after that that's where we can start to make our request to our posts microservice we probably want to use the async 08 syntax inside this function rather than dealing with promises or callbacks or anything like that so i'm going to mark this function as being async and then inside of here we can make our actual request so i will do await axios.post we're going to make a post request to our post service and remember our post service if we go back over to our terminal very quickly this middle terminal window right here is where i'm running my post service remember it is running on port 4000 so we need to make sure that we make a request to report 4 000 in particular so we're going to make a request to http colon slash localhost colon 4000 slash os and that is the second argument we'll put in the body of our request so we want to send along a title and the reason for that remember we designed our whole api to receive a body that has a title that is some kind of string okay so this looks pretty good now the last thing we probably want to do here after we create a post this is just a very small little ux sort of thing after we create a post we probably want to blank out the title or reset the title back to an empty string and the reason for that is to just make sure that if we after we click submit right there if it is successful i just want to empty out that input which is essentially going to be a sign that hey the request was just issued successfully so i'm going to put inside of here a set title of empty string all right so that should be it let's save this i'm going to flip back over before i attempt to test this thing out i'm going to open up my development console inside my browser because i can tell you right now we are going to get an error when we run this code from a very very small thing that we're going to fix up in just a moment so i'm just going to make sure i've got my console open go to my network tab i'll put in some random title hit submit and there we go we got a little air right here so this is an error that not super relevant to micro services but it's probably going to come up just about like every time you work on micro services depending on how everything ends up getting set up so i just want you to see this error really quickly just to have this in our mind this is a very classic web development era that you run into all the darn time it's a course request error so let's take a pause right here we'll come back next video do a quick review on what a course request error is and then fix up this error and make sure that we can actually create a post inside of our app in the last video we attempted to create a new post but we very quickly ran into a course request error just as a quick reminder on course requests course requests are an issue anytime that we are looking at some domain or domain with a port or domain with a subdomain that is different than the url or the domain that we're trying to make your request to so in our case in the browser we are at localhost port 3000 and we are trying to make a post request to localhost port 4000 those ports are different and so the course request policy comes into effect the browser is going to automatically reject or prevent any requests from being issued from localhost 3000 over to 4000 unless localos 4000 our server right here provides a very specific set of headers so in order to get this error right here to go away there's nothing we could do inside of our browser there's no additional configuration we could add to our react app or anything like that to make this error go away we have to do some additional configuration on our server itself let's do that right now to get started i'm going to flip back over to my terminal we're going to do this additional configuration on both our post service and the comments service it's going to be a very small little piece of configuration so i'm going to find my internal windows running my post service i'm going to stop that server and my comment server as well and then in both of these terminal windows so for both posts and for comments i'm going to run npm install course so there's one and there's two very small package all it's going to do is help us get around this course error by setting a header on very specific responses that are going to go back to the browser so after that i'll start up my post service and i will start back up my comment service very good and i'm going to open up my editor in both these directories and we're going to make use of that course module that we just installed so i'll first start off with my post service here we go so inside of my posts folder i'm in the index.js file inside there at the very top i'm going to require in course and i'm going to wire that up to my express application as a middleware so i'll do app.use scores like so and make sure you call coors as though it worry function i'll save that and i'm going to do the same thing inside of my comments project as well so i'll swap back over to my comments project here's my comments project again inside of comments at the very top i'm going to require in course and again wired up to my app as a middleware and once again i'm going to make sure that i call the course because it is a function okay save this and we should be good to go now let's flip back over to our browser and we're going to try to create a post once again just for fun i'm going to refresh the page to get those nasty errors to go away i'll then enter in a title here so i'll say first post submit it and there we go so my request was issued i got a response of 201 which means that my post was successfully created well this is definitely good progress forward and we got that little course air to go away we're going to make sure that if we start to add in any other services to our project we just add in that course module from the get go as we start to work on our later project so that big project that we're going to work on later on inside the course we're not going to have to worry about this course issue quite so much because there's a couple of little architectural changes we're going to add in here so that we will not end up making requests from one url inside the browser to some different url where our actual api is hosted we're going to make a couple changes so that they're actually kind of co-located so to speak all right so quick pause right here come back the next video now that we've got that post creation put together we're going to start working on our posts list component and then eventually make sure that we can add on the ability to list out comments and create comments as well so i'll see you in just a moment in this video we're going to start to work on our post list comment list and comment create components right now we're kind of deep in the world of react and it sure seems like we're not messing around with micro services too much don't worry we just have to put these three components together very quickly and as i've mentioned several times now we're gonna start to see there's some really big issues with our current micro services architecture so we're gonna get back to the world of micro services very very quickly in the meantime let's just finish up these components really quickly to get started i'm gonna go back over to my code editor for my react project here it is right here inside my src directory i'm going to make a new file called post list dot js inside of here i'll import react right away i'll do an export default inside of here for right now i'm just going to return an empty div and i'll make sure that i show this component inside of my app component so i'll go back over to my app.js file at the top i will import post list from post list then right underneath my post create i'm going to add in an hr so that's a horizontal rule just to draw a line across the screen to make sure that it's clear to users that they're looking at a different section i'll put in an h1 right underneath it and just put in their posts and i'll show the post list component okay so simple enough let's go back over to our post list component so let's think about what this component really needs to do it needs to make a request over to our post service and get a list of all the posts that have ever been created we're then going to iterate over that list of posts and create some div or something similar to just show the title of each post inside of one of these little card looking things so let's first add in some code to make a request to our post service to get the list of posts that have been created to do so at the very top we're going to get that use state hook from react again because we do have to store our list of posts somewhere i will also import axios from axios so we can actually make the request itself oh one other quick thing we need here we need to use effect as well to make sure that we only try to fetch our list of posts one time when our component is first created okay so let's write out some code to actually make this request we'll first get a piece of state here so we'll declare a new piece of state called posts and we do have to provide a initial starting value for this thing now you might be tempted inside of here to put like an array because hey we're getting some list of posts but i want you to think back to the post service we really put together let's go back over to the post code editor really quickly so i'm going to tab back over to my post service i'm inside of my posts project right now i'm inside the index.js file inside there and as a quick reminder we stored all of our posts inside of an object and we're sending back that entire object whenever someone tries to get a list of all of our posts so when we think about providing a default value for that use state call we don't really want to put an array inside there we want to put an object instead to kind of represent what our final state is going to actually look like so back inside of my post list component rather than putting in an array as our default value right there i'll put in an object again just to represent how we're going to actually get this data back from our api after that i'm going to define a function that's going to make the actual request off to our host service so i'm going to define a function called fetch posts this is going to be an async function because we probably want to use that async await syntax inside of here we'll get some response from calling await axios.git and then remember to get our list of posts we need to make a get request to localhost 4000 that's where our post service is and the actual endpoint that we want to reach out to is the post endpoint or the post route so we will put inside up here http colon slash localhost 4000 slash posts as a quick reminder anytime we make a request with axios we get back your response object our actual data is nested inside there on the data property so we're going to take that response or more specifically the data from it and use it to update our posts piece of state we'll say set posts will be res dot data well we've now got this function put together so now the next we need to do is decide when to call it that's why we got this use effect hook as a reminder use effect can be used to run some code at very specific points in time in the life cycle of a component in our case we probably want to run fetch both only when our component is first displayed on the screen so to make sure that we can run this function only when this component is first displayed we will call use effect we will put in a empty function right now as the first argument and then critically as the second argument we're going to put in an empty array that empty array right there is what's going to tell react to only run this function one time and then inside that function we can actually call batchpose very good just as a quick test right after that use effect let's put in the console log and we'll try to console log out our posts piece of state okay gonna save this you know flip back over and inside of my console right here which i already have open i can see that i've got one console log that's the default value of posts that we initialized inside of our component and then right after that i've got an object that has a key of a01 blah blah so that's the randomly generated id that we generated when we first created a post and as a value is the actual post itself cool so this looks good now all we have to do is iterate over the values of this object and for every value on there we're going to display a little post something on the screen let's do that right now i'm going to go ahead and delete the console log we just put together and then after that i'm going to do a rendered pose and that's going to be the result of calling object dot values on posts so object.values is a built-in function javascript that's going to give us back an array of all the values inside of this object right here so it's going to essentially be an array of actual post objects we will then map over that array and for every post inside there we're going to generate some jsx and return it from this mapping function so i'm going to return and we're going to put a little bit of markup right here i'll give myself a div on the div itself we're going to add in a class name of card i'm going to add it in a hard-coded style property just to make these cards look kind of nice i'm going to give this thing a width of 30 percent and a margin bottom of 20 x let me save this so you can see that entire line and then because we are generating a list of elements here react is going to expect us to place a key property on each of the elements we are creating or i should say the top level elements so to have an actual unique key i'll use the id out of our post object because remember every post has an id i'll say key is going to be post dot id like so all right next up inside this div i'm going to give it a another div with the class name of card dash body i'll give it an h3 and inside of that h3 i'll display the actual post title so post dot title making sure that i've got those curly braces because we're referring to a javascript variable right here okay so let's say this looks pretty good we are now generating a list of all the different post titles now the last thing we need to do is to just make sure that we display rendered posts on the screen somewhere so we just need to make sure from the overall component we return something that's going to wrap up or display rendered posts so inside this div i'm going to open it up give it a opening and closing tag and inside there i'll show rendered i'm also going to give this div right here a little class name i shouldn't say little this is going to be a kind of long series of class names just to get these cards to display or lay themselves out very nicely we're going to say d dash flex flex dash row select wrap and then just one more justify dash content dash between and i'll save that line once again so you can see it there we go okay let's save this flip back over quick test and there we go now you probably see something like this right here just as a reminder whenever i'm showing my browser window i'm almost always zoomed in so you can see everything on my screen very easily so we've got that post listed right there and of course we can create another post so i'll say second post we can submit it the post does not show up on the screen right away that's because we don't have any logic to actually refresh our list of posts so i need to manually refresh the page and once i do i'll see the second post appear i can do third post submit it refresh and there's my third post all right well i'd say we're off to a good start so one more quick pause come back we're gonna start to tackle all this commenting stuff so i'll see you in just a moment there's just two more components we need to create very quickly we're going to get through these rather fast because they're really the same as two components we put together before so we're going to make comment create and comment list let's get to it we'll first start with comment create back inside my editor for the react project i'm going to make a new file inside the src directory called comment create dot js inside of here we'll import react right away and then create a new component and export it like so and for right now i'll just return once again an empty div now let's think about what comment create really needs to do comment create is going to represent this form right here so user's going to type in some content for the comment and then click on submit the expectation is that we should take whatever content the user enters and make a post request off to our comment service now one thing i want to point out in particular is that whenever we create a comment we have to know the id of the post that we are associating that comment with so inside of our comment create component we need to know the post that this comment is going to be associated with so long story short whenever our posts list or a post inside a post list is going to create a comment create component we need to pass down the id of the post that it's going to be associated with that's the long and short of it so inside of comment create we're going to assume that this thing is going to receive a prop so we're going to receive some props right here that's going to contain something like post id or something very similar i don't really expect to receive any other props inside this thing so i'm going to destructure out just this host id value okay so we're not going to make use of post id just yet but i just want to talk about it right away just to make sure it's really clear yeah we needed to know the id of the post that we're going to associate this comment with so now we can start to put together the rest of this component to get started let's work on a little bit of mock markup i'm going to expand this div inside there we're going to want a form element because this thing is all about showing a form that the user is going to enter some text into inside that we'll place a div with a class name of form-group inside that div we'll do an input and right above that let's do a label as well on the label i'll give it some text like how about new comment on the input let's add in a class name there as well i'll do form dash control we'll add in some event listeners and whatnot in just a moment first right outside of that closing div that we've got right there i'm going to add in a button that says submit and i'll give it a class name as well of btn utn dash primary okay so this is a good start so now we need to make sure that we've got a piece of state that's going to track whatever value a user has inside this input we need to make sure we've got an event handler on the form itself to watch for a submit event we need to make sure that we've got a function that's actually going to make a post request off to our comments microservice and attempt to persist the given comment so let's get to it let's first add in the use state hook we're going to create a new piece of state that's going to track whatever value the user has inside that input so we'll say how about content and set content it's going to come from use state and we'll give it a default value of empty string then we can set up some event handlers and value setters on the input itself so i'll say that this thing's value is going to be equal to content and it's going to have an onchange event listener whenever a user changes this input we're going to receive an event which once again will abbreviate just as e and we'll use that things target.value property to update our content piece of state we'll say set content e target value okay that looks good so now let's work on the form itself we're going to add in an on submit listener once again anytime this thing gets submitted we'll call a function that we'll call simply on submit so let's define that function right away so on submit is going to be an async function because we probably need to make a request inside of here because this is a form submission once again we're going to receive that event object and call prevent default on it and so now finally right here is where we're going to want to take our content and the post id and use them to make a request off to our comments micro service so let's make sure that we import axios at the top so we can actually make that request and then inside of here we'll do an await axios.post it's going to be a post request because we want to create a new comment and then remember the path that we said that we were going to use for that microservice we said that we were going to make a post request to post slash the id of the post we care about slash comments and we're going to include a body of content and that was going to have a string so inside of here we'll use a template string notice i'm using the backticks and we'll say http colon slash localhost and then remember our comments microservice is at port 4001 we'll do slash posts and then we'll do some string templating here and put in our post id which we discussed a little bit ago that's coming in as a prop slash comments then we'll make sure that we provide the actual content inside the body of the request that's inside this object right here provided as a second argument and we'll throw our content inside there so that should create a new comment and associate it with a given post right after we make this request successfully we're going to once again clear out the value of that input so we're going to reset the inputs value back to an empty string just to make sure it's clear to a user that hey your comment has been persisted right after that i'll do a set content of empty string okay so that looks good now before we test this we need to make sure we actually show this component somewhere remember we want to show that component inside of our post list every single post that we display needs to have an instance of comment create displayed right underneath it so we'll go into post list and find where we iterate over our list of posts to build out this list right here so i will go back over to postlist.js i'm going to scroll up to the very top and i will import post or see me comment create from comment create we'll then find where we mapped over all those posts here's the mapping statement right here so this is where we display the title of the post and as we just saw in our mock-up we want to display that form right underneath it so right after that div or see me right after the h3 my mistake we want it to be inside the div so it's got that card body class applied to it we're going to display our comment create component and we'll make sure that we give it its required property which is the post id we'll say post id and we've got access to the post ids via this post variable right here so we'll pass in host dot id okay that should be it let's save this we'll flip back over and once again do a quick test so i can now see my comment creation form i'll enter in a comment and then submit it and with my network request tab open i can see that that comment was created successfully all right so that looks pretty good now the last thing we have to do here is just make sure we put together the comment list component so quick pause work on that component finish it up in just a moment all right very last component as soon as we're done with this thing as i mentioned several times this is where we're going to start to see some weird things start to appear and this is where we're going to get back into the world of micro services but just a little bit more of this react stuff let's finish this off we're going to flip back over to our editor we're going to start working on this comment list component so back inside my editor inside the react project i'm going to find my src directory and inside there i'll make a new file called comment list.js at the top we will import react and the use state hook from react we'll get axios from axios and you know once again i forgot we also need use effect as well so we'll get use state and use effect then inside of here we'll do an export default and once again right now i'm going to return an empty div so what do we really have to do inside of here well very similar to our comment create component our comment list is going to be responsible for managing its own data requirements so we want comment list to make sure that it can reach out to our comments microservice and fetch all the comments associated with some post if we take a look back at the api design for our comment service here it is right here remember that we said that we can make a get request to post slash host id slash comments so we once again just like inside of our post create component we need to know the id of the post that we are trying to show commons for so all that really means is that we need to make sure that we communicate a post id from post list down into comment list so back inside of our comment list component i'm going to once again assume that this component will receive a post id as a property then inside of here we can write out some logic to fetch some data set it on state map over that state produce a list of comments and display them to the user in practice this is going to end up being very very similar just about identical in structure to what we did back inside a post list a moment ago so we're gonna have some piece of state we're gonna have a function to fetch some data we're gonna call that from use effect and then we will map over the data that we fetched so now that we know we're gonna do let's write out that code so first off we'll get some comments and set comments coming from you state we're going to initialize this to be an empty array you might recall that on our post list we initialize that piece of state to be an object but whenever we get a list of comments remember what our api sends back to us the api that we put together is going to give us an array of comments associated with the given post so in this case we know that we're going to be working with an array i'll then define a function called fetch data this will be an async function inside of here we'll get some response from calling await axios.git i'm going to once again pass in a template string we're going to make a request to http colon localhost and again we're going to our comments microservice which is hosted at port 4001 then the path that we need to make the request to is posts slash then the post id slash comments so then take the data out of that response and update our comments piece of state using that set comments function we'll call set comments res dot data next up we need to make sure that fetch data is called just one time when this component is first displayed on the screen so that's what we got that use effect i'll put together a use effect call we only want this effect to be called exactly one time so as a second argument we'll put in that empty array and then inside of here we will call fetch data and that's pretty much it so now last thing we need to do is map over our list of comments and return some jsx out of that entire list so to build out that thing i think inside of our mockup we displayed it as a unordered list right here so a ul with some lis so let's map over that array of comments it will say const rendered comments is comments.map and for every comment that we get back we'll return an li inside the li will display the content of the comment because remember every comment that we've created has a content property we'll say comment dot content because we are building a list right here react is going to expect this li to have a key property assigned to it so we will assign a key property and inside there we'll use the comments id so then finally at the very bottom i will return a ul and inside there i will display my rendered and that should be it so once again let's save this file we'll then go back over to our post list component that's where we said we were going to show this thing from so inside a post list we want to show many copies of comment list so here's my post list component at the very top i will import comment list around comment list we'll then go down to our rendered posts map function so this is where we iterate over every post and then right after comment create we can show comment or something not right after we want it right before because we want to show the list of comments and then give the user a form to create a new one so right here is where we will put in comment list and once again remember we need to tell comment list which post or which id of post which post id there we go this thing needs to retrieve comments four so just like comment create we need to pass down that post id prop we'll say post id is post dot id okay let's save this and we'll do a test okay i see my comment that i created just a moment ago appear right there now i should be able to create yet another comment so i'll say second comment i'll submit it i'm going to refresh the page because remember we don't have any kind of a reload logic inside of here right now and i'll see second comment appear and i should be able to associate some comments with these other posts i created so i'll say neat post and then on the third one i'll put in something like this is a great post i'll refresh the page and i see those comments appear well this definitely works but like i said there is some big downsides here so if we take a look at our network request log i'm at network i'm filtered by xhr requests and if i refresh the page i just want you to notice something very simple might seem very benign and small we are making one request for every post we have fetched and that's kind of the root issue that we are in right now that might not seem like a big deal but let's take a pause right here come back the next video and i want to highlight why this is kind of a big deal right now real quick note if you skipped over the entire react application chances are you downloaded the completed code from the last lecture if you did so make sure you read the text note inside that lecture so you need to make sure that you overwrite your entire current project with all the code from that zip file we made two small changes or really one small change in two locations to the post service and the comment service you need to make sure that you get those updates after you update those files make sure you rerun npm install in the post and comments directories okay so let's get back to it in the last video we finished up with the react application and we saw that while we were able to see all of our different posts and comments associated with them there was a downside here and that downside is that for every single post we load up we are making one request to our comment service to get all the comments associated with that post so in my case i've got three posts right here and i ended up having to make three separate requests to our comment service to get the comments for each one so in other words we're in this kind of scenario right now we are making a get request to some post endpoint that's giving us back an array more or less of posts and then for every one of those we have to make a follow-up request this is incredibly incredibly inefficient so i think it would really be worth our time to figure out how to maybe condense all this stuff down to just one request i want to be able to make one request one single request and get all of our posts and all the associated comments for those posts as well that's what i want to try to do now if we were trying to do this in a sort of monolith architecture this would be really easy and straightforward to do so if we were building a monolith right now we could maybe say that if we ever make a get request to slash posts and add on a query string that says something like comments equals true maybe that would be some sign to our monolith server that we want to get a list of our posts with all of the relevant comments embedded in those posts as well this be super straightforward super easy with a monolith approach but of course we're not using a monolith how are we going to solve this with what we have available how we can serve this with microservices right now we only have the ability to make a request to either the post service or the comment service so we need to figure out some way of solving this problem well to solve this this really goes back to something we discussed a little bit ago the different styles of communication between services so we're going to take a look at two possible solutions here and the pros and cons of both these solutions are going to be very similar to those methods of async and sync communication that we discussed a little bit ago so we'll first begin with the solution based on synchronous communication with this style solution we might say that we are going to continue to make a get request to our post service and then maybe to make sure that we get all the relevant comments embedded we could add some code to our post service to reach out automatically to our comment service and say hey give me all the comments you have associated with these post ids the common service would then reply with all the relevant comments then the post service would take those comments assemble them all together with the relevant posts and then send the entire bundle back over to the browser so again this is one possible solution that relies upon synchronous communication the downsides to this approach are identical to the downsides we discussed earlier when we are first talking about synchronous communication so while this approach is conceptually pretty darn easy to understand well there's a lot of downsides to this approach as well first off it introduces a dependency between these services this is another thing we have to track and understand inside of our application if we ever have the comment service go down for any reason so if this thing just mysteriously disappears all of a sudden our post service is probably not going to work correctly either if that request from the post service over to the comment service fails then the overall request is going to fail as well so we will show neither posts nor comments we also are introducing another kind of round trip request here between one service and another so if for any reason that request is slow then the overall request coming from the browser is going to be delayed or the response is going to be delayed as well and once again we discussed this back on the synchronous communication stuff right now our application just consists of two separate services but if we started to add in a bunch more services and for some reason fetching comments from the common service required some calls to other services we're gonna start to build up this tree or really a web of different requests which really exaggerates all these earlier problems as well so even though this is conceptually easy for you and i it is perhaps not the best solution from an engineering standpoint now that we have taken a look at the synchronous communication approach let's pause right here and then take a look at a second possible solution that we could use we just said that using synchronous communication was maybe not the best way of solving this because although it's really easy for you and i it's not really the best solution from an engineering standpoint in this video we're going to take a look at a second possible solution as you guess this is going to be an asynchronous communication based solution remember with asynchronous communication we frequently introduce something called an event broker and the goal or purpose of this event broker is to receive notifications from some different services take those notifications or those events and route them off to all the other services that we are running so with this approach we're going to dramatically change how our application behaves we are going to introduce the idea of a query service down here the goal the query service is to listen to any time that a post is created or a comment is created so anytime a post is created or a comment is created we're gonna have these services emit an event the query service will then listen for those events and it's going to take all the different posts and comments to get created and assemble them all into a very efficient data structure that can essentially solve our root problem right now which is to make sure that we reduce all these number of requests down to just one single request so again the goal of this query service is to take all the different posts all the different comments and just serve them up to the browser in one very simple and easy request let's take a look at how this would actually work in practice so here's where everything would start whenever someone makes a post request to the post service we're going to have our post feature emit an event and it might look something like this maybe it's an event that has some type of post created and it has some data associated with it as well and that data might be the actual post that was generated so it would have an id and a title the post service would throw that event off to the event bus and then the event bus would automatically route that event or send the event off to all of our different services that express some interest in it we might send that event off to our query service then it would be up to the query service to somehow process this event and store some data from it i've got here the query service and the event that it needs to process we might decide to create some kind of data structure like the one you see right here to store all these different events that are coming in so in this case we might have a kind of collection or object keeping track of all of our different posts we might store the id of every post that has been created its title and all the relevant comments so anytime that we see this post-created event come in we would take that id right there and enter in a brand new post so it'd be a1 jp5 is the id the title is new post and then right now we don't have any comments associated with this post i'd probably just default this comments property right here to be an empty array for right now until we start to actually receive some comments then we can imagine that at some point in time in the future maybe someone creates a comment tied to that post so someone will make a post request to our comment service and very similar to what we just went through we're going to have our common service emit an event that might look a little something like this it might have a type of comment created and some data related or describing the comment that was just made so i will go to our event bus and the event bus is going to take that thing and route it off to any service inside of our app that is interested in it now it's up to our query service once again to process this new different incoming event so we're back to our query service we still have that same kind of data structure that we had before and we've got the definition of some existing post inside there already so we'll write out some code inside of our query service to process this event it's going to take this comment that was just created it's going to find the related post with this given post id right here in this case the post id is a1 jp5 okay there's the post right there so our query service will take this comment and add it into some kind of comments array i'll say the id of this comment is 2j56 and the content is a comment like so then at that point in time someone can make a request directly to our query service and ask for all the different posts and all the related comments and all our query service really has to do now is take this entire data structure and send it out and inside this thing we've got all the relevant posts all the relevant comments so again this is this kind of asynchronous communication style in this diagram i just want to make sure it's really clear rather than making a get request to our post service now to get a list of all the posts and whatnot we would instead make a get request down to the query service instead so that would require making some changes inside of our react application okay so at this point i want to go over some pros and cons of this approach and it turns out yeah the pros and cons are identical to what we discussed before this query service that we're imagining creating doesn't really have any direct dependencies on other services yes totally with you i understand it does rely upon some incoming events that are being issued by those services but if those services go down for any reason if they stop functioning if they stop working the query service is still going to work as expected the query service is also going to be really really fast compared to that more synchronous style of communication the reason for this is that we're not making any requests between our different services anymore if someone ever wants to get a list of all the different posts and comments associated with them that's gonna be one very simple request the downsides here are identical to the downsides we looked at previously we now have some data duplication one thing to be clear about is that even in this asynchronous style approach if we have say a post request come into the post service right here the post service is still going to store a post it's still going to have its own idea of what a post is so still being stored here but we're also storing what a post is or this some information about this post inside of our query service as well so we now are now effectively duplicating data between these two services it might sound really wasteful to duplicate this data but there are some really good reasons to persist data between these two services and these reasons are something that we'll discuss a little bit later on and then the last issue here is well without a doubt way harder to understand no doubt about it from an engineering standpoint this is a lot harder to implement because we need to be aware of all these different events that are floating around our application however when it comes down to the actual operational efficiency of this it's going to be incredibly fast no issues with dependencies on their services so again if anything else goes down this service will continue to work now at this point you might be thinking all right steven sure whatever maybe this is how it's done you might have some really big questions so i put together a quick diagram here where i think i've got some questions that you might have at this point in time and some possible answers to them this video is going a little bit long however so let's take a pause right here and we'll go over some of your concerns that you might have with this approach in just a moment we've now taken a look twice at this style of asynchronous communication and at this point you probably have some really burning questions so in this video i want to go over some questions i think you might have and some possible answers the first thing you might be thinking is something like wait a minute steven you're saying that if we have two types of resources so in our case posts and comments if we want to serve up that information effectively we have to create a third service no that is not what i'm saying at all we are not always going to be creating extra services just for the sole purpose of joining data together in reality if we were actually building this sort of blog application well this blog application will be part of a larger a scheme of resources or a larger application in reality we would probably put this idea of posts and comments together in the same service so we could join that data together at the code level rather than at the service level by creating a third service so what we're doing right now this is solely for learning purposes this is just to help expose you to these ideas of how we can have information stored in multiple services and eventually kind of replicate that data or make use of it in one single location so i'm not advocating that you create an extra service for every last join of data that you need second big question you might have i've been saying many times that these services are independent and if one crashes the others stay alive you might say who cares how often are these services going to be crashing well at this point in the course i haven't really gone into a lot of reasons on why you would use microservices in the first place to be totally honest with you i'm kind of assuming that if you're in this course you've already done at least a little bit of research and you might have an idea of why you want to use microservices one of the big reasons that we use microservices is the possibility of increasing the overall reliability of our system that's a huge driving force in why we use micro services so the fact that we can make these things independent and keep the vast majority of our application running even if some part of it goes down that's a huge driving force in why we are here learning about micro services in the first place okay third thing you might be saying okay this is way too complicated for the tiny bit of benefit that we get we're having to create entire new projects just to support these very basic data queries and i know it seems that way now i know this entire event style architecture might seem really complicated and challenging but it really just seems like that at this point we're going to very shortly start to add in another feature to the project so the one we're working on right now and by taking this kind of event style architecture adding in this additional feature is going to actually be somewhat darn easy compared to if we were using a monolith or possibly some kind of synchronous style of communication so i know it seems like this is way over the top right now but it turns out that some things down the line start to get a little bit easier the last thing i want to mention here is that at this point if you are really starting to think through this architecture you might be starting to say hey steven wait this system isn't going to work in the scenario or what if this event occurs and that event or what about this corner case over here just to be clear there are definitely some super special corner cases that you and i need to be concerned about are very special scenarios when we start using this event-based architecture we are going to take a deep look at some of these problems and i mean a deep look later on inside the course and if you don't see anything wrong with this current approach hey don't sweat it it's something you really have to think about for a pretty long time before we start to realize where things start might start to go wrong again if you see some stuff that looks a little bit funny right now don't sweat it we're going to go over a lot of possible quarter cases later on and we have solutions for a lot of them i'm not going to say like every possible solution i'm sure you could think of some things that are going to go wrong that i have not thought of but again on that big application we're going to work on later we're going to look at a lot of these different corner cases okay so that's it just want to go over a couple of questions and answers that you might have had so with all that in mind let's take a pause right here we're going to start to implement this new query service we're going to start to set up this event bus and then have all these services communicating with each other via events in the next video the last couple of videos we've had have been just a bunch of lecturing for me i know that's super boring just one more lecture and then we're going to start writing some code again so in this video we're going to go over the design of the event bus we're going to talk about how we can use an event bus to communicate events from one service over to another as a reminder we're going to try to build as much of as the stuff as possible from scratch rather than using some off-the-shelf solution and that includes the event bus so we're going to build this event bus on our own we're going to build it using javascript and express i want to give you a couple notes on how this thing needs to work okay so event buses the first thing to understand about them is that there are many different implementations available you might have heard of terms like rabbit mq kafka or nats these are all different types of event buses they're open source projects you can download them and run them yourself or you can get some kind of pre-hosted provided solution the one common thing between these different event buses is that they're going to receive events and then publish them out to listeners when we use the term events here we're really talking about some piece of information there's no set structure of what a event has to look like it can be json it can be raw bytes of data it can be a string it can be whatever you want to share between your different services when we use the term listeners we're talking about other services that want to listen to events that are being emitted now between these different implementations of say rabbit and q kafka nats and many others that exist out there it turns out that there are many very small features available in these different event buses that makes some things a lot easier or a lot harder so in this larger application that we're going to work on in the second half of this course i picked a event bus that is really easy to get started with extremely fast but there are some downsides to it as well some things that are going to make our lives a little bit more complicated so you just need to be aware that you cannot just pick one of these implementations off the shelf you kind of have to evaluate them and understand what they can really do for you now once again we are going to build our own event bus using express it is not going to implement the vast vast majority of features that a normal event bus has so ours is going to be incredibly simplistic incredibly simple not very useful outside this one single implementation but again we're going to build this from scratch just so you have a really good idea of what is going on behind the scenes and yes again for our next application we're going to work on the much larger one we are going to use a production grade event bus this is an event bus that is used in many many very large deployments and projects so you're going to get some very practical experience with some real technology as well all right let's talk about the express based event bus that you and i are gonna put together now this really is a very simplistic implementation for eventbus the reason we are doing such a simple implementation is just so you can see how this stuff kind of works behind the scenes and so you can very easily see the flow of data throughout our application so let me tell you about how this thing is going to work we are going to add in a new route to our post service and our comment service we're also going to make sure that our query service has a very similar route as well each of these routes are going to watch for a post request to a path of slash events we'll talk about the purpose of that in just a moment at some point time inside of our application we're going to have our post service or common service decide that it needs to emit an event whenever a service needs to emit an event it's going to make a post request off to this new event bus that you and i are going to put together again this event bus right here is going to be a plain express application essentially we're really just doing a post request from one service to another in that post request we're going to attach along some event data so it's going to be some object that represents this event right here this event bus is going to receive this event it's going to take that event and make a series of post request with its so it's going to take all that event data and it's going to take that exact information and just send it off to a post request to localhost 4000 events that would be our post service it's going to make an identical request off to local host 4001 events and same thing or localhost 4002 events so in all three of these post requests it's going to send along this event data so in short anytime one of our services makes a post request over to eventbus the eventbus is just going to take that exact information and throw it out to everything else that we have running inside of our application even the same service that emitted the event originally so that's it that's how simple our event bus is going to be now again as we start to use some more production ready application or solutions here for the event bus you can see that there's a lot more to this implementation but at the end of the day this is pretty much what is going on more or less we're throwing an event over to the event bus the event bus is just going to echo that event back over to all of our different services so now that we've got an idea of what's going on here quick pause we're going to start building this event bus which is going to be very simple very straightforward in the next video all right let's get started working on this event bus implementation to get started we're going to first create a new folder inside of our project directory to house all the code for this event bus so i'm back at my terminal i'm going to open up yet another terminal window so i've now got four got one for the react app one for posts one for comments i'm down here in the new one in the new one i'm going to change back to my blog directory which is housing all of my three overall services then in this folder i'm going to create a new folder called events we'll call it how about eventbus just be really clear i'll then change into that directory let me make this window just a little bit larger inside of here we're going to generate a new package.json file so that's an npm init dash y and then we're going to install express nodemon axios and i think that is about it yup that's it we'll go ahead and run that and then after this is done i'm going to open up my code editor inside this directory all right so as usual we're going to create an index.js file inside of here at the very top we're going to import express we're going to get body parser and we'll get axios as well i'm then going to create a new express application i'll then associate the body parser json middleware with this app so we'll do an app.use bodyparser.json and then that's pretty much it for the initial setup now all we have to do is implement this endpoint to watch for incoming events so as we just saw in this diagram back over here it's going to be a post request handler that's going to watch for post request to slash events anytime we receive an event where it's going to turn right back around make a series of requests to these different servers so we'll set up a post request handler on slash events i'm going to put in my callback right here we're going to get our event which we're going to assume is just going to be the request body so whatever comes along in the request body that is going to be our event we don't know if it's going to be a json object we don't know if it's going to be a string a number who knows what all we know is that we're going to take whatever is inside that request body and send it off to all of our different running services so now that we've got that event we're going to make our series of post requests to our other running services so we'll do an axios dot post to http localhost 4000 events and the data that we're going to send along is that exact event i'm then going to duplicate that line twice and i'll put in localhost 4001 and then localhost 4002 and then finally at the very bottom we'll do a res.send and we'll just say anytime someone tries to emit an event we'll just send back something that says status okay just to indicate that everything worked as expected now there is one downside to the implementation we have right here we are assuming that all three of these post requests are always going to succeed we don't have any handling code around the possibility of one of them failing that's just something i want to point out right now because it's going to start to become a little bit relevant as we start to implement each of these different event endpoint handlers okay so now finally at the very bottom we're going to make sure that this thing is listening so we'll put on an app.listen we're going to have this listen to 4005. notice how i skipped a couple ports right here so we've got our posts our comments soon to be our query service and then our event bus is just going to go directly up to 4005. i'll put in my callback and i'll do a console.log on 4005 okay so that is it for our very simple very basic event bus implementation now last thing we're going to do we're going to open up that package.json file we're going to update our script inside of here so i'm going to delete the default test one and replace it with the start script once again we'll do nodemon index.js okay so let's go back over to our terminal i've got my fourth terminal window right here so again react posts comments eventbus i'm inside of eventbus and inside there i'll do an npm start and so i should see a listening on 4005 very good now that we've got our very simple event bus put together let's take a pause right here in the next video we're going to make sure that whenever someone creates a post or a comment we're going to emit an event over to our event bus so quick pause and i'll see you in just a minute we've now got an initial implementation of our event bus put together we're now going to start to go through our post service and our comment service anytime something interesting happens inside those services such as creating a new post or creating a new comment we're going to make sure that we send a request over to this events endpoint in our event bus and in that request we're going to include the event eventbus will then take that event and echo it out to all the different services running inside of our application at present our different services do not have this post events endpoint wired up so when the event bus tries to send that request over the request is going to fail due to a 404 as soon as we make sure that the event bus can emit this event we'll then go back over and start to implement these endpoints but the other services can listen to these events that are being emitted but again for right now we're just going to make sure that the post service is going to emit this event anytime someone creates a new post so let's get to it between the last video and this one i opened up my code editor inside of my root blog project directory we're going to start to have to change between all four of these different services very quickly and so it's just a lot easier to maneuver between them if we have all of our projects open inside of one editor as opposed to for separate editors i'm going to find the post directory inside there i'll find the index.js file at the very top i'll immediately require an axios like so i'm then going to scroll down to our post endpoint so this is the code that gets executed every single time someone tries to create a new post so this would be a perfect time to try to emit an event saying hey someone just made a new post right after we add the new post to our post collection i'll use axios to make a post request over to http colon slash localhost olin 4005 because remember that is where our broker is running slash events and then as a second argument we'll put in the actual event that we want to send over so for right now we'll say that every event that we met is to have two properties the first one is going to be a type and that type describes the event that just occurred the second property will be a data property and that will have some information that further clarifies exactly what happened so in the case of creating a post will probably include the actual post that was just created as the data property remember the event that we send out throughout our application can have any structure we want it doesn't even have to be an object it can be a string or a number any data you want to have but usually we're going to make sure that all these events have a very consistent structure we'll talk more about the design and sort of schema of events quite a bit over time so for right now we're just going to say that every event will have a type and data okay so see object right here is essentially the event that i want to have be emitted or my entire application so i'm going to give it a type of post created and then a data and data is going to be the post that we just made and remember all of our posts have an id and title that's essentially what our post is so we pretty much want to take that style of object right there include it as the data property we'll say id and title and then finally this is an asynchronous operation making the network request so we will add on async and await like so okay i'm going to save this we're going to flip back over to our browser and find our running react application i'm going to refresh this page and as soon as i do you'll notice that all the posts go away that is totally fine it's because remember all of our posts are being stored in memory with that post service so as soon as we restart that server all of our posts just disappear all right i'll go ahead and try to create a post i'll call this new post and submit it we don't have any kind of live reload on the react application so i have to refresh the page as soon as i do so i do see the new post appear but what happened to that event well let's go take a look at our terminal we'll take a look at our server logs and we'll just make sure that the post service did try to send that event over to the event bus okay so here are my terminal logs right here this second window that i have right here that's kind of highlighted is the post service i don't see any information there that's very interesting if i go down to the bottom window right here that is where my event broker or event bus is living or actually running at present it looks like there is a couple of errors here so all these errors are identical in nature they all say request failed with status 404 so that is actually good remember as i mentioned just a moment ago our post service comment service and query service that doesn't exist yet exist yet does not have this post slash events endpoint they don't have any way of actually receiving these events so even though the event bus is trying to send that event off well there's nothing receive it which is why we're getting that 404 error so overall let's say this looks good we are definitely emitting an event to the event bus anytime something interesting happens inside the post service so let's take a pause right here and continue in just a moment we're now going to move on to our comment service we need to make sure that anytime someone creates a new comment we once again emit an event over to that event bus in this case our event is going to look a little something like this it'll have a type of comment created and the data in this case will be the actual comment itself so once again we're going to send this over to the event bus and the event bus is going to echo so to speak this event over to all of our different services we're going to once again see that we're going to get a couple of 404 errors because again we don't have anything on the services themselves to receive these events just yet all right so i'm going to change back over to my editor i'm going to find the comments service folder here it is right here inside there i'll open up the index.js file at the very top i'll get axios i'll then go down to my code where i'm creating a new comment here it is right here i'll then add in right after we add in that new comment right there or we push it into that array right about right after that's really where we kind of save so to speak the comment i'll go ahead and we'll add in axios.post to localhost colon 4005 slash events and once again the data or the event that we're going to send over is going to have a type of something like comment created and a data property that's going to be the actual comment itself so remember a comment is going to have the comment id some content and then in that case or in this case that is the entire comment but we're going to also add into this data property another property of post id just to clarify exactly what comment this thing is tied to so in this case for data i'm going to put in the id of comment id the content and then finally our post id as well which is available inside this request handler remember it's technically in that parameter string right there or the route string so we can access it using rec params.id we'll say post id is rec.prams.id and then once again i'm going to add on async to the wrapping function and a wait on the request itself okay so that looks good so let's test this out again i'm going to flip on over to my browser i'm going to find the post that we had just created and i'll add in some comment and submit it i can refresh the page see some comment appear and then finally i'll go over to my terminal and i'm going to expect to once again see a series of 404 errors coming out of our event bus again that's because we don't have anything inside of our services yet to actually receive these events okay so that looks good well at this point in time we've now got two services that are emitting events whenever something interesting happens so now we need to make sure that all of our services right now really just post and comments because we've not yet created the query service has an end point where it can receive these events and then do some processing on them if that service cares about the event that was just emitted in our scenario or in our case right now our post service and the comment service don't really care whatsoever they just don't care about any incoming events out of the two that we've created comment created and post created but as soon as we make this query service well we're definitely going to have something that is very much interested in some events that are coming out of our application so quick pause right here we're going to start putting this and this those two event or something route handlers together in just a moment let's go ahead and put our events handlers together for the post service and the comment service so i'm going to get started by going first to my post service i'll find the index.js file and then towards the very bottom of the file but right above the app.listen line i'll add in a new post request handler so this will be app.post to slash events we'll get our wreck and res in there and then remember this endpoint is going to receive any event that is coming over from our event bus so for right now inside of our post service we don't really care about any events that are coming over but let's just go ahead and log any events that we receive just to say hey this event exists so i'll do a console.log of received event and we'll just print out the type of the event so how about rec.body that's going to be the actual event and remember every event that we receive we said that it was going to have a type property so i will print out the type of the event that we just got after that i'll make sure that i still respond to the request that was issued just to say hey we got this so we'll do a res.send of empty object let's just say yeah we got this event everything's good to go so now repeat the same process over inside of our comment service as well i'll find my comments directory index.js inside of there i'll go down towards the bottom and right above the app.listen line i'll do an app.post for events we'll do a console log of event received and rec.body.type and then we'll do our res.send empty object okay so that should be enough to test this stuff out so now we're going to really see the entire process here we're going to see everything from start to finish if we take a look at our terminal after we start to emit some events we should see some console log coming from our post service and the comment service and they should say every single time they receive some kind of event so let's try to test this out i'll go back over to the browser and find my application i'm going to refresh the page once again because remember every single time we make a change to our code we dump all of our data i'll go ahead and create a post i'll say new host and submit if i refresh yep there's the post but more importantly let's go over to our terminal so here's my eternal window and i can see that we've received an event for post created inside of our post service this terminal window right here is from my comment and we've also received an event of post created our event bus is still throwing an error down here that's okay because remember it's trying to send a request or this event over to our query service which does not yet exist let's also try to create a comment and just make sure that the event of comment created is being sent to the post and comment service as well so back inside my browser i'll put in a comment here of a comment i'll submit it i'll refresh just make sure i see the comment right there and then finally if i go back over my terminal there we go so i've got my event of common created and comment created okay so that is it that is the full communication cycle we have our post service sending events over the event bus takes that event and sends it off to service one and two and in a little bit not quite yet but in a little bit it'll try to send it off to the query service as well so now in theory if we had any kind of data dependency or more strict data dependency between our post service and common service we could watch those incoming events and deal with them in some way as i've said several times now in the last couple of videos the post and comment service don't really care about any events that are being emitted right now but now that we've got these events coming out let's start to put this query service together i will make sure that the query service listens for a post created or a comment created event starts to take that data and assemble it into some kind of usable data structure in the exact same way that we've discussed over all these last couple of diagrams where are they like this one yeah here we go like this one right here remember we're gonna take all those events and assemble them into some usable data structure okay so we're gonna take care of that in just a moment so i'll see you in just a little bit in this video we're gonna get started working on our query service so remember the goal of this service we want to have one service that we can make a request to to get a full listing of all the different posts and their associated comments the one request all the data we need to actually implement this thing we're going to give it two different route handlers one route handler is going to receive events from our event bus our query service is going to care about events of type post created and comment created whenever it sees these events it's going to take the data contained inside the event itself and then assemble it all into some very easy to access data structure the second endpoint that we're going to implement is going to have a handler for watching a get request to slash posts anytime someone makes a get request to that endpoint we're going to send back a full listing of all posts and related comments so let's get started working on our query service right now to begin i'm going to open up yet another terminal window here's my new window right here i'm going to change back into our root blog directory that's where all of our services live right now and inside there i'll make a new folder and we'll call simply query i'll then change into that directory and i'm going to generate a package.json file using npm init dash y after i generate that file we'll then go ahead and install two dependencies all we need for this service is express and cores the query service itself is not going to actually emit any events and that's why we are not installing axios i know ahead of time that the query service is not going to emit any events but if you were working on this from scratch and if you were unsure about whether or not this thing was going to emit any events you would go ahead and install axios until you were sure that okay i don't actually need to emit any events and then you can remove that dependency okay so i'll go ahead and do that installation i'll then go back over to my editor and i should see that new query directory so let's start to build this express application out inside of that directory i'll make a new file called index.js and then at the top let's go ahead we're going to require in express body parser and that course module as well so i'll get express i'll get body parser and i'll get course i'll then create my new express app and i will wire up the body parser and i will wire up cores okay so that looks good so now we're going to put together our two route handlers remember the two that we want are for a get to slash posts and a post to slash events we'll do app.get slash posts and then put in our rec and res and right now i'll just leave that empty and then the next one will be app.post to slash events so this is of course the endpoint that is going to receive events from our event bus then finally at the very bottom let's go ahead and set up that app.listen call we'll do an app.listen and remember at present we are using a couple of different ports we've got ports 4000 4001 and 4002 i think now just four thousand and four thousand one so this one will be at four thousand and two and we'll put in our callback inside of here we'll do a console log listing on 4002 before we start to worry about any implementation here just yet let's make sure we can actually run this project so i'm going to save this file i'll go back over to package.json and we'll set up a startup script ah that's what we forgot on dependencies we forgot to get nodemon i'll go and install that really quickly as well so back over my terminal we'll do an npm installed nodemon and then once that is installed we can update that start script so start will be nodemon index.js let's just run this project really quickly to make sure we don't have any typos or anything like that so at my terminal and the window that is running our query service we'll do an npm start and there we go listing on 4002 well now that we've got all this boilerplate put together we can start worrying about the actual implementation of the post events endpoint and git post as well we'll do a quick break first and then start to worry about those two endpoints in just a moment our query service has a little bit of scaffolding put together so now we need to make sure that it can receive events of type post created and comment created whenever we get post created we're going to save the post whenever we get comment created we're going to save the comment with the associated post the first thing we have to do back over here is decide on a data structure to use to save all these posts and comments we're going to once again use a simple object to store all the posts and comments let me very quickly give you an example of what this object is going to look like eventually so you don't have to write this code out this is a quick example of what post is going to look like so posts will be equal eventually to having an object full of some keys and for every one of these keys we're going to have the id of the post so that would be identical to the id right there it will have the title to post and we'll have an array of comments associated with this and of course every comment will have its own id and some content like so so over time as users add in more posts to our application we would have say a second post and then a third post and so on again that's what this post object is going to look like so we just need to make sure that as we receive all these different events we insert data into this post object with the appropriate structure okay so inside of our post to events right here we're going to take a look at that rec object remember the rec.body property is going to be the event itself that we actually care about so let's take a look at that event remember that every event that we create has a type and a data property i'll pull that out of rec.body we will then set up a very simple series of if statements to take a look at that type so we'll say if type is equal to post created then let's go ahead and run some code or if type is equal to comment created we'll do something entirely different so let's handle post created first if it's equal to post created that we want to take the id and the title out of data because remember with post created that event is always going to have an id and a title and we're going to insert that information into our posts object we'll say posts at id is going to be equal to an object of id and title and that should be it we'll probably also want to default the value of comments to be an empty array as well so that later on whenever someone emits an event of comment created and we receive that we don't have to worry about creating that array or anything like that so now let's handle a event of type comment created remember an event of type comment created is going to have slightly different structure to it it's going to have an id a content and a post id so let's pull that information out say id content and post id then we will find the appropriate posts inside of our post object jose const post is post at host id we'll then take a look at post dot comments and we'll push in this new comment so our new comment is going to have a given id and some content and that should be it of course at the very bottom here after we have processed the events this still is a route handler so we need to make sure that we send back some kind of response so i'll do a res.send of just an empty object to say hey we received the event and processed it then finally let's go back up to our slash post endpoint and anytime someone tries to get the collection of all the posts we have we'll just send back the entire post object we'll do a res.send of posts and that should be it so let's save this i'm going to go back over to my terminal you'll notice i've changed the layout here just to make sure everything is a little bit more legible so the order now is the react app posts comments query empty and the event bus right here so we're going to try to create a new post and a comment and we're right now just going to make sure that we don't see any errors coming out of this window right here because that's where our query service is running we're not actually using the query service inside the react application just yet again i just want to make sure we don't have any errors okay so i'm going to flip back over to the react application i'm going to enter in a title new post i'll refresh and i'll add in some comment to that post and refresh well everything over here still works totally expected because we haven't made any change to really any existing code just yet and if i go back over my terminal window it looks like the query service is running successfully as well of course we can't really see any data we can't really verify that it's receiving these events or processing them correctly i'll tell you what how about after we process an event inside of our query service after we run these two if statements let's just print out the current data structure or the current host collection that we have okay so i'll save this i'm going to go back over again i'll enter in a second post and refresh and then a second comment and submit and now if i go back over my terminal i should see the appropriate data being reflected inside of my query service take a look at that we've got two separate console logs the first one was from receiving the event of post created and it looks like we receive that post and add it to our post collection and the second console log right here is from creating the comment so there's the exact same post there's our list of comments and you can see that there is a object inside that array it's being abbreviated right now just because node when it prints out a nested data structure or nested object doesn't want to recursively print out everything inside there at a insane depth so chances are the correct comment is inside there we just can't really see it effectively using this tool just yet all right well let's say this looks pretty good so in theory our query service now has all the data is that is required to get the entire list of posts and all the associated comments so now the last thing we have to do is update our react application and make sure that the react application will make a request to this endpoint to get this data structure right here parse it and then use that structure to list out all the posts and comments so let's take a quick pause right here and start to work on the react app in just a moment now that our query service is all put together we're going to need to make some changes to the react application make sure that it reaches out to the query service to get the data that it needs so right now our react application makes get requests to our post service and get requests to our comment service directly whenever it needs to show posts or whenever it needs to show comments so that's not what we want anymore rather than making a request to posts or comments we want the react application to make one single request over to queryservice where it's going to get all the information it needs to show everything about our application all the posts and all the associated comments as a quick reminder queryservice runs on port 4002 so we want to make sure that we go around and update our request to go to port 4002 and make a get request to slash posts the other thing i want to mention very quickly is that right now we are just talking about reading data we're just talking about getting a list of posts to the show to the user the post service and comment service are still 100 in charge of actually creating comments and creating posts so if the react application needs to create a post or create a comment it will still reach out to these services directly all we're talking about right now is getting information to show to the user okay so let's open up our react application we're gonna make sure that we only make that one request directly to the query service so back inside my editor i'll find the client directory i'll then find src and then finally post list inside of post list this is where we are making a request to get a big list of all of our posts from the post service right now that's not what we want anymore we instead want to make a request to localhost 4002 and then still slash posts again 4002 is where our query service is running let's then do a quick console log of res.data just so we can inspect the information that comes back and just make sure that we've got everything we expect okay i'm going to save this file go back over my browser and check that check out the react application you'll notice that my app is automatically refreshed inside my console i'll see that console log so this is the big list of posts and embedded comments we got back from the query service that's the id of a post inside is the actual id of the post along with the title the post and the array of associated comments so it looks like it's working correctly right now we are getting all the data that we expect it looks like the application itself is still working as well but if you take a look at the network request log you'll notice that the react app is still trying to make that request to the comments endpoint it's not actually using the list of comments that is embedded inside of here automatically so we still have a quick change or two to make back inside my editor i'm going to remove the console log that we just added i'll then go down to rendered posts remember rendered posts is where we iterated over the list of posts that we got back inside that response then we built up a separate card out of each one we then eventually created an instance of the comment list component when we create a comment list we pass down just the id of the post that we're currently looking at and then it was up to comment list to make a follow-up request and get all the comments associated with that post id that is no longer necessary we now have all the comments that we need directly inside of this post that we are iterating over so rather than passing down the post id to comment list we'll just pass down the list of comments directly so i'll delete that post id thing and replace it with comment or assuming comments is post dot comments we've already got the list of comments we'll just pass them down directly and then leave it up to comment list to iterate over that list and render them out so i'll save this i'm going to go over to my comment list component now here's comment list and then remember comment list is currently making requests to get all that data or all that list of comments no longer necessary at all so we can delete that state or u-state call we can delete batch data and we can delete use effect i'll clean up the import statements at the top so we no longer need axios we no longer need use state or use effect and then in our props list right here we are no longer receiving post id instead we just receive the list of comments it turns out that all the other code we have inside of here is going to work just fine so we take the comments we receive as a prop we're going to map them we generate an li for each one and then render those lis inside of a ul so let's go ahead and save this flip back into the browser and see how we're doing so i can now refresh the page you'll notice that i still see my post right here with the associated comment but i only had to make that one single request over to the query service we can still continue to try to make new posts and comments and whatnot so i'll put in a third post refresh the page and i'll put in a third comment and submit that and refresh and there we go we've got our second post second comment and third post with third comment well i'd say this worked out pretty well so we have now introduced a brand new service into our application it is consuming events from these other services and it's using those events to populate some internal store of data and we did all this to make sure that we can minimize the number of requests that are required but more importantly this really is a demonstration of how we can do some cross-service communication there's something really interesting about this approach remember i laid out a couple of big benefits to this approach a while ago back in this diagram back over here i said hey our query service is not going to have any dependencies like direct dependencies on other services so why is that good well watch this if we go back over to our terminal we can now kill a hundred percent the common service that's the common service and we can destroy the post service as well so we can pretend that those two services just crashed for who knows what reason but you know what our query service is still running just fine so we can still serve up data to users of our application without any issue whatsoever so i can refresh this i still see my data appear if i try to create a new post i will of course get an error because that post service which is in charge of creating posts is not running but i still have a major portion of my application running successfully and that's all what this independent idea of independent services is about we can have some services crash others are still working and in general maybe our application will still be in a very usable state all right so this looks good but i do want to add in one last feature to this application so we'll take a quick pause right here and i'll see you in just a minute our application is looking pretty good and in this video i would like to start to add in a new feature let's first discuss exactly what this feature is going to be here's what we're going to try to do i want to add in the idea of comment moderation so in other words i want to take a look at the content of every comment that gets submitted and depending upon whether or not it has some very specific word we're going to flag that comment in some way and say hey this thing is not permitted or something like that we're going to flag comments that contain the word orange so it's going to be a very simple filter we're going to literally say does the comment contain the word orange if it does there's something wrong with this comment we want to flag it in some way let me give you a little bit more detail on this feature just to clarify a couple of different things so first off if we were doing some simple filtering like this and just trying to say whether or not a comment had orange it would make a lot of sense to implement it just in the react application but let's just pretend for a second that maybe the filter lace list changes very frequently in other words that word orange maybe in five minutes we need to change it to banana or something like that if that was the case we would not want to hard code any filtering logic directly inside the react app because then every single time we wanted to change that filter keyword we would have to redeploy the react application the next thing that we're going to assume here is that although it would be super easy to implement this in the existing comments service that we already have we're going to say that for some reason who knows what it is we want to create a new service so we are going to make a new service to implement this kind of filtering or moderation logic the third little assumption we're going to make here is that in some scenarios you'll see why in a little bit we're going to assume that it may might take a very long time for the new service to actually moderate a comment so at the end of the day we are really just checking to see if a string contains orange but we are going to assume that maybe that is going to take minutes or even hours to actually complete okay so let me show you a mock-up of what i want this app to eventually look like after we make this change so we will imagine that we've got three posts right here and each of them has one comment so each of these comments can be in one of three different states the comment can be successfully moderated so as you see right here in the middle one this string does not contain the word orange or anything like that so we show that comment to the user the other state a comment can be in is awaiting moderation so this is the scenario in which maybe it takes five minutes or an hour to actually run that moderation logic again it's really just a simple string comparison but you'll see why we kind of have to make this assumption from the get go if we are awaiting moderation then we should display something like this to the user something that says this comment is awaiting moderation and then finally the third possible state is the case in which the comment contain the string orange so in that scenario we want to display it to the user this comment was rejected and let them know that there was a comment there but for some reason we are filtering it so from the get go i want to point out that there's kind of one assumption we can probably make here very easily without a doubt based on the mockups you are just looking at we know a hundred percent that the react application needs to be able to tell whether a comment is awaiting moderation rejected or approved right now the react application thinks that a comment has this structure you see right here the react app thinks that comments just have an id and content and that's it so to really tell the react app whether a comment is moderated rejected or approved we're going to add in an additional little flag to every comment and that flag will be a string of approved rejected or pending as you could guess approved means that we've filtered this comment we've made sure that it doesn't contain the string orange or whatever else rejected again as you can probably guess means that well for some reason we don't want this comment displayed to the user so if the status is rejected we want to show that right there and then finally if the comment is pending that means that we're still trying to do that filtering logic and in that scenario we should display this comment as a waiting pending or awaiting moderation over here all right so in this video i've now spent about four minutes telling you about what appears to be a very simple and straightforward feature and i cannot stress that enough this feature looks crazy simple at first glance but as we start to implement this you're going to see that there is some incredible hidden complexity here there's way more going on than you would ever expect and implementing stuff like this turns out is a little bit more challenging than if we were in a very simple monolith style world okay so let's take a pause right here we're going to come back next video we're going to take a look at the current design of our application and talk about how we can change it to implement this feature and we're going to see some issues start to arise along the way so quick pause continue in just a minute now that we've got a better idea of what this feature is we're going to take a look at a couple of different ways of implementing it so let's get to it the first thing i want to do is just give you a very quick review on how our system works right now so present we have the post service comments and query whenever a user submits a comment the comment service is going to emit an event over to the event bus of comment created the eventbus is then going to take this event and send it out automatically to all the different services inside of our app including the comment service like so now at present the post service and comment service although they receive this event they don't actually process it in any way they just say okay here's an event i don't really care the query service however does do some processing the query service is going to take this event and use it to understand this new comment that was just created and it stores it inside of some local data structure so again that's what's going on inside of our system right now i know we just did this and so it's kind of me repeating myself to tell you what's going on but it's really critical for you to understand this flow because the options are about to go through for implementing this new feature are going to be pretty darn complex so with that having been said let's get to it let's take a look at option number one so in option number one i first want you to take a look at this diagram you'll notice that i've added in a new moderation service right here so this is going to be a service that is in charge of taking a look at a comment and deciding whether or not it should be approved or rejected you'll also notice in this diagram i have removed the post service entirely that is not because we're going to delete the post service i just removed it for clarity so you can better understand this diagram this whole idea of comments and moderation and whatnot really doesn't have anything tied to the post service whatsoever okay so in this idea with option number one we're going to have a sort of chain going on where we're going to have the comment service emit an event saying that a comment was just created the moderation service will then emit an event saying that the comment was moderated and then finally the query service will persist that comment so let's take a look at exactly what would occur so once again we're going to have a user submitting a comment to the comment service the comment service will then immediately persist information about that comment as it is doing right now so it'll create some new record with say an id and some content and probably the post id as well but we'll just ignore that for right now because it's not a relevant property as soon as it persists that new po comment the comment service will then continue to emit an event over to the event bus of comment created so it's going to throw this over to the event bus and the event bus in turn is going to send that event out to all of our different services as it is doing right now now with option number one we're going to say that the only service that cares about comment created is going to be the moderation service so we're going to say with option number one query service no longer cares about that event so functionally only the moderation service is going to process comment created the moderation service will take a look at the content of this comment and decide whether or not to approve it or reject it so we'll say that in this case because content does not have the word orange the moderation service will approve this comment so to tell all the other services that this comment has just been approved we'll have the moderation service emit a brand new event that we're going to introduce right now called the comment moderated event the data of this event is going to have all the information about this comment along with the status of the comment as well so in this case we'll say status approved the moderation service will emit this it'll go over to our event bus and once again it'll be sent to all of the different services inside of our app now the only service that probably cares about this event will be the query service the query service will listen for comment moderated it's going to take all the information out of that data property and persist it the query service will now know the id of the comment its content and its status as well like so so now anytime someone makes a follow-up request to the query service they will see okay here is a comment and its status is approved so let's talk about the pros and cons of this approach because there are very much some very big negatives to it the big negative to this approach is the fact that there is some delay between a user submitting a comment and that comment actually being persisted by the query service so i want you to think back to the mockup we were looking at just a moment ago a comment truly has three states it can be approved as it is right here rejected or pending moderation i want you to really think about that pending moderation state right now we are really assuming that this entire approval process by the moderation service is instantaneous in nature but it is entirely possible that maybe at some point down the line we decide that rather than just checking to see if a comment has the word orange in it maybe instead we rely upon a human to moderate these comments a human cannot process comments or moderate them instantaneously it might take a person several seconds minutes hours even days to read a comment and decide whether or not to approve it or reject it so think about what would happen if our moderation service took a long time to run let's go through this scenario again and assume that it's going to take some amount of time for the moderation service to actually process a comment okay so once again a user is going to submit a comment comment service will persist that and the comment service will admit this event and that event is going to be sent on over to the moderation service where it's then going to await actual moderation now at that point in time we're essentially paused in this workflow nothing else is going to happen anytime soon and so in the scenario well that might sound okay but i want you to really think about the user experience what happens to a user as they are actually using our application think about what would happen if a user typed in some comment right here and clicked on submit and then critically refresh the page when a user refreshes the page after submitting a comment they expect to see the new comment listed on here immediately or at least something that says hey your comment is awaiting pen or pending moderation or something similar so with the approach we're discussing right now we're saying that after a user refreshes their page they are not going to immediately see that comment from the query service right away because it's going to take some amount of time for the moderation service to actually process that thing and then tell the query service that there's this new comment so the downside of option number one is that this entire flow could potentially result in a user not seeing the information that they just submitted very very easily now i want you to understand that this idea of a user making a change and then not seeing that immediately reflected that's something that's going to come up all the time in this idea of micro services so this is a very big thing that we're going to discuss quite a bit throughout the course but just in this scenario because of the possibility of the moderation service being ran by an actual human we're kind of exacerbating that problem so i think that option number one has a definite and immediate downside to it so as you can imagine we're not going to go with option number one now let's take a quick pause right here we're then going to take a look at options two and three much more quickly now that we understand some of the general issues that we're going to run into we're now going to take a look at a second option for adding in this moderation service and adding in some events to support it so here's option number two option number two is gonna be very similar to option number one with very one very small difference as a matter of fact option number two is probably what you thought option number one was going to be okay so let's walk through it we're still going to have a user submit a comment to the comment service we are still going to have the comment service emit an event of something like comment created the event bus is still going to send that event off to the moderation service but now we're going to also have it go off to the query service and actually be processed by the query service so this is similar to what is going on inside of our application right now without adding in this moderation feature as soon as the query service sees comment created we're going to have the query service persist some information about that comment and critically it's also going to have a default status of something like pending the query service is going to instantly know about this comment even if it takes some amount of time for the moderation service to process and actually moderate the given comment so now we can imagine that if a user goes over to our application and they enter in a comment right here and hit submit we're going to instantly emit comment created and that event will instantly go over to the queries service and the query service will have this record of the comment so as soon as the user refreshes the page in theory they will see that comment appear right away and because we know its status is pending we can show a nice little and of picture of that thing something like this right here or a nice little something note that says this comment is awaiting moderation now of course we still want to go ahead and moderate this comment so the comment created is still going to go to moderation service and at some point in time in the future maybe seconds months who knows what it will still continue to even emit an event of something like comment moderated this will go over to the query service the query service will see it and update the status of that given comment to approved or rejected or whatever it needs to be so that's option number two this definitely solves the issue of a user submitting a comment and not immediately seeing it appear on the screen but it does also kind of persist an issue that we did not discuss about option number one it's an issue that's present in option number one and option number two as well so let me tell you about what the issue is that is common with one and two i want you to really think about the query service right now and what its job is that query service is all about presentation logic as a matter of fact its name is query service it's about making a query or storing some data and serving that data up very quickly to users so right now it's really joining just two resources just the posts and comments but at some point in time the future we could totally imagine that there might be other resources that it joins together as well such as maybe upvotes down votes images who knows what else this query service might take many different resources and jam them all together and that's what this query service is really all about so quick question for you does it make sense for this presentation service to understand how to process this very precise update to a comment like a comment moderated event does it make sense for the query service to understand how to process an event like this well right now it's kind of easy to say yes because the common moderate event really just means go and find this comment and update its status to approved or rejected or whatever else so processing this event very simple and straightforward in nature it's one line of code more or less but i want you to think about a real-world commenting system think about all the different ways in which a real-world commenting system or real-world comment might be able to be updated a real world comment you might be able to moderate it you might be able to upload it to downvote it you might be able to promote it so maybe a moderator or someone in charge of a website can say this is a really high quality comment i want to boost it up towards the top of all the comments you might be able to make a comment anonymous you might be able to flag it as searchable you might be able to mark it as an advertised comment like a comment that someone paid money to promote in some way each of these different precise updates to a comment has some very precise business logic associated with it to update the definition of that comment so if we continue down this line of saying that our query service is going to be able to process this comment moderated event we're essentially saying that somewhere down the line we might end up in a scenario like this one right here where the query service needs to understand how to handle this multitude of different possible updates that can be made to a comment and you can easily imagine that if there were other services like our query service maybe something to process weekly updates for popular blog posts or maybe something that functions as a recommendation service and if those had to store the idea of what a comment is as well in theory they might also have to handle these events and so we start to get into this scenario where every possible way of changing a comment has to be handled by a ton of different services and as you can imagine yeah this is not even remotely what we want so even though this all works and this is a more or less viable approach for our current application as it stands right now i'm gonna suggest that maybe it's not the best solution so we're gonna take one more pause come back the next video and discuss option number three we were just taking a look at option number two and we eventually said that the issue with this approach is that we are allowing our query service to have a very deep understanding of what this common moderated event is so to solve this we're going to have the comment moderated be instead processed by the comments service let me show you how this is going to work out okay so in this diagram on the left-hand side we've got our comment service and the query service the common service is the service that is ultimately in charge of exactly what a comment is it knows all the very precise business rules all the business logic everything around what a comment is how to update it and how to deal with it in some way and so it makes a lot of sense to have our comment service be the one that is responsible for some very precise very well calibrated way of updating a comment whenever the comment service updates a comment by handling one of these very specialized events we're going to have it emit one single very generic event called simply comment updated whereas all the events on the left-hand side meant that we wanted to update a comment in some very specific way the common updated event says hey there's a new comment right here or a new version of this comment don't worry about what the update was don't worry about trying to interpret it don't worry about trying to run some specialized business logic around it just take these updated attributes and store them if you need them so we're going to follow this pattern throughout all the services we put together the service that is in charge of a basic resource will be in charge of these very specialized updates and anytime those specialized updates occur that service will emit a very generic event update so let's take a look at what this is going to look like for the services we are talking about right now so we're going to once again have a user submit a comment as soon as they do so we're going to have our comment service versus that event and notably you'll notice that it now knows the status of that comment as well the comment service will then continue to emit a comment created event that will go to the event bus it will go off to our moderation service and to the query service as well so we're going to still solve that issue we ran into earlier where the query service didn't really know that a comment was created so that was where we ran into issues with the user submitting a comment and then refreshing the page we're then going to make sure that the moderation service still processes that comment and moderates it in some way so that's going to go off to our event bus and now it's only going to go over to the comments service the common service will be the only thing that knows how to process this very specialized update to what a comment is so in this case we'll change the status from pending to approved then because the comment service just made a change to a comment a very specialized very domain specific change it will then emit a comment updated event so this is a very generic event it just says hey some attributes change don't worry about what changed don't worry about processing this in any way just use these attributes if you care about it at all that will go off to the event bus and the event bus will send it off to the query service and now the query service is going to say oh a comment was updated i don't care how or why it was updated i'm just going to take all the different properties out of that event and i'm going to use those as the basis for my new comment or for updating this comment so we're not going to necessarily just change that status flag we're just going to say take all those attributes and use them to update our existing comment that's it now i know that this might seem a little bit challenging to understand this idea of having kind of a domain specific event and a very generic event but you're going to see many examples of this on the later project we work on as well so don't worry you'll get a lot of experience with this over time so that's what we're going to do inside of our application we are going to use option number three we are going to end up introducing two events one is going to be very specialized in nature that is going to be the comment moderated event it's going to be processed by comment service and then as soon as comment service updates that comment it's going to emit that generic event to say hey this comment was just updated if you care about it great use it in some way now the upside to this approach is that the query service only needs to know about common updated even if we start to add in a billion different ways of exactly how we can precisely update a comment query service doesn't need to know that it just needs to know oh this comment was updated i'm just going to take these attributes and use them okay so now we understand what we're going to do inside of our application we'll take a quick pause right here and start to implement option number three in just a moment in the last video we discussed the pros and cons of option number three so this is the option that we're going to go with there's a lot of changes we need to make in several locations to implement this entire flow so we need to make changes to the common service and the query service we also need to create the moderation service i think we should get started by creating the moderation service for right now it's a good place to get started we're just going to worry about putting together a little bit of boilerplate for the project in this video and in the next video we'll start to add in all these additional events and add in some code to handle them as well so let's get to it we're going to create this new moderation service to get started i'm going to flip back over to my terminal i'm going to open up yet another terminal window which i've already got right here inside my blog project directory and inside there i'll make a new folder called moderation i'll then change into that directory i'm going to maximize this terminal window really quick just you can see this very easily all the other terminal windows are still running i'm just using a hotkey to maximize that one window inside of here i'm going to generate a new package.json file with npm init dash y and then as we've done several times before we're going to install a couple of dependencies so i'm going to get axios express nodemon and in this case we do not need cores because we are not going to have our front end application make any direct request to this moderation service so the course module not required this time around so i'm going to install that stuff and after that's all done there we go i'm going to kind of pop that terminal window back into this tile we're not gonna start up the server just yet let's go and write a little bit of code and we'll come back over and start up that additional service so i'm gonna go to my editor here's the new moderation directory inside there i'll make a new file called index.js and then at the very top let's add in some different require statements so i'm going to get express i'm going to get body parser and i'll get axios i'll then once again create a new express application and wire up the body parser middleware so i'll make sure i call json as a function all right so what does this service really need to do well all this service does is watch for events it's just going to watch for that event we mentioned so comment created whenever we see comment created the moderation service is going to need to emit the comment moderated event so we really just need all we need inside this thing is one route handler just a single route handler for that slash events endpoint that we already set up previously inside of comments query and our post service as well so inside of here we're going to add in app.post for events we'll then take our rec and res like so we'll come back to that route handler in just a moment first let's make sure that our app actually starts listening on some port now at this point in time we've got several different ports in use so as a reminder we've got four thousand for posts four thousand one for comments four thousand two for what is this the query service and we'll use 4003 for moderation so we will do app.listen 4003 and inside of here i'll do a console log listening on 4003 okay before putting together any implementation on this post event hand or post route handler right there let's set up our package.json file with the script and just make sure that we can run this thing successfully at our terminal here's my package.json file i will delete that existing test script and replace it with a start and we'll do nodemon index.js okay that looks pretty good let's go and run this project so i'll go back over my terminal once again i'm going to find that terminal window that's going to be in charge of running our moderation service there it is right there and inside there i'll do npm start okay there we go so we've now got many different services running for our application definitely hey you know this is a course about microservices so yeah we're going to create a lot of services just to understand how to create them all and get them all working together looks like that is running on port 4003 and we've got a good start to this moderation service so let's take a quick pause right here when we come back next video we're going to start to add in some implementation for the events handler right here and make sure that anytime we see an event of type comment created we do some moderation on it and then eventually emit this comment moderated event in turn so quick pause take care of that in just a moment we've now got some scaffold put together for our moderation service so now we need to go around to all three of these different services and make a couple of changes to each ones in some cases we need to tweak an event that already exists and in some cases we need to add in a new event we're going to go through this step by step and kind of follow the actual workflow of a user submitting a comment so let's think about what happens when a user submits a comment remember right now we persist a new comment inside of our common service at present we are just storing that comment's id and content but we probably also want to store that comments status as well whether it is pending moderation approved or rejected so as soon as a user submits a comment we need to make sure that we store in addition to everything else a status of pending to say this comment is still awaiting moderation let's open up our code editor right now we're going to find our common service and make that change right away so i'm going to go back over to my editor i'll find my comment service inside there is my index.js file i'll then go down to where we create a new comment inside this post request handler right here so let's read through this code really quickly and just get a quick reminder of what's going on we generate the random id we get the content of the comment we then get the list of comments that already exist that is associated with the given post and then right here is where we create the actual comment itself so this object that is the comment so we want to add into that object this new status property and by default it should always be pending so inside that object i'll add in a new property of pending or submit status that's better of pending like so okay so that's step one let's go back over to our diagram and figure out what to do next so step number two remember whenever this whenever we create a new comment we then immediately emit a new event and that event is the comment created event that's going to go into our event bus and then get sent over to about the moderation service and the query service remember that we are sending it over to the query service so that the query service can immediately store that comment and the entire idea there was that we want to make sure the query service as soon as possible had a copy of that comment so that if a user refreshed this page after adding a new comment they could immediately see it on the screen as opposed to waiting for some moderation event coming out of the moderation service so we need to open up our query service now and we need to make sure that when we send over that event we take off the status property from the event and save it inside the query service as well we also need to make sure that the event itself also includes that status property so let's go to our comment service first here's where we were just looking at a moment ago this is where we create the comment created event right now it does not reflect the status of the comment so let's add in that status right now in the data property i'll add in status of pending so now when this event goes over to our query service the query service is going to understand okay a comment was created and its status is pending so now we can go and open up our query service we're going to make sure that when receives this event it persists that little extra piece of information that we are now adding in of status pending so i will now go over to my query service here's the index.js file inside there i'll go down to our code where we are handling a comment created event so we're going to pull off that new status property that we just added in and we'll make sure that when we add in this comment to our array of comments we also persist the status flag as well like so okay so that looks good all right so that gets us up to this point in time so now the next we need to do is make sure that we also handle this comment creation inside the moderation service remember that the entire goal here is to actually look at that content property inside that event and see if it has the word orange or not if it has the word orange then we're going to emit comment moderated with a status of rejected otherwise we'll emit common moderated with the status of approved let's take a quick pause right here however and then continue with moderation service in just a moment we now need to open up our moderation service and make sure that we've got some code inside there to handle this comment created event so as soon as we receive that comment we'll then do some checking on the content of the comment and then we're going to attempt to emit comment moderated so let's go ahead and give it a shot back inside my editor i will find the moderation service inside there i'll find the index.js file so we've got this post request handler right here to watch for any request going to our events endpoint so this is where we are going to receive an event from our broker remember that the event itself is going to be contained on the rec.body property because we are receiving all these events as simple post requests for right now so off of that rec.body property we will pull off the events type and the data associated with it we'll then take a look at the type and we'll say if the type is equal to comment created then we want to go through this entire comment moderation thing the first thing we have to do inside of here is decide whether or not to approve or reject the comment to do so we're going to set up a ternary expression so we'll say con status is going to be data.content remember that is the actual content of the comment itself we're going to check to see if that includes the string of orange if it does then we want to assign rejected to status otherwise we'll assign approved like so so now that we've moderated the comment we've got the status right here so now we need to make sure that we emit this comment moderated event so we're going to make a post request over to our event bus just as we've done several times we will make sure that we include the comment along with the new updated status so i will make a post request to http colon slash localhost and remember our eventbus is at 4005 events then we will give this thing a type of comment moderated and for the data we will include the comments id is post id the content itself and the updated status so we will say the id of this comment is data.id the post id is data.postid the status is going to be the status that we just calculated right here and then finally the content will be data.content now one thing i want to point out right here is that i just kind of pulled these properties of id post id and content off the top of my head i just kind of remembered them but i could have very easily forgotten the different properties that were contained inside of an event of type comment created you and i know what is inside of the comment created event because we were just looking at the definition of that event a moment ago when it was emitted from our comment service so here's the comment service here's where we create that event so we can look back at this thing right here and very easily see the different properties that comment created has well i think you can kind of imagine that if we were working on a large system understanding the different properties that were contained inside of any given event can be really challenging definitely without a doubt would be hard to remember off the top of your head so chances are we would want some kind of documentation or something like that to reflect or kind of document what different properties exist inside of every event that exists inside of our application that's just something i want you to keep in your mind for right now because it's going to be very relevant later on okay so now next up we made use of the awake keyword inside of here let's make sure that we mark this function as async and then finally right after the closing curly brace of the if statement we do need to make sure that we eventually send off a response otherwise this request handler is just going to hang okay so this looks good so this gets us caught up to creating this comment moderated event and sending it off to our event bus there is one little thing that we need to make sure we do very quickly right now our event bus is not sending any events to the moderation service just because we created the moderation service after we made the event bus let's make sure that whenever the event bus creates or receives a comment it sends it out to the moderation service as well so back inside of my event bus directory i'll find the index.js file so right here is where we receive all the different events and we just turn right back around and send them off to all these different running services so again 4000 is posts comments query and we just have not added in the moderation one just yet so let's paste one of those lines down and then just make sure we update the port to 4003 which is where our moderation service is running at okay i'll save this file and close it okay so let's take another pause right here when we come back in the next video we're going to make sure that when the event bus comma moderated and sends it over to comments service we're going to make sure that we receive that event inside of common service take a look at the status property update the status of the appropriate comment and then emit this comment updated event as well so still a little bit to do let's take care of that in just a moment in this video we're going to make sure that the common service watches for the event of comment moderated we're going to make sure that we take some information about the comment that was just moderated and update our local definition of that comment so the status should go from pending to either approved or rejected now once again i just want to remind you that understanding the different properties that are inside of each of these events is super critical so i took a little bit of time just to kind of document out exactly what's going on right now with the comment moderated event comment moderated has an id content post id and status and status is going to be either approved or rejected it's going to be emitted from the moderation service and we're going to receive it inside of comments so let's open up comments right now and make sure we receive this event and use that updated status field so i'm going to open up my comments directory i'll find index.js inside of here i'll go down to the post request handler we had already put together to handle incoming events i'm going to pull off the type and data properties once again from rec.body we'll then say if type is equal to comment moderated then we want to handle this thing in some way so the first thing i have to do inside of here is pull out the comment that we already have stored inside of our data structure of common spy post id so we need to find the appropriate comment that we've already stored inside of here and update its status property so let's get the post id we'll just pull all the different properties out of data because we'll probably have to use each of these very shortly so i'll pull out the id post id and status so post id id and status from data we'll then get all of our different comments that are associated with that post id we'll say comments is comments by post id at post id we then need to iterate through this array of comments and find the appropriate comment inside there or the one that we actually want to update they'll say const comment is comments dot find and then we're going to try to find a comment with an id equal to the id from the event so this right here is the comment that we need to update so we'll take that comment and we're going to update its status to be the status that we just pulled out of the event as well and that should be it and we don't have to actually insert this thing back into the comments array or anything like that because the object is the same object in memory it's the same object inside the array we essentially just don't have to insert it back into the array or anything like that so we've now updated status so now the next thing we need to do is tell every other service inside our application that this update just occurred that's going to be where we attempt to emit comment updated so we're going to send out comment updated that's going to go over to our bus and once again we're going to make sure we receive that over inside the query service let's also take a look at some documentation on comment updated just so we really understand the different properties that need to be inside there so common updated needs to have the id of the comment the content the post id and status as well and at this point status should be either approved or rejected so let's put this event together and send it over to our eventbus so let's say await axios.post over to http localhost 4005. the type of the event is going to be comment updated and our data is going to be once again id content post id and the updated status so id we can use the short and syntax here because we've already got id post id status and you know what the comment will be in there as well or it's gonna be content so we'll take the id the updated status the post id that this comment is associated with and the content as well now i'm using the await syntax right here so i'm going to make sure that i mark the enclosing function as async and that should be it so now the last thing we need to do is open up our query service and just make sure that we receive comment updated so another quick pause we'll take care of that in just a moment just one last big step we need to make sure that we open up our query service and watch for the comment updated event whenever we receive that we're going to find the appropriate comment in memory and we're going to update its status to whatever the status is inside the event so let's get to it let's open up our query service back inside my editor i'm going to find my query service open up the index.js file inside there i will find where we handle all the different events that are coming in here i'm going to add on a new if statement and watch for a type of comment updated i'll then pull out the updated id content host id and status from data and we'll once again attempt to find the appropriate comment as a quick reminder we are storing all of our posts inside of an object so we're going to look inside there we're going to find all the comments with the appropriate post and then we need to just as we did a moment ago look through that array of comments and find the comment that we're trying to update so very similar code to what we wrote in the back inside of our comments service just in the last video so i'll say post is going to be post at post id we'll then find the appropriate comment which will be post dot comments dot find we're gonna iterate over every comment and then return comment id equal to the id of the comment that we're trying to update we'll then update that comment so let's say that its status is going to be this new status but remember common update right here is kind of a very generic updater it's saying hey there's some new attributes associated with this comment so chances are we would want to not only update the status here we might have also updated the content of the comment itself as well so we should probably just take that property and use it to update this comment because again we don't really know what change here might have been the status might have been the content who knows we'll just take all these updated properties and assign them to this comment so i'll do comment dot content is content and that should pretty much be it once again we don't have to try to save this or store this back inside the comments array because we are updating an object that already exists inside there okay so we've made many changes so far and i just want to say that chances are some point in time during this process you have said wow this seems crazy this seems insane how do i know what changes are being made those are some really great questions and honestly if you did not get confused during this process of updating these services i would be kind of surprised this really was nasty and i'm gonna be kind of surprised if you made all these changes without making any typos whatsoever i just want you to keep that in mind because this entire process of having to go between these different services add in some events change events that's some really nasty stuff and without doubt if we're gonna start working on any larger application we need some better tools or some better methodology of managing the definition of all these events between these services there's no doubt about it we need a better way of managing all this stuff because the last three videos really have not been fun having said that i think it's time to actually do a test of the application and see if this moderation stuff is actually working now remember we do not actually have anything on the react side of this application yet to actually show something that says hey this comment is uh being approved or rejected or what have you so for right now we're just going to take a look at our network request log inside of chrome and make sure that all these different comments we're creating have the appropriate status attached to them before we do any of that testing however i'm going to go over to my terminal and i'm going to make sure that none of these windows have any errors being displayed inside them if you see any errors that means you likely have a typo somewhere inside of your code now one last thing i want to mention very quickly if you go through this process of testing out this application and you don't get an error from something again i'm kind of going to be surprised because we've made a ton of changes so many places where you can make a typo very very easily all right so let's go over to our browser and at least try to do a test so i'm going to refresh the page i'm going to create a new post so i'll say new post i'll refresh the page i'll add in a new comment hit submit and i'll go back over to my terminal and see what i have when i float back over i don't see any errors anywhere again incredibly likely that you will have an error from somewhere inside of here if you have an error you can either try to hunt it down yourself or just download the completed code that is attached to this lecture and try running that instead so i'm going to go back over now i'm going to refresh the page i see the comment right there if i click on my list of posts or see my yes my list of posts inside the network request log i'll expand that one post that i have take a look at the comments and you'll notice that this comment has been approved okay well that's good let's now try making a comment that should be rejected so i'm going to put in a comment here of orange i will submit it i'm going to refresh i'll click on the posts request again and now i should see a second comment inside of here and this time around it should have a status of rejected because it met our criteria for rejecting a comment it had the word orange inside of it so that means that hey this stuff is working out pretty well the last thing we really need to do is update the react application so the react application should show hey this comment has been rejected if the comment has been rejected and it should show something like this comment is still being moderated if it is still in the pending state so let's take a look at the react application in just a moment and fix it up let's open up our react application and make a little change to this list of comments right here okay so i'm going to find my code editor i'll find the client directory inside there then src and remember all the comments are being rendered inside of comment list here's comment list inside of comment list we iterate over all the different comments and produce an li for each one so we probably want to take a look at the status of every comment and if it is equal to rejected or pending we don't really want to show this li we probably want to show something else or at least change out the content inside of it so let's try putting together just a simple series of if statements i'm going to declare a new variable up here called content let's then say if comment.status is equal to approved then content can be the actual comments content if comment.status is equal to ending we'll have the content be this comment is awaiting moderation and then if comment.status is rejected content can instead be this comment has been rejected and of course we could refactor these three if statements into a switch statement instead if you would like i'll leave that up to you then finally rather than showing comment.content inside of here i'll display whatever the value of content is i'll put in content like so okay let's save this i'm going to flip back over and now you'll notice that the comment that had the word orange inside of it has now been replaced with this comment has been rejected very good i would like to also test out the case in which we do not undergo moderation immediately so this would be the case in which maybe it takes a human intervention say something like 5 minutes 10 minutes 20 minutes to actually come in and moderate any given comment so if we do not get that status updated from pending over to rejected or approved then we should instead see this comment is awaiting moderation to simulate that case we can go back over to our terminal and just shut down the moderation service entirely so i'll go back over to my terminal i'm going to find the window that is running my moderation service i'm going to stop that operation and now i'll go and create a new comment i'll submit it so now that comment is going to be stuck in the pending state there's nothing to actually approve it and move it forward so we can now refresh and we should see this comment is awaiting moderation awesome okay so this looks pretty good but i want to point out that there kind of is a downside to our application right now we just turned off the moderation service if we start up the moderation service again so i'll flip back over my terminal and start it back up well now the moderation service is running but the broker or eventbus tried to send an event over while the moderation service was down so we're now in a scenario where we had a temporary interruption to our moderation service but we lost events in that window and so now our entire application is kind of out of sync so to speak we don't have any way to kind of fast forward and get those missing events back over to our moderation service so maybe that's something we should try to at least think about and figure out some way to fix let's take a pause right here and see if we can't figure out some way of dealing with that in just a moment our application is now working pretty well but at the end of the last video we saw a little issue and this issue might be something that's been kind of nagging in the back of your head throughout this entire course what happens to our application when a service goes down for some period of time we just saw that in the last video with the moderation service going down we created a comment while the moderation service was down and now this comment is going to be forever stuck in the pending state so how do we deal with this let's take a look at a diagram to better understand what the real issue here is okay so in this diagram kind of hard to understand what's going on this is kind of a time sequence diagram so we start off time of our application starting up for the very first time right up here and we have time flowing down or vertically in our application we've got the event bus the green lines throughout all these different services indicate times in which the service was successfully running so we're going to say that our event bus was running the whole time host was running comments and query those are all running for the entire time that our application has been up and running and during that time maybe we've had a couple of events flow out so maybe event one went out to post comments query and moderation successfully because all those services were up at the time that event was sent out but let's imagine that for some period of time indicated by this red line right here maybe the moderation service was down so event two and three might have been emitted from the event bus gone over to our post successfully went to comments and queries successfully but then failed to be delivered over to the moderation service and then maybe some time later moderation service came up and it received event four but events two and three have now been lost to time we don't currently have any way to tell moderation about these events and how they just occurred now this is the scenario in which a service goes down for some little period of time but there's another scenario that you've probably been wondering about again throughout the first half of this course already what happens if we're using this kind of event style approach and we don't bring up or we don't even create a service until maybe sometime in the future so in this diagram let's imagine that we did not initially create our query service and so maybe we've been running posts comments and moderation for days maybe even years and they have tons of data inside them and they've already received tons of events but maybe we only created that query service like one year down the line and so we're creating this query service but it's already missed out on all these different events how do we somehow get query into sync how do we get all the existing posts and comments and results of moderation over to the query service well as usual there's a couple of different ways to handle all these different cases so let's take a look at some possible solutions so here's option number one for option number one we're going to imagine that we've had our post service and common service running for the entire lifetime of our application and then maybe one year into the future we create the query service the query service of course needs to know about all of the posts that exist and all of the comments so we somehow need to get query into sync with everything else one way or option number one would be to use synchronous requests so the instant we launch query maybe we'd have some code inside of the query service to make a direct network request over to posts and say give me a list of all of your posts it could get all the different posts that exist inside the post service via plain network requests once it stored all those posts it could then turn around to the comment service and also make a sync request directly over and say give me all the comments you have and then i could store all those comments with the associated posts now the downside to this approach is pretty clear we are falling back to synchronous requests the real downside here is that we would have to have some code inside of posts and comments just to service or kind of handle this new service that is coming online right now we do not have any real bulk kind of endpoint where we can say give me all the posts for all eternity per se well okay technically our application does right now but you can imagine that in a production application we would probably not have an endpoint that just says give me all posts that exist probably would not implement something like that so if we did not already have some endpoint like that we would have to implement it for both posts and comments now one thing to be clear about after getting all the posts and comments and synchronizing all this data then from that point in time into the future then the query service would start to receive any events that were emitted from posts and comments so eventually query would kind of revert back to our expected behavior but just to get it online and up and running it could make these initial synchronous requests so that's option number one option number two is the one exception to that rule that we discussed way earlier on inside the course around every service having its own private database so with option number two which is kind of similar to option number one we could say that the instant that query came online we could give it direct access to the data store or essentially the database for all the posts that we have and same thing for comments as well so rather than relying upon synchronous network requests directly to the service we could just say you know what query needs all the information on that database let's just give it access to the database now the upside to this is now the query service could run its own queries and figure out all the different data that it needs to get out of the post database and comments database after synchronizing all this data once again the query service could start listening to different events and the downside to this approach is once again we are making sync requests over which means we are going to have to implement some code inside of query to work directly with whatever this database is or this database is let's imagine that maybe the post data store over here was mysql and maybe the comments datastore was mongodb now all of a sudden we need to write some code inside of query to interface with a mysql database and a mongodb database that's a lot of extra code to potentially have to write so on to option number three which as you can guess is what we are going to be doing all right so option number three really falls into the same category that we've gone through several times in the course where i'm gonna tell you this and you're gonna say no way not possible totally inefficient can't do it not gonna happen but once again yes this is how people actually implement micro services people do this not making this stuff up so with option number three we're going to once again say that we are implementing or bringing query online at some point time in the future like right here now in theory query could work if it had access to all the events that had been emitted in the past so the post service for example is going to emit events maybe one two and three and each of these might be a post creation event those are all events that query cares about if query just had access to those events it could work just fine and that's what the strategy is going to rely upon we're going to say that whenever any of our services emits any event whatsoever over to the event bus the event bus will send that event out to all the other services but it's going to do something else at the same time it's going to store that event internally so we can imagine that after event one gets emitted the event bus is going to store that event internally in some kind of data structure probably not in memory probably in some kind of database or something similar because this data store is going to grow to be very very large over time we can then imagine that maybe the post service emits event number two and so we would add that on now eventbus has a record of event one and event two and then finally event three as well and so we can imagine that at that point in time the event bus now knows about event one two and three again i want to repeat these events are still going out to all the other services as they currently are we are just adding in one extra little step here the event bus is going to store all these events now the upside to this approach is that if query comes along or online at some point in time in the future where you can say over to the event bus hey give me access to all the events you have stored all of them just throw them over and i'll decide whether or not i care about them and so we can send over event one and event two and event three and now the query service will be totally up to speed and we can use all the same code that we've probably already written to handle these exact exact events so we don't have to write any extra code the only extra burden we really have here is storing all these events inside of our eventbus store now admittedly this data store could grow to be extremely large over time but as you saw from that calculation we did a little bit ago where we said hey we could pay like 15 a month for a hundred million products well even though it might cost some amount of money it probably costs way less than you might think so that's what we're going to do inside this course we are going to be using option number three we're going to say that whenever we emit even an event we're going to store it with our eventbus so that if we ever bring a service online in the future we can get access to all those events that occurred in the past this also solves the issue with a service going down for some point in time let's imagine i don't have a diagram prepared for this but i'll just improvise really quick so let's imagine that moderation misses out on events two and three but it did receive event one when moderation comes back online right here it can take a look at what the last event was that it received maybe moderation would know that it had received event one and it could say to the event bus hey give me all the events that give me everything that occurred during the time that i was down and so eventbust can say okay you received event one well i'll give you everything since then so we can take event two throw it over to moderation and event three throw it over and now moderation is all caught up it's received to events two and three even though it was down for some period of time so you can see that this approach actually ends up working out pretty well not only does it solve the issue of bringing services online in the future but it also solves this problem of events possibly being missed while a service is experiencing some amount of downtime alright so let's take a pause right here i apologize for the long video we'll continue in just a moment in this video we're going to try implementing option number three inside of our application so we're going to take our query service down we're then going to try to create some number of posts and some number of comments as well we're then going to launch our query service and we're going to try to make sure that the query service can reach out to the event bus and tell it give me all the events that have occurred up to this point in time now i want to remind you that we are putting together a homegrown version of an event bus so there are real open source projects very production quality in nature that are going to do a lot of what we were discussing right here in a much more automated and well-intentioned fashion that within what we are doing currently so all you and i are doing are trying to get a sense of what is going on here you should not use this code that we're about to write in a production environment i just want you to have an idea of what is going on behind the scenes the first thing we're going to do is to make sure that whenever our event bus receives an event we are going to store it inside of an array we're then going to add in a new endpoint to our eventbus an endpoint that can allow us to retrieve all the events that have ever occurred we'll then make sure that whenever we launch the query service we'll have it reach out to the event bus and request all the events that have occurred and we'll make sure that the query service attempts to process all that data so let's get to it the first thing we're going to do is open up our event bus and make sure that we store all the different events that we collect over time so back inside my editor i'll find the event bus implementation so here's index.js right above our post request handler where we deal with incoming events i'm going to simply create a new variable called events and i'll have it be an array like so so we're going to take every single incoming event and throw it into this array then inside of our post request handler we'll take a look at the event that we receive and we will push it into that array so we'll do it in the events dot push event so now critically the most recent event is going to be at the end of this array the first event we receive will be at the very front of the array we're then going to create another endpoint on this event bus to retrieve all the events that have ever occurred so after that existing post request handler i'll put in an app.get for events with rec and res and then if anyone ever makes a request to slash events right here we will simply respond with that big list of events now again want to repeat what i said just two minutes ago real implementations of event buses are way more complex than what we have right here this is just to give you a sense of this approach of trying to synchronize services after they've been out of service down not even in existence or whatever else okay so now let's go over to our query service so i'm going to close that file i'll go over to the query service and open up the index.js file the first thing we're going to do inside of here is extract some of the logic that we have inside of our post events route handler right now inside of here we've got a lot of code that knows exactly how to deal with or handle any given event that's all localized directly inside this post request handler right now but we're going to need to very quickly process events in some different locations inside this file long story short we're going to take all these if statements and extract them into a separate helper function so inside this post events i'm going to find the first if statement i'm going to go down to the bottom if statement right here i'm going to cut all that and so i'm just left with type data a console log and the send right there i'm then going to define a new function right underneath posts and i'll call it handle event and then i'm going to paste all the stuff that we just cut inside of that function now this function is going to need access to the data of the event and the type as well so i'm going to assume that we're going to provide the type and the data as arguments to handle event then finally back inside of our post request handler here is right here we're going to delete that console log which we don't really need anymore and i'll replace it with a call to handle event and i will pass in the type and data so all we just did is extract all that event handling data into a reusable function okay so now last thing we need to do whenever our query service comes online and it starts listening on port 4002 right after that would probably be a pretty good time to make a request over to our event bus and try to get a listing of all the different events that have been emitted up to this point in time so right after we do that console log i'm going to add in and await axios dot get we're going to reach out to http colon slash local host 4005 slash events so that's going to give us all the events that have occurred over time remember we're making a get request right here so we'll assign that to some res variable i'm going to make sure i also mark the enclosing function as async and then finally we're going to iterate through all the events that have occurred using a simple 4 of loop we can also do a 4 each whatever you want to do but in this case i'll just use a four of very simple straightforward so i'll say let event of res dot data remember whenever we use axios the response or the actual data we get back is available on the data property of this response then inside of here maybe first we could do a quick console log and say something like processing event and then event.type and then right after that we'll go ahead and actually handle the event so handle event we'll put in the event type and the event data and that should be it okay so let's save this this is kind of a long video so take a quick pause right here and then test it out in just a moment in the last video we put together some sync code inside of our query before we test this out we did try to make use of axios in here but unfortunately our query service does not yet have axios installed we haven't even required it into this index.js file so i'm going to go up to the very top of this file i'm going to require in axios i'll save this i'll then go back over to my terminal i'm going to find the terminal window that is running my query service i'm going to stop that thing i'll install axios really quickly and then i'll start that server back up okay so that looks good so now we need to make sure that we can actually test this out effectively so i'm going to just go ahead and stop that server even though we just started it up so now we do not have any access to query it just doesn't exist but hopefully we can try to create some posts comments and whatever else those events will be cached or stored by our event bus and then as soon as we launch query hopefully queries should be resynced and get all the different events that it has missed over time so let's try this out making sure that the query service is not running i'm going to go over to my browser i'm going to refresh the page you'll notice i've got an error inside of my console right now and that is to be expected because the query service does not exist right now it's not running at all but i should be able to create a post so i'll go ahead and create a post something like new post and submit now in theory this post has been created and we've gone through that entire process of storing it on the post service and so on if i refresh right now i get another error again because the query service doesn't exist so now let's go back over to our terminal we'll go ahead and launch the query service and as soon as we do so it should reach out to our event bus you'll notice there are some errors here you could ignore them it should reach out to our event bus and try to receive all the different events that it has missed so i'm going to start up the query service and you'll notice right away it's processed in the event of post created that's the event that it had missed so if i now go back over to the browser i can refresh and there's my post now the benefit to this approach if i kill my query service once again so now it's dead again now i can start to maybe create some comments i can say comment number one i can create a comment number two i can create even an invalid comment something with the word orange in it something that's getting get rejected now if i refresh again once again i don't see anything because the query service is down and the query service has completely missed all these different events it hasn't seen any of the comment created any of the comment moderated or the common updated events so now let's relaunch query and instantly it's going to process all those different events that it just missed out on so now if i go back over the browser i can refresh looks like the cdn is taking just a moment chances are it's gonna refresh way faster for you there we go and now we can see that the query service is online and a hundred percent up to date we've got our post we've got those comments and the comment that was rejected as well all right so you gotta admit that's pretty neat so this 100 really deals with this issue of a service being brought online at some point in time in the future or possibly the case in which a service goes down for some very small period of time and misses out on a couple event events we're going to use this strategy very heavily as we start to work on our next application now if you see some issues with this approach and there are some problems inside of here without a doubt don't sweat it there are corner cases and we are going to cover these corner cases particularly around the possibility of having like persistent data right now none of our data is persistent we store it inside of some in-memory data structure that's lost instantly whenever a service goes down but if we were using a database where we were storing these posts and comments inside of some database would say the query service you might be thinking hey we'll get into some trouble here if we try to run the same event or process the same event twice again if you're thinking that don't sweat it there are solutions to it that we're going to implement in our next application okay so this entire idea of syncing events looks like it's pretty handy so pause right here continue in just a [Music] minute
Info
Channel: Improve Your Skills
Views: 13,058
Rating: 4.8206897 out of 5
Keywords: Be a Learner, Learn, microservices with node js and react, microservices, microservices mobile app, microservices in mobile app development, app maker, app development, what is a microservice, microservices architecture example, microservices advantages, microservices vs api, microservices java, microservice architecture diagram, udemy, github, node js, react, stephen grider, Mini Microservices App | Microservices With Node JS And React, Mini Microservices App
Id: 0rVWXQi1so4
Channel Id: undefined
Length: 212min 49sec (12769 seconds)
Published: Sun Jan 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.