Adding Controllers | Creating a REST API with Node.js
Video Title: Adding Controllers | Creating a REST API with Node.js
Welcome back to this series where we build a restful service with noches we added a lot of functionality we added authentication and I’d call our service finished right now you can always tweak it can always improve it and definitely share any tweaks additions or alternatives you created in the comment
Section in this video I wanna have a look at one improvement it certainly makes sense so let’s dive right into it and see which improvement that is as I mentioned you can’t do a lot of things but one thing I want to bring your attention to it are our route files
We have a look at them you see they’re relatively big now obviously not super big everything’s fine we can leave them as they are but we could also argue that in the route files we in the end just want you distribute our requests we want
To tell them where to go right we want to tell our get request targeted at just slash products to go somewhere where it is code runs that code itself doesn’t necessarily be have to be a part of that routes file so therefore I will add a
New folder in the API folder and I’ll name it controllers and therefore we will get closer to an MVC approach though the via the view is of course missing because it’s a restful service we don’t render a view but at least on the back end we have our models we
Created these with Mongoose and then we have our controllers where the actual logic should live and that will allow us to trade cleaner route files so now I could create our orders dot J’s file here too and the idea is simple I want to export a couple of functions here in
The ordered J’s files then the end chests are the same functions as I passed to my router here so for example for getting all orders I can grab that function which I passed to my get method here like this and cut it out of there
Out of my get route and go to the orders J’s file and there I now want to export it now to export it I’ll add exports and then a name of which under which I want to export this and here I’ll name it order get orders get all maybe and
Assign this function as a value and that’s actually almost all done there’s one thing of course I need to get access to the order here so I will take the order import from Mongoose and copy that and put it into my orders controller here like this so that I can still use
My order here with that added here I can go back to my route to the orders jazz route and import my controller so I can import the orders controller from and now let’s go up and then to the controllers folder and the orders file and now I can simply assign orders
Controller that orders get all here as a function I don’t execute it don’t pass parenthesis just a reference to the function telling DD Express basically that it should execute this function this is pointing to whenever we receive an incoming request here and yeah yeah I got an error because I worked too much
On the front end it’s of course Const orders ik controller equals require we should use the nodejs import syntax so let me save this and let me also make sure that check off here is of course incorrect in the orders controller that should stay in the route foul this still
Is my extra check I’m executing here in the middle where now if that if I save this it should work and now if I send a request to orders again I get off failed so if I do quickly authenticate and I grab that token here and now use that
New token instead of the old one from the last recording session I now sent this this still work so we’re still able to get all the orders now for the controller keep in mind what I accidentally messed up but good thing I guess that the check off middleware
Stays in the routes file you could of course also rule change your controller to also kind of expose that but I guess adding the middleware directly here makes sense so you can easily see okay any requests reaching that route goes through that middleware and then ultimately is handled by this function
Here in my orders controller and this is how we well can set this up and now we got a very clear route file at least once we did this for all the routes so now I will grab the next one here this is the route for
Creating a new order so in the orders J’s file in the controller file I will now add this and export this as a function to so I named this one orders get all here a limit orders create order maybe assign this function as a value the one I just grabbed from the routes
File there I also use the product model and not just your order model so I will import that you I will import product wire require models product to get access to this too and now in your orders J’s file I just want you add this here orders controller and then its
Orders create order and now if we test isn’t postman and I also will add my authorization header here I’ll copy the one I just used on the get request here and I’ll use this old product ID here which helpfully works if I now hit Send
Here I get product not found so let me quickly grab all my products yeah all failed thanks very much so let’s add the off header here quickly to change this to a get request get all the products let me now grab this product ID end now
Try again by creating an order for this ID I get an error we have a look at the log mongoose is not to find yeah makes sense I guess because here I’m creating a new object ID by accessing Mongoose types so we should also add this import
Which we have a new routes file so let’s also import Mongoose here in our controller we need it here too now if I save disincentives again now we stored it order so now that is working too and now to continue in our orders J’s file here in the routes folder we got our
Route for getting a single order so I’ll cut this code here to go to the orders controller and add here so I’ll now have exports orders get order and assign this as a value and we got all the imports we need for that so
All I now need to do is go to the routes file and assign orders controller and now orders get order if I now save this and we try this out – in postman now I want to get a single order why not the order we just created so let’s copy the
ID from that order and attach it here orders IDs and I get requests to it now we get that single order so that’s working – and finally for deleting of course I want to do the same grab all that code cabott and go to the orders control controller exports orders delete
Order and assign that value here again I got everything I need I got the order import already so now in the orders file in the routes folder I’ll simply access orders controller and then there it’s the delete order and with that if we save that and we tried try this too
So we delete this order now we got that deleted response and now we get a very clean route file obviously we now got our crowded orders controller but that is where the logic should live and it makes it easier for us to understand the flow of our application of the incoming
Requests if we got a leaner route file at least it is an alternative or an option you should think about it also means that we can now remove all these imports like the order and product model of course and Mongoose and I only need Express router my mail aware which I
Still apply here and of course the controller and now we can do the same for products and users so I can add the products dot J’s file in the controllers folder and then the product J’s file here in the route folder I will still he’ll still leave the team altars set up
Here and the file filter and everything here which is related that malt urmila where we could also outsource this into its own file if we wanted but I’ll leave it here and I’ll now just grab that code for a getting a single product and getting all products
Excuse me and put it into my products chairs fall there I’ll also have exports products get all and assign this value and now here we well have the logic to get all the products I there for all the needs that import from the product model
In the products J’s file now in the new controller file so that we have access to that model and let’s now try this out first of all of course let’s go back to the products file and reroutes folder and let’s import so let’s import our new products controller with the required
Syntax by going to the controllers folder and then importing that products file and now we can use that product controller here on the get route so here the products controller with the products get all method we’re pointing to you and now if we save this and we go
Back to postman and send a get request to slash products we get all the product so this is working fine now the same of course for posting a new product I’ll leave to check off and team ultimately we’re in that routing file I’ll not put that into the controller I’ll just grab
This function here cut it out of the route file and create a new function which I export in my products controller file I’ll name this products create product here like this in there we now also again need to import Mongoose to create that ID so that is an import I’ll
Get from my products J’s file and add to the products just follow the controllers folder like this and now we should be able to create a new product let’s try this out let me quickly send a new post request here let’s add an authorization header to this post request and in the
Body should be form data let’s pick a fitting file and let’s and make sense that we get not found I should maybe also hook this up here in the product shares for the routes folder there for posting I forgot to use my new controller function so on the products controller
I want to forward requests to that function the create product function now if we save that and go back and try this same request again it works so now we successfully added that product now if we’re getting a single product obviously that’s also something I wanna do
So let me cut this code here and go to the products J’s file here and now it’s exports products get product like this now back in the products file in the routing folder I’ll use my products controller and use that get product function we just created and now if I
Try to get a single product like the one we just created so let me get this ID and set a get request to slash product slash that ID then it still works so that’s fine now for patching a product I’ll of course do the same copy or cut
The code from the route file add a new function in the controller so exports products update product would be a fitting name in my opinion like this assign that function we should have all the imports we need now I’m point to that function in the routing foul so products controller update is the
Function I want to call and now we have this too now let’s also add our delete function to our controller by exporting products delete and assigning this function here we should all have all the experts we need here – and now let’s of course also point to that newly created
Function in the controller for this route – and now we got a very clean and lean products routes file – and then I said you could outsource all the Malter related code here if you wanted to now finally let’s create a new user JS file in the controllers folder where we manage all
The logic for our user j/s routes so I’ll copy or cut the code here for trading a new user and export it in the user J’s file here user signup let’s refer to this code I just cut from the user J’s file now we need p-trap we need
Mongoose and I need to use her model I will actually copy all these imports because I will eventually need them here in my controller file so I’ll add them there now we should have everything we need in the user J’s file I now need to import my controller so Const user
Controller is require and now let’s go to the controller controls folder and import the user file and then here for signing up I can use my user controller and use the user signup method point to it the method I just created and with that if we test this and we try to
Create a new user so for that don’t forget we need to pass an email and a password field so if we try this out and I turned this into a post request to slash user slash signup can remove the content EDD authorization header set content to application Jason though to a
Raw data here which is Jason and then simply pass on email which could be test 55 at test comm and a password whoops like this password she could be test her and now hit Send I get not found because that should be user not users now I get user created so
This works and with that let’s also put the login functionality into the controller so let’s cut this and go back to the controller and exports user login and assign this to the function I just cut and then the user J’s file in the routes folder I’ll then point to this
New controller function so to the user login function and now if we try this out here and send the post request to user login with that same data I get off successful and a token so this is working to you and now finally let’s wrap that code for deleting a user let’s
Put that into our controller to user delete it’s pointing to that function we need to use remodel which we already are importing here and then the user route I can then also point to user controller whoops not delete user delete like this and now if we try to delete a user and
We therefore quickly grab the idea of the user we just created and I then send a delete request user slash with that ID and I had sent and I turn this into a valid ID maybe then I get user deleted so this also works now with that I just
Recognized one tiny thing we should also add the check off middleware in front of delete to prevent that and authenticated users to lead our users so that would make sense so let me quickly add check off here which I require from my middleware folder check off like this
And let’s simply add it here check off and now if I try this again and I first of all try to create a new user so I post a new user here whoops user signup of course someone to create a new one now if I grab that idea
Of the new user and I go back to my delete request and I try to delete that ID I get all failed and I would first of all have to log in and delete it and even then any user could delete an average user you would have to add some
Kind of authorization where you manage a different table in Mongoose where you assign roles or permissions to your users that is something you can simply add to this application but at least we got this basic protection against enough indicated users the cool thing of that video however will ask that we create
These controllers and we did and now we have very lean routing files and of course we can now clean these routing files up remove user cattle UTEP Mongoose from the user J’s file here only leave the controller and the middleware and of course Express and router and for products it’s the same we
No longer needs the import to the product model there so we can remove that we can remove the Mongoose import we need Malter still and we need check off still though and for orders we already clean this up so now this is all cleaned up we got leaner route files now
We’re using controllers to manage our logic there and to only manage routing and the route fault which I guess makes sense and now it’s up to you you can enhance this application you can try to add authorization so try to manage different roles for different users you
Can of course add other routes our functionalities you can exchange mongoose with my sequel database if you want lots of stuff there you can dive into I hope you enjoyed this series and you’ll learn a lot about how you can build a restful service with note and Express
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Looks unnecessary, isn't it better if you make a controller for error, success, failed response instead rather than splitting response function into different folder 🤨
Now I fully understand about the JWT. thank you vry much
thanks
Can anyone explain me if I'm a user, then logically I shouldn't be allowed to check all the orders available? How to fix this issue?
Thanks for sharing such quality content on NodeJS, helped a lot!
understood.. Thanks man.
Awesome, Max. I followed through each of these video series and it works! Thank you so much for sharing them.
thanks a lot man. I have been struggling with this user authentication for a while. but you saved me. those youtubers were always missing some detail in their videos. But you covered all the Informations that I need to learn. keep going.
thanks a lot bro was such a great tutorial, i watched a lot of tutorials but this one did put me on the right path to create great backend API's
Literally, this is the first series i have ever reached the end of. Thank you so much. You are awesome🥳🥳🥳
Thank you soooo much for this. This is the best tutorial I've ever had.
Thank you so much, 10K time thanks.
first ever youtube series i completed, thankyou max learned a lot from this.
I think a good thing to add is comparing the userId in the token with the userId in the route, so that a user can only delete or update themselves, but not any other user
Thank you so much Max. Things have been so diligently explained :))
We have controllers, models…So what is "VIEW" in this MVC sir?
Thanks for your expert lessons. Totally loved it.
This is what I'm looking for, the controller. Because the functions are not looking good if I put it directly to the routes. Controllers should be handling the logic functionality.
Is this relevant in 2021 What I need to change
This series was amazing, thank you so much 🙂
Very good series, even though I had to troubleshoot quite a bit to get everything working it was simply going back and checking what I missed. Great content Max, thanks !
You try to give the video more brightness it will be great if you do