Nest.js Crash Course #3 – Controllers

In this series you’ll learn how to make a ninja-themed API with Nest.js, which is a node.js framework for making server side applications.

⭐ Thanks to Marius for making this course. Subscribe to his channel here –

?‍? Nest.js docs –
?‍? VS Code –

In this video we're going to go over Controllers in sjs in the previous video We talked about creating you know maybe A ninjas API that allows you to manage An Army of Ninjas so in order to have an API right you probably will have some Kind of routes I defined so let's write A couple comments here imagine that Perhaps you want to have a get slash Ninjas right which returns you maybe a Collection of ninjas Typically in rest you might also have a Route that allows you to get a single Ninja where you provide a an ID for that Ninja on the path of your request you Also want to be able to create ninjas Right so typically in breast it'll Probably be the same endpoint as this Except we're using post HTTP post and Then similarly you might have a put or a Patch on the slash ID path to update That record and finally you might have a Delete also taking in a ID parameter so That you know you can delete ninjas you Know maybe you're trying to remove them From the battlefield so at a high level Controllers are in charge of defining Exactly this right it defines what are The paths what are the the HTTP methods For each of these paths so you can see That in this controller we have this String ninjas that basically says that Everything within this controller is Going to have that prefix X right so

That's one of the things that we want in Our paths is that ultimately each and Every one of them has a prefix ninjas so In order to create these routes again You need a class that is annotated with The controller decorator and then Optionally some kind of path that you Provided in here and then within your Controller you can Define methods for Each one of your routes So for example if we were trying to do Get ninjas let's define a method for That let's start with just returning an Empty array we'll update this later in The series and right now this is just a Method for a class Nest doesn't yet know That this is meant to represent a route The way we do that is to include another Decorator get From this JS common and that basically Provides Nest an idea that hey this Method is to create an HTTP get on slash Ninjas now you might be wondering what About other paths that are Beyond just Ninjas so if we were to implement get One ninja and this is also a get but Notice that in the definition of get you Can provide an optional path To append to the controller's path so if We did ID like this that pretty much defines This route now let's go ahead and test This real quick to make sure it's Working our application is already

Running if you're following along and Your application is not running make Sure to run npm run start Dev But we're back on thunderclient Localhost 3000 if we go to slash ninjas HTTP get and hit send we're going to get Back that array and if we were to pass Any ID right now We're gonna get back that object Right and as an example the next thing We need to implement is to post on slash Ninjas if we try to request that right Now without it being defined we should Expect a 404 not found because it Doesn't know where to bring that to so Just to save you a little bit of time I Went ahead and implemented the rest of That boilerplate for you but it's all The same idea notice that we got methods For each of these routes there's a Dedicated decorator for post put and Delete and other ones that you might Assume like you know patch And then again remember to provide the Parameters inside the decorators here And that's really routing in a nutshell Now of course there's a couple other Parts here that we need to add in for Example uh how do we get how do we parse Out this ID from the request so that our Logic down here can work with it so That's where the param decorator comes Into play you usually provide this Within the method definition here and

You can see that the parameter decorator Can also expect a string in our case We're trying to parse this ID out of the URL so we're going to say ID here and Then just for typescript we're going to Say that this is a string so what Effectively happens here is that you Know behind the scenes Nest is parsing Out the URL and auto injects it into our Method here when it gets invoked so if We just print out perhaps the ID and Response here If we go back to our get ninjas slash Some kind of ID hit send you'll see that The ID is the thing that we passed in Right so you can probably imagine that We also need the same thing in our other Routes down here All right so that's URL params now the URL can also include a query for some of These right so for example uh for ninjas Maybe you want to be able to filter uh The type of ninja that you're getting Back right so your url might look Something like this with a question mark Type to do fast you know maybe you have I don't know a fast ninja and a slow Ninja right so same thing we need a way To be able to parse that out of the URL And a lot of it is very similar to what We're doing here except instead of param We're going to use Query and same thing You can provide the string here that You're trying to parse out

Uh say this is a string And again just to kind of mock it out Let's provide the type that we inputted Into the response so if we did then just Type equals fast we should expect a Response of you know it's got fast in There so I hope you see where we're Going with this later on we are going to Do some kind of filtering on a real Collection but let's move on and learn Other things about the controller so Typically with a post request like this Right you could think of it as you're Creating a a new Ninja for your army we Need to be able to also parse the Request body and again it's all the same Pattern as you might imagine there is a Body decorator That allows you to parse out that Request body so maybe let's call this Create ninja dto now it would be nice if We had typing for this right so that we Can kind of figure out what's the shape Of this object so what you typically Would want to do and notice that in our Generated users research earlier it kind Of did it for us there's a TTL folder Here where there's a create user dto and An update user dto we're going to do Something similar let's go ahead and Actually just copy this Into our ninjas folder so that it also Has its own detail folder and then let's Rename these two

Uh create ninja dto and update Ninja Dto and let's also update the class Theme Here To create ninja detail same thing for Update All right and you can see that this Update dto just extends the create ninja Detail we're going to use this later in Our update Route but let's focus on the Create ninja dto first right so imagine That maybe as you're creating Ninjas for Your army maybe you want to have a name For each of those Ninjas and we can add more fields to This later but for now we can take this And add a typing to our create ninja dto In here make sure to import that and Just to make sure that you know this is Working correctly let's go ahead and Just create a mock created ninja here Where the name is the same one that's Passed through I had a dto right so if you go to our Thunderclient let's go to post ninjas Where we need to provide a request body With a name field give a name here send And it's going to give us back an object With the same name Right so that just proves that we're Able to parse this out and later we're Going to work with that and add Validation you know if you keep watching The series we'll come back to this ninja Dto to kind of improve it and add

Validation and all of other fun stuff Now to wrap up our controller here Similarly for an update Route besides The uh the ID parameter we also need its Own request body there that provides the Updates so very similarly we're going to Add body here with update Ninja ETO and then we can provide our update Ninja dto type right and same thing We'll return the name now our controller Right now is really not doing much but You can see that it's its primary Responsibility in sjs is to really just Define the routes it's uh in charge of Parsing things out of the request from The URL from the request body and then Ultimately for forwarding that down to Services or providers which will do a Lot of the underlying logic that we want To actually happen so think of Controllers as very lean routers they Really don't do much other logic besides What we've done here alright so that Pretty much wraps up our initial Controller here in the next video we're Going to talk about providers and Dependency injection so that you know we Can start using those services within These controllers that we can start Actually implementing these crud Endpoints to behave as we expect them to

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *