Nest.js Crash Course #3 - Controllers

Net Ninja · Beginner ·🔧 Backend Engineering ·3y ago

Key Takeaways

This video series covers the basics of Nest.js, a Node.js framework for building server-side applications, focusing on controllers to handle API routes and using decorators to define HTTP methods and parse parameters from requests.

Full Transcript

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

Original Description

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 - https://www.youtube.com/channel/UCDpd-qEwAI9wglx4tsEBAtw 🐱‍💻 Nest.js docs - https://docs.nestjs.com/ 🐱‍💻 VS Code - https://code.visualstudio.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video series teaches the basics of Nest.js, focusing on controllers and API routing, and provides hands-on experience with building a ninja-themed API. By the end of this series, viewers will be able to build a Nest.js application and create controllers to handle API routes.

Key Takeaways
  1. Define a class with the controller decorator
  2. Add a path to the controller
  3. Define methods for each route using decorators
  4. Use the param decorator to parse out parameters from the request
  5. Use the Query decorator to parse query parameters from URL
  6. Use the body decorator to parse request body
  7. Create a DTO to define the shape of the request body
  8. Forward request to services or providers
💡 Controllers in Nest.js are used to handle API routes and should be lean, with minimal logic, and forward requests to services or providers for underlying logic.

Related Reads

Up next
/dev/push: An Open Vercel Alternative to Ship Your Apps Quickly
Ian Wootten
Watch →