Develop RESTful Web Services using NestJS and MongoDB | Vinod Kumar | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Develop RESTful Web Services using NestJS and MongoDB

teacher avatar Vinod Kumar, Software trainer, developer & consultant

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

42 Lessons (4h 44m)
    • 1. Course intro(SkillShare)

      1:28
    • 2. Introduction to RESTful services

      2:54
    • 3. Introduction to Nest JS

      2:24
    • 4. Software setup

      6:49
    • 5. Creating our first Nest JS Application

      15:40
    • 6. Handling HTTP GET requests

      13:00
    • 7. Handling HTTP POST requests

      9:45
    • 8. Handling HTTP PUT requests

      7:08
    • 9. Partial update using HTTP PATCH request

      3:47
    • 10. Handling HTTP DELETE requests

      4:09
    • 11. Overview of providers

      4:07
    • 12. Creating the ContactService injectable

      16:34
    • 13. POST /contacts controller and service

      10:58
    • 14. GET /contacts controller and service

      1:48
    • 15. GET /contacts/:id controller and service

      3:39
    • 16. ASSIGNMENT Implement PUT, PATCH and DELETE handlers

      1:19
    • 17. ASSIGNMENT SOLUTION

      10:04
    • 18. Overview of Nest middlewares

      1:56
    • 19. Class as middleware

      12:10
    • 20. Function based and third party middlewares

      9:56
    • 21. Standard exceptions

      6:19
    • 22. Custom exceptions

      6:53
    • 23. Exception filters

      10:43
    • 24. Overview of pipes and using built in pipes

      14:14
    • 25. Creating and using custom pipes

      18:01
    • 26. Using ValidationPipe and class validator library

      7:56
    • 27. A quick intro to Mongodb

      2:12
    • 28. Downloading and setting up Mongodb server on our local machine

      6:33
    • 29. Getting familiar with basic Mongodb shell commands

      7:08
    • 30. Creating a new Nest project with required dependencies

      2:27
    • 31. Creating contacts module, controller and service

      3:46
    • 32. Contact model and schema

      5:04
    • 33. Adding a new contact via POST request

      11:03
    • 34. Get all contacts via GET request with pagination

      10:55
    • 35. Fetch a contact by id via GET request

      6:28
    • 36. Update a document via PUT request

      7:54
    • 37. Delete a document via DELETE request

      4:23
    • 38. Partial update of a document via PATCH request

      5:13
    • 39. Connecting our app to Mongodb Atlas (Cloud)

      7:27
    • 40. Creating an account with Heroku

      1:59
    • 41. Installing Heroku CLI

      2:38
    • 42. Deploying our application to Heroku

      8:48
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

119

Students

1

Project

About This Class

Learn to build a feature rich production ready RESTful web services using NestJS and MongoDB.

Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!

Nest provides a level of abstraction above these common Node.js frameworks (Express/Fastify), but also exposes their APIs directly to the developer. This allows developers the freedom to use the myriad of third-party modules which are available for the underlying platform.

In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications. This has given rise to awesome projects like Angular, React and Vue, which improve developer productivity and enable the creation of fast, testable, and extensible frontend applications. However, while plenty of superb libraries, helpers, and tools exist for Node (and server-side JavaScript), none of them effectively solve the main problem of - Architecture.

Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications. The architecture is heavily inspired by Angular.

In this course I am going to guide you through the process of planning, developing and deploying a fully-featured RESTful web service using TypeScript+NestJS on Node platform.

Meet Your Teacher

Teacher Profile Image

Vinod Kumar

Software trainer, developer & consultant

Teacher

Hi, my name is Vinod, and I am a software trainer, consultant and freelance developer. I am also the creator some of the highest rated courses on Udemy and SkillShare. In my professional teaching career (spanning over 23 years), I have trained hundreds of thousands of software engineers. Teaching is not only my profession, but also a passion. Creating online courses gives me the opportunity to reach and help students across the world.

See full profile

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Course intro(SkillShare): welcome to the develop. Rest full Web services using messages and Mongolia because where you will learn how to develop a production. Really modern JavaScript rest full application using the next J Scream work. Knishes is currently the fastest growing technology, with over 300,000 weekly downloads on NPM. My name is we know on I'm a professional, softer trainer with over 23 years of teaching experience. By the end of this course, you will know how to develop and deploy a fully featured less a P A that persist later in Mongolia. You will learn how to develop modular high performing on scalable applications with best industry standards. We start with the very basics off rest full Web services next year's and then go on to learn providers, pipes, error handling, connecting to Mongo DB database and even deploying our application. Teoh really correction there were so that it is accessible publicly. This course is meant for anyone with a basic knowledge of JavaScript. Knowledge of databases may help, but absolutely not necessary 2. Introduction to RESTful services: arrested and I couldn't for representational state transfer. At first, it might sound a bit complicated, but if you read it from rewards, it reads more or less like transferring state in different representations that don't stayed here refers to the state off a collection off objects known as a resource. In general, a resource has some information, which is nothing but stayed. Often object, and the client I'm server may exchange are transferred the same in different formats are up with conditions. For example, a mobile application may request this Alberto provide state off resource in XML format, while another Web obligation may request the silver for the same state. In Jason Former, both sour unclaimed can bargain for representations off state from each other, which is stormed. US. Content negotiation This type of communication between the Clintons are work is carried out , using the Web as transport platform on leverage that it's TDB protocol features. When working with the rest will services, these points must be kept in mind. Resource is access to a are A. You are our uniform resource identifier. For example, the you're right slash ap slash contacts represent a collection off contacts in an address book The Ex TDP request matters such as Get post foot, delete our patch actors. Words are actions to be performed on a resource. For example, sending a get request for slash AP slash contact should get all the contacts in some format , maybe XML or Jason, but sending a post request to the same your I slash ap slash contact with the request Body should create a new state in the resource on the SIRO site, but its GDP requested are except is used by the client to negotiate with the Sarwar for a specific type of representation. For example, a value off applications slash Jason for this header instructs that Sarwar toe send it Jason The presentation of the state while applications slash example tells this Alberto send an XML copy of the same similarly textile slash plane may bring a textural representation off the same resource as well. The ex TDP requested Our content type is used by the client toe. Indicate what representation off data being sent from the plane to the server while making a post. Put our patch requests in these requests. The data is center. The request body, commonly known as payload with this basic idea off rest full servicers in the next Lecter. Let's have a look at what Ness just is all about. 3. Introduction to Nest JS: next year's are simply called NEST is an open source and mighty license framework for building efficient, scalable nor Jace applications that run on the starboard side. It is built by Kamil Mr Vick and uses progressive JavaScript. It is built with on fully supports, type tripped and combines the elements off object oriented programming. Functional programming on functional reactive programming under the Hood Nest makes you self robust. It's TDP Sarwer Frameworks like Express, which is the default on optionally, can be configured to use fast if I also expresses the fast, unopened, you knitted, minimalistic Web framework for Norges that provides many it's TDP utilities for easily and quickly building robust rest A. P s. Although Nest provides a level of abstraction about these frameworks, such as express our fast if I it exposes their AP is directly to the developer as well. This follows develop was the freedom to use a countless number of third party modules which are available for the underlying platform. In recent years, thanks to know, Jay's Java script has become the lingua franca off the Web for both front and back in applications. This has given rise to awesome projects like angular react and view, which include developer productivity and enable the creation off fast testable on extensible front and applications. However, while plenty off superb libraries, helpers and tools exist for North on server side JavaScript, none of them effectively sol the main problem off architecture nest forwards and out of the box application architecture, which all those developers on teams to create. Highly testable, scalable and loosely coupled and easily maintainable zero cell applications. The architecture is heavily inspired by Angula, since it makes use of the based concepts off angular and typescript. Angular developers can learn it quickly on will be able to create back and for their angular APs without resulting toe. Others are beside frameworks. Having said that, to learn next year's, especially with this course, you don't need to have a background knowledge off angular 4. Software setup: to get started with this training, you need a couple of softness. Number one is nor Jace to install Norges on your computer. Open a Web Rosa on visit, nor J start. Argh! I little real Eric. You tow this page where you see two big buttons. It automatically detects your operating system on, then gives me two options here. One to download what's called LDS, which is long term support that's currently 12 about $17 0 all. If you want the latest pictures, which might be tweaked and probably even removed, which is 14 doctrine or zero called us current washing, it is highly recommended that you installed the LTs wash in answer of the current version. Let's go and download this. I'm gonna keep the file on my desktop. Go on sale once it is downloaded. Let's open the same thing on the finder on double click the package in solar that brings up this installation wizard. Let's click. Continue. Continue again to continue installing this after you must agree to the terms off software license agreement. Let's click on Agree click on install If it asked for administrator password. Let's give the same thing ender on the installation is complete. Let's click close to verify whether the installation was successful or not. We can open a terminal on Windows. It's called Command Prompt, and he sure command Nord Dash. We are dusters worsen. That'll show me that the current question is 12 about $17 0 No. Just also comes with another utility command called NPM, which is a known package manager. It helps installing the dependencies required for applications. Let's check the portion of the same. I'm gonna type NPM Dash V and it says six start 14.4. The second software requirement for our training is a good court editor, and the most popular one is Visual Studio Court from Microsoft. This is based on another very popular platform called Atom. But now this is maintained by Microsoft to get the latest question off visual studio called Goto court dot visual studio dot com, and you will see a big blue button here download for Mac Once again, this website also has identified our platform on We simply have to click on this download button, but if you want to download for a different operating system, you can see that there are other options. Also, let's click on this download for Mac. Once again, I'm going to keep the downloaded in the desktop, Nick. See. Once the download is complete, let's open the same thing in Finder and then double click the Zip file, which just unzips the continent, which is nothing but the executable. We just to your coat I can execute from desktop itself, are on Mac OS. It's good idea toe drag this and drop it onto the application's folder. And since I already had visuals to the accord, it's asking me that. Do I have to keep both of them? Are Shall I cancel the operation? Actually replace I click on replays to keep the latest Russian. One thing I would visual studio code is that it's one of those software, which is called Evergreen Soft Dress, which means once you download and install every time there is an Internet connection and there is new updates available, it will automatically update itself so we don't have to download electric switching anymore , so to see how this is gonna come up. So I'm gonna double click this visual studio core. And since I'm running some softer downloaded from the Internet, macaroons is prompting me there. Shall I open this? Are shall I show you the webpage for details? Let's click open. And this is how visual studio code looks like. That's good screen by different visual. Studio poor comes with this dark team. If you want to change to something different, you can goto cord references and choose a different color team that is available. I would like to live it to the default, which is dark. One more thing that you also want to do Probably east toe run visuals to the airport from command around our terminal. For this visual studio court must be available in the part off the oils to ensure that this is gonna happen. Command shift B. Our control should be on windows and look for shell and you can see that David An option Shell Command, install court command in path. Let's select that on the bottom. You can see Shell Command called successfully installed in part. So with this now, if I close visual studio cord open a terminal and then they called dot you can see that we should. Studio Court opens on shows all the files from the current folder Let's close visual studio code. The terms offered that we require toe get started with this training is next Chase Command line interface this Valassis toe. Create new messages projects on add additional components to our existing projects as well . Father, let's go to the terminal our command prompt in windows and then type in the command NPM install all you can simplify an entire dash G that g required because this is gonna be a command line interface. We must be able to execute the command from any locations. And that's where the Dash G is important. That is a flag for global and then the package to be installed is admitted. Nest jails slash ceelo on Microsoft windows This is good enough. But on leaners on my quiz we also have to run this with pseudo privilege West ender. If it ask for the password, type in the password breasts tender and after a couple of minutes we got the installation done on. In case if you see some Arabs during the installation procedure, all you to look at is whether it installed at next JSTOR cli at the rate seven door to door zero R, which are the latest fashion when you are installing is displayed here or not to check whether our installation is done correctly or not, you can also clear the screen and then type nest dash, dash Washington are you can simply say, Dash Week. It should give the Washington that be just now in stone, which is seven dot co 7.0.0. So these are the three softer set up required for getting started with this training. Now that those after set up is done in the next lecture, let's use this command nest to create a new nest Jace project and see what are the source code generated for us. 5. Creating our first Nest JS Application: in this lecture, Let's see how to create a new nest Js project and also have a look at the files. Gender it for us in order to create a new next year's project. We can issue the command nest new on the project name that would create a new project folder for us. So it is better to decide where do we keep out projects in at once? So I'm gonna go into my desktop and issued a man that's a your silly desktop and then typed the command nest new on a name off a project. Whatever you want to convey you Typically you should view something in lower case on if you have multiple words you should you the high fund to separate the same thing. So I'm gonna give it us something called nest dash training on a per intern. First it's gonna create a bunch of sore scored for us and then it will ask you What is the package manager you want to use? For example? NBN are young. I want to use NPM, So I think we have to press enter after a couple of minutes of the project has been successfully created for us. It's called Nestor Dutch training on their the feedback here as what we're supposed to next it is get started with the following command. Number one is theory next to training and then issue the command NPM run, start. Let's do the same thing. So I'm gonna type your city next dash training, press enter and then issued the command NPM run start are simply you can type in pm start also. So I'm gonna press enter on this brings up the developments or work. Deploying our application that just got created onto the developments are, well, the developments. Our work has started in port number 3000 so I can open a browser and access local host Colin 3000. Let's do the same thing. Its GDP double slash local host cool and 3000 enter and you can see it is hello world, which means our application is up and running properly. So let's go back to the command front. Press control, See toe stop the same on. Then let's open visual studio cord and load the current folder into the same father I can simulate. I called dot and then press enter. Let's get it off the welcome screen here. The first thing you notice is the kind of icons I have over here. While it doesn't really matter, if you want toe have icons that look like mine, what it can do, they can go toe extensions and then look for material icon that is actually a team, so you can see that in my credit quality install. But what you can do it. You can click on the install button over here, or maybe you can open that and then click on the install. Now, this is especially helpful when you're working with angular applications, and since next year's uses the angular style off coding, these icons may still be off some use. But it's really not mandatory. It's totally optional. Let's goto our files and see what other fights that came up. Now you can see that they're either dissed folder here. This is for the final bill that we would be creating. However, every time you'll run your project, there'll be a bunch of files copied and pasted over here. You can ignore this for now. On almost at the end of our course, we will be discussing about build and deploy at that time, you can come back and have a look at What are these files? The 2nd 1 is the north Underscore models, discontents. All the third party dependence is that we have added Why other Packaged or Jason, if you are sharing your project with someone using some repositories like a get UB are big bucket. No models will be excluded from that and that can be specified in the date. Ignore file Here on you can say no. Models and dissed have been included in the get ignored. The next one is the SRC folder that contains the source scored generated. As you can see, all of them are typescript. Files will come back here in a minute. On the next one is the test folder that contains the E two e spec files. Nothing but test cases. Apart from these, there are a couple of important configuration fights. Number one is the packaged or Jason. If I checked it out, here is a bunch off meta information like the name of the Project washn description, Arthur etcetera. So if you're publishing this particular project in repositories like NPM Cheers, this information would be useful for searching. There is a bunch of scripts over here. One of the script is what we ran earlier called NPM Run Start that triggered this command. Nesta, start on on these commands are executive from the North Models. For example, If you see that there is a command, your car nest But under no models you can see that dark being. And inside the dot been you may find a command called nest on on windows platform. You may see next to dark CMB as the fight Any commander do you want to execute from here? You can add a shortcut script over here. Although we executed this one From now on, we will be executing start Poland, Del because it actually has a flag here called bastards Watch, which keeps an eye on the source court changes that mean if I make any change to my so scored, the developments are what will automatically start. And that's a good thing because the change is what I dough can be immediately reflected and we can go and test the same thing on the browser are too like postman. If you want to go do some debug, you can also execute NPM Run start Colon Bieber which has added a flag here called debug. Apart from this, probably towards the end of all of course, we will also use NPM run build are If you want to test your application probably you can't on N p m test Out of all these shortcut commands, two commands like start on the test can be run directly by typing the command NPM start our NPM test for all of the other ones you have to take npm run and the actual scripted me Apart from the scripts, you can see that there are some dependencies over here. These are the production dependencies, which means they're going to be a part of your production bill. Most commonly, the one that we are going to ruffle toe is next year, slash common and that internally uses the rest off them. Any other additional dependence is that we might require in the future. When we are, they will be added in this particular section. Apart from the production, different individuals are their depth. Dependence is, for example, there some tooling support for sea life. There is some testing. There is some pretty formatting and then the typescript language support itself. Let's close this file on, then have a look at one more important file which is called ts conflict or Jason. Now, this is nothing to do with messages. But since ness jizz is built on the supports typescript, it's good idea to have a look at this fight. One of the most important property here in this particular configuration file is the target . This is where we're telling the typescript toe. Compile all our typescript, gored in tow, awash in of javascript or a musket for years 2017. And if you want to complain this toe, other Russians, you can also give the same thing over here. Another important property here is the source map, which has been turned toe through here. Now this is useful, especially when you're actually doing a build. You get Thomas good files, but they will be magnified. However, you can gender their corresponding source map, which can be used for debugging purposes. Apart from that, there is a base Ural on the output directory where your build files will be dumped on. We have seen that there is a folder called Distant can. If you want to change your output directory during the bill, you can actually change it over here. If you want to know more about the typescript configuration, you can visit types, tip Langdon art and then go to the documentation. There you have the Project Configuration section, and you can find more detailed explanation about tortillas, conflict or Jason in the section. Let's go back to the escort on. Have a look at the source scored that is generated. So when you run the NPM run, start our NPM run start cooling Dale. The starting point of your application is the main Doherty S. If you're from angular background human, probably related immediately that did. Also, we have something called Main Dark Tears. In this particular file, you can see that there is a bootstrap function being called, which is nothing but a function that is defined over here. It's not a building function or anything. It's just a function that is being defined over here, and we're in walking the theme. So this line triggers the creation off object off a class called at Model, and that at Model is the one that is run on. A star were listening on Port number 3000. If you want to know what is there in the at model, you can press command, click on Mac or control. Click on windows and leaners. It will take you to the actual source score Abdullah Model tortillas, which defines the class over here and then decorates the same thing using accurate model, very similar toe accurate engine model in angular. If you're not familiar with angular, you don't have to worry about that at all. We're going to discuss about all these decorators in detail. The eight model decorator has few properties that you can configure. Number one is the import. You can think off a model as a logical group off controllers and salaries is on all other port that you have developed. You've buried another model that somebody else have developed. You can actually start using them in imports a section over here, for example, if I want to panic toe mongo db using a library called mangoes, mangoes country something for bongos module on. I can simply import that over here. At this point in time. The most important one is the controllers, which is nothing but a rotor for our applications. You may also see that there is another thing called the providers A provider basically our car injectables. Basically, you can think off. This is a helper plus that has some functionality. I want this to be available for dependency injection across my application. More on this we will discuss later. But for now let's go to the APP controller by clicking on that holding the command key on Mac control key on windows and leaners. It would take me toe abduct controller tortillas. As you can see, there is a decorator called at controller. There is no you are part segment here. So because of which local host 3000 if handled by this controller and since we made a request using a browser and browser requests are always going to be a get request by default, bury the function that is decorated with other it get which is responsible for sending a response value. So when you make a local host Colon 3000 as a request, that request is eventually received by dysfunction. This is returning value over here, which is coming from our service function. And if you go there, you will see that it simply returning a lower, which is what we saw in the browser when we access the Ural Local School and 3000 for the time being. Let's go back door controller on the change This to, let's say, for example, hello from nest and let's go to the terminal on then run the Sarwar once again. But this time let's run using the watch options. So I'm gonna take your NPM run, start colon, their press enter and this time on words. Any change I make to my source scored. That's our were automatically the stocks. Now that does start what is really let's go to the browser. Access local host 3000 Once again on day, you will see that we got the output as hello from next. One of the very important feature off nest is the written data type. We call it as mind type, multipart Internet mail extension. To understand the same, let's goto our developer tools. I go to the view developer and then go to develop a tools. I select the network tab, make sure that you have the request for on I refresh this once more and you can see we got a request log here. Click on that and you will see that the response comes with a header called Content Type, which indicates what other type of data that start where it's ending, which says that texter slash pitched GMO. This is important because nest automatically identifies the kind of data that you're sending on ads. Appropriate value for response, header content type. So since I'm sending a primitive value over here like string, so next automatically thought that this is a textual value. However, if I go and declare a variable, let's say, for example, contacts equals toe an empty are a This is an object. Now where is our object in JavaScript on ever return Here they start contacts on change. Er return data type of the function toe Probably any are even. I can remove this completely. No, Nancy Ness just determined that this is an object and not a primitive. The response did it will automatically be applications left Jason. No, I don't have to restart. The servers are where is in the watch more so I can go back to the browser directly. Make another request while I got an empty array here. If you go and have a look at the response headers This time the response had our content type is application slash chase on, and that's automatically done by messages. However, if you want to control this, you can still are your own responsive hours. But since nest is opinionated, a lot of things are automatically done for you. Let's go back toe ria score on. Probably written a string once more. Let's say hello world again. Andi, I don't need to use this constructor for now. Let's not worry about what is this constructor doing? Let's get it off that since I'm not using it all day, I don't need to add that in the import section. Also, In fact, I can even delete the file abduct service tortillas. If I delete this file now, I made on inter problem. If you go back to the Sarwar console here, you can see that there is another. It is that import AB service from adult surveys in the APP model. Dirty s is giving an address. So let's go back to the at, model tears on, Get it off this line from here. And since I don't have the AB service, I don't have to mention anything over here, you may observe one more thing that I'm not saving my files. That saved automatically because in the file there is an option called Otto. Say I have enabled that. So every time I make some changes, the final is being automatically saved on every time the finally saved that, sir, where is restarted? I can go back to the browser now on the send in a request we got hollow word on. Once again, it's easier. The content I please text slash html. So for primitives like numbers bullion, our strings, this would be texted slash html. But for objects and arrays automatically, this is street address applications like Jason. Now that we have a basic understanding off on exchange applications work in the next lecture, let's create a new model for our contacts. Restaurant point on the right couple of handlers toe handle the get the requests 6. Handling HTTP GET requests: in this lecture, let's see how to create a new module on new controller for the same model, and these models and controllers are nothing but new files. But I don't have to create a new file manually. There is a command to gender the same thing, just like how angular perverts the commands like N g gendered component, etcetera. You can also issued a similar commands here called Nestor Generate on an artifact that we should the same command. Let's go to the terminal or command prompt in windows. If you don't want to stop the server, you can open a new command prompt in windows, I can open a new tab by prison Commander T. And then I got that. First, let's ensure that were in the working directories, some multi probably toe check if I'm there in the working military, as you can see, I'm in the home military. Let's start city the stop and then type nest dash training press. Enter all the commands that you will be issuing for generating artifact, for the current project must be given in this particular folder. So this is your projects Home directory on the command. I want to give here is nest G G four generator recon, take completely generate and then type, model and name of the model on the name of the models can be anything but since we want to write Arrested Point for handling contacts off in a just book. So I'm gonna type your contacts and then press enter. As you can see, it has created a context dot modeled tortillas under Contacts Folder, a new folder here, and then it has updated Abdullah model 30 years. Also, you know, if you go back and see what is the change it has done. Number one is. You can see that there is a folder under this article contacts and a file called Context. Our Model 30 Years. The file contains an empty class called Contacts model, but it has been decorated with a great model. But I don't know. The module is almost like an empty moderate doesn't have any members in it. Typical members of a model would be controllers, injectables, pipes, exception, filters and many other stuffs. At this time, this is all empty. The other thing that has happened is that in the at model 30 years and entry for this context model has been made in the imports property, which means that model is like a parent model, which uses child models like Context Module. Let's go back to the context model, and now I want to create a new controller, which becomes part of this particular model to do so Let's go back to the terminal again on issue the command Nest G and then type controller Oregon's Implicated Nest G C On the name of the controller, we want to create once again the name of the controller I want to give. As contacts press enter notice. Once again, If model were not there, it would have created a new folder called Context. Since the Contacts folder already exists in the same folder, it's going toe are the new file Contact start controller that ts a suspect file for the same as well as it has updated the context. Start model tortillas in case of context. That model 30 years was not dead. Then it'll updated the app dot model 30 years, and that's really smart. Let's go back and see what is the file that is gendered it. We're not interested in the spec file, right now, so we're more interested in the contact dot controller 30 years. As you can see under it, Controller has a new route over here that's called contact. This is toe handle on the incoming request for local host 3000 slash contacts. This class is supposed to be filled with functions which are called request handlers, which are decorated with at the red Get to post put Patch Our Deal it. So let's have a function here that can respond to the client when the user makes a get request and to make things interesting, let's create an array called Contacts on Initialize. With some values, I'm gonna give some value like, let's say idea is one name is for example, be note email is that we know we know dot co ongoing, duplicate this a couple of times and put a semicolon over here on. Then write a function called Get All the name of the function can be anything you want, but I'm just going to say return this start contacts. Ideally, you should not written the actual reference off. The member variably should return a copy off this so that whoever is calling this particular function may not be directly imitating this reward. In our example, this function is called by nest on nest is not going to do an imitation. But if you want to send a copy off this so you can remove this from here and then put a square bracket. A square bracket always represents a new Ari. I want the values from the distort context today so I can spread them using the Year six spread operator. So I like to say triple dot distort contacts. One last thing we have to do is tow a noted this function using a decorator call at the rate. Get soil, do the same thing by typing other it. Get press enter on that automatically Import from Nesci is common were toe right a bracket for this over here and inside. This I can give either a part are an array of parts also, But at this time I want dysfunction toe handle the request for slash contact that is local host colon 3000 slash contacts, which this is going to do anyways. Let's go back to the browser and then try to access local host 3000 slash contacts and pressed. Enter and you can see I got the list off all contacts. And if I click on the response over here on the response content type is nothing but applications. Last Jason, which we saw in the previous lecture notice. When we make a request from the browser, the browser always sense a get request, not post are put for that. You may want to make it a tool called Postman are at once dressed client. There are other tools also available, but for now, let's everyone toe right. One more handler for a request that can give me a specific contact detail based on the i D . So if I type your contacts slash for example two and press enter, you can see I get an exception over here in the form of Jason. It's a state a scoreless for not for messages, it is cannot get slash context. That's to enter, not fund, obviously, because we have a handler for slash contacts, not for slash. Contact slash to to handle such a request. Let's go back to a V a score on write a function called get one, which takes idea as a perimeter. You may type your if you want as a data type off number, and then I want to take this I d such incidental collection. If it is found, I want to return. If I don't find one, I may want toe throw an exception to do so, we can make use of the are a function called find Let's toe the same a multi pure Let C equals toe this start contact start find, which takes a callback function on the contract is going to receive one single contact from this particular array after time internally the fine users and loop and gives me one object and its corresponding index. I'm interested only in the object. I'm gonna stay here, see one and then I have to return true or false, based on whether this is object that I'm looking for on I'll have to do is to type c one dot idee assuming see when is one contract object is equals toe The idea supplied as a perimeter nor that I'm using a triple equals which means not only the value off see wondered I really should match with the idea. It's data tape also should match. We may run into a problem with this, we will discuss that and make a temporary fix for the same. Now what happens is that I get the first contract object, which happens to be this one on the idea off that is being checked with this one. And imagine if I send the ideas too. So this is going to be fun because it's returning false C one is not the object that I'm looking for because of which fine will get into. The next iteration gives me the second object and the chicken object is this one. And that idea is equals toe the Islay that I've supplied over here because I'm sending here slash to and because it is a match C one will be the return really off the fine function which comes to the sea. However, if that is also not a match, then it will continue This situation for all the objects on when it is not so on a fine will simply return. An undefined I'm see is an undefined. What I can do now is I can check, if not see that mean if C is undefined, I can throw an exception right now. I want to throw an exception called not phoned exception, which is coming from nest. However, we will have a detailed discussion about how to handle exceptions are how to create our own exceptions and so on for the timing I'm going to say throw new, not phone exception Press enter. It is imported from this chase. Common Put a cynical and but if it is found on C is not undefined. I'm gonna simply say return, see, And because sees an object, a response off Jason will be sent back to the client. The only thing that I have to do now usedto annotate dysfunction with the decorator called 100 get. But we already have a get 100 for this. But this is going to receive the request for slash contacts. But I want this to handle, slash contact, slash something and to say that Richard, with your contacts slash something that are the decorated I get, unlike the previous one. This time I'm going to use a string here that represents the second part. But this part right now is to But it could be 34 r 25. It doesn't matter. It has to be a variable. So to say, that it's a variable we're gonna say slash And then, Colon, we're gonna type something. We can take anything we want like I d are. If it's confusing, we can type your contact i d. But we have to tell nest that whatever this particular part is, there, which is a varying part, should be assigned to tow this one. And to do so, we'll have to type your act great. Param, which is again another decorated from next year's common, and then say that there is a part perimeter are a You are a segment called Contact I D. That we have a cento. This idea. With this done now we can go back to our browser and then try accessing this. If I say slash contacts, I should get all of them. I am getting that. But if I type your slash two, I'm expecting this particular car. But you can see the women run into a problem. It says that status scored for not for message, not phone. This is coming because we ran in tow. This situation, see, is undefined. Now, the reason for this happens to be the data type off this value that I'm sending here because we're using an http protocol. Everything comes in the text on value Here is string on, then string equals toe number because you can see that all the ideas that are given out numeric this didn't work. We will handle this with the help off pipes in the future lectures. But for now I have a simple solution. Let's not worry about the triple equals that simply give the double equals which checks the value off this irrespective of the letter type. So we're checking a numeric toe equals toe string toe which is OK in Jolla script with this Now let's go back to the browser. Send this request once again our click on the refresh button you can t now I got ideas to name a sham email is Chamakh example that come our genuinely If I don't have a value, this will result in tow for not for because we're throwing an exception Now one more thing is we're returning the actual object but for best practice sick just like how we did a shallow copy off this area. We can also create a shallow copy off days by using the spread operator on how to use a new objects of curly bracket means new object. But I want to spread the properties off. See which I can do by just typing tripled out over here. Although in this particular example, it's really another concern. It's always a good practice to do so Now that we have written handles for get in the next lecture, let's read a handler for Post http method wherein user may send one contact object on an array of contact objects, and I wanted to be added toe my collection off contracts, which is a member variable. 7. Handling HTTP POST requests: in this lecture, let's create a new function that can be mapped to the it's TTP post method. The idea is the user should be ableto send in a single contact object or in a day of contact objects, and we should be able tow. Add those contacts toe the existing context. Sorry, but before that, let's install something called Postman. Because using a browser, you will be able to make only get requests, not post put Ordeal it. So let's open a new tab and look for postman until it the first feeling that you get here download postman at. Based on the operating system, it has already given the appropriate download button. Let's click on the same thing. Don't let it on desktop. Once the download is done, let's unzip the same. And if I goto new finder window, you can see on my desktop. There is this postman, so I'm gonna drag this and drop it on to my applications and in the applications. Now I have the postman icon so I can run this from anyway. So let's close this. Find a window open postman and you will be prompted post monies and abd under it from the Internet. Are you sure you wanna open it? You can click on open. And this is the interface off postman. So I can click on the cross button over here at a new tab here, you can select the it's TDP request method that you want to use. For example, I want to send a get request toe http colon double slash local host 3000 slash contacts and click on sent to get the four context that we already have. However, I should be able to send http post mattered to the very same you are by supplying an appropriate body. So, for example, if I'm going to copy this on, then open a new tab click on post based the urine and in the body section you can send the details of the contract that you want to add. For example, you can send the data in the form of form data our rod text. In our case, we want to send Jason so rod text is fine. When you selected Are you also have tow ard http request header called content type with a value off applications like Jason. Now you can do the same thing by selecting from this drop down Jason and then send up payload. For example, If I want to send a new contract person with name off, let's say James on, then email off James at example dot com and then click on Send. There will be a new post request, but as you know, we haven't written the court yet, so we're gonna get a fortnight for better, which is okay for no, But we want to fix this. I really got into http standards. You should be getting a 405 error indicating post matter is not supported. But that's okay. We can always control the same thing. Similarly, I should be able tow. Send an array off data, for example, if I want to send another contact with name is little. For example, Rummage email is Ramesh at example dot com. You have to surround this with a squared record. That's why we're getting this error. So I have toe select all of them, cut it, put it in a squared record, and now we have a value GIs on r E. So I should be able tow handle these kind of scenarios. So let's go back toe arias scored at a new function. Let's call it as create contacts because this could be one or more contacts and I want to receive the entire request body toe a variable called body on In order to tell the messages that we want the entire request body to be injected into this variable, we have to use a decorator called Body. So I'm gonna say that they're it body. I know that body is going to be imported from nest jizz common. Of course, body has to be given with parent. This is like this and now we have an object that could be a single contact object. Are would be an array of objects. Also, we need to decorate, dissenter function using at the right post once again import the same thing from next year slash common. Since the incoming body which may contain one contact or multiple contacts, they do not contain ideas. So the first thing we want to do is to find what is going to be the new I d off the contact that we're gonna add. And to do that, we have to first convert the contacts into an area into just consisting off only ideas and that's very easy to do. We can just do the map function. For example. I can say Let ideas equals two. They start contacts dot map, which needs a comeback which receives a single object at a time, and then we have to return an equal in value. From that object, I would say cedar idee, which means that we will be getting an aria off ideas at the end of this operation. So there's gonna be an array of numbers consisting off 1234 Now we need to get the maximum value from that which can be done using the mat dot max function. So I'm gonna take your mat dot max, which takes a bunch of values as perimeter. So we do have ideas, but I can spread the ideas into this function. So by this typing to pull dot ideas and now this gives me the maximum value in the collection. I can call this as let new I d equals two one plus mad dot max off all these values. So basically, we are now having fire as the valley because four is the maximum idea in this collection. We now have five as the new I D. The next thing we have to do is toe check. If the request body contains an area of contacts, are a single contact and that can be done by chicken if body instance off. Harry, that means we have an array here. Let's call it us. Let contacts equals to body. Yes, I can say let a single contact equals toe the entire body. Of course, Here I can take contact. Our i d equals toe new I d. But as here, I have toe loop over each of these elements and then associate a 90 for that. And that's very easily doable by typing contacts start for each. This is a function, but behind the thing, it uses a loop where I get an element on its index. I is the index here. And then I have to do some operations so I can simply type your cedar. I d equals toe new I d. Plus I. So I'm actually adding +0123 etcetera. For example, if we have sent an area of two elements here for James, we will now get new ideas. 55 plus zero is five. James Idea is nothing but five. But when the situation goes forward, I is one because the index off Ramesh is one and that Phi +16 will be Ascender, the I d. And this is the job done at the end of this. So there's no return value from contacts or forage, but it has updated the ideas for each one of them. Now all I have to do is tow Add each of these elements toe the area that we have here are this particular object to the Ari. So here I can say now they start contacts dot push. And then I can spread the contacts, Ari. So individual elements of the context will be pushed one after the other. Here, I can simply say this. Start contact start pushed and then supply this contact object, which is a local variable over here. Now, after doing these operations, you have to give some response back to the user by default. There is no response, but the status called off 200 will be sent. However, if you want toe respond to the user with the contact having newly generated ideas what I can do that can create a variable. Your core let out equals toe none. And then here I'll say out equals toe contacts. And here I'll say out equals toe singular contact. That's this variable. And then we're gonna written the same by typing written out nest automatically Arts The response header called Content type with applications last Jason, because this is not a primitive value on our post handler is pretty much really we can now test the same thing. Let's first test the get request over here. So we do have four. Let's send this again. We got our four records back and then I'm gonna send to off them here. It's an Ari. So James and Ramesh when I click on Send previously we got the for Not for. But this time we should get status 200 plus. Both James and Ramesh should have some ideas. Added to that. Let's check it out and you can see James has an I D off five. Ramesh had the 90 off six. Also, if I go back over here and then click on send, you should now see that there are six contacts in our attic. So this is how easy it is to create a post handler. All we have to do is tow. Declare a variable here toe, receive the entire request body. Decorate that with the help off at the rate body on decorate the function itself as at the right post. In the next lecture, let's read. I put metal handler which can be used for updating a contact details. 8. Handling HTTP PUT requests: let's know, right, A new function over here on the map. The same thing to the its GDP put request matter. In theory, the it's TDP request mattered. Put he supposed toe update a resource, which means you're gonna send a contact with data on. We need to search for that particular record in our database and then we have toe replace that are up, did the same thing. Unlike the Post, we're not actually modifying multiple records. But in case if that is what you want, you know how exactly that can be done. So the function we're gonna write is going toe have to perimeters. One is supposed to be the i d off the contact that we want to update. And the second is the request body which contains the new details off the contact. For example, I may want to send a put request toe This particular you are also let me copy this year oral at a new tab over here selector. It's TTP put matter base that you're over here and if you want toe update the details off, let's say, for example, Sham. The idea is to we have to send it as part of the Ural segment here like this, it is as if you are supposed to search for the particular person with idea off to and replace his or her details with the one that we're sending as part of the body. Once again, the body will be raw, and then we're going to send Jason content. In theory, the put request is supposed to replace the details off the person that we're searching for with the details that I'm sending. Whereas if you want to send only partial data, then you may have toe handle the same thing using Patch. But for now, let's look at the put. So I want to update the name and email off contact with the I D to. So let's a name is going to be Sham cinder. Andi email is going to be, let's say Sham Casey at gmail dot com. And if I click on send once again, since we don't have the handler, we're gonna get for not four, we can give it a try and you see that we got the for not for, but we want to implement the feature Nam. So let's go back to Rhea scored on add a function called update contact, which this is an I. D. As the last body. And it's supposed to return the modified or updated contact details, which is nothing with the body itself. Notice that the body that we're sending doesn't contain the idea. The idea is going to be deterred from here. Even if I have added an I d over here, that should be ignored. So let's go and search for the contact with this idea first, and then replace that with this particular body fasting. First, let's add the decorators. So this is going to be at the rate put press enter to do an auto import at the parentis is idea is supposed to come from the perimeter that we're gonna receive over here. So I'm gonna take your slash colon idee and then here a monotype at the rate bottom off. I d whatever that were given over here is the value for at the rate for, um, decorator on this is gonna be at the dead body. Now, Since we know that this is going to represent the contact, I can simply type your contact. I missed their single courts over here that's where we're seeing the other. And now we have to take this contact set this value as its I d on then replace the contact in our member variable. First of all, let's check if this is a valid I. D. So to do that instead of using the find Amber News, the find index. So I said this start contact start find index and I will receive unusual contact from the Ari. And then I'm gonna check if Cedar idee is it equals toe the idea that we're supplied once again, keep in mind that we're going to use a double equals instead of triple equals, because when the perimeter was received, it will be in the form of a string, although we can convert that into an integer. But for the time being, we're going to use that as is So this is a new medical I d over here and then we're comparing that with their string I d. But as long as their values are saying this is going to return true and if that is true, this is the contact that we're searching for. We get the index of the same thing over here so I'm gonna type here. Let index equals toe this for their cynical. And over here, however, if the Islay given is wrong and not to be found in the entire area Bigot minus one as the index value. So we're gonna check your if index equals toe minus one. We're gonna say throw new, not found exception. We have seen this in the previous lectures where the response scored off for not for will be sent. However, if this doesn't take place. So we are here in light number 58. Now we're going to say contact our idea called Stow the idea given over here, which is what we distinct. Of course, you can always do a part into just to make sure that it is a numerical value. And now we have toe replace the contact details in this index with the new contract object over here. I'm going to say, here they start contacts off index, so the value in that particular index is going to be replaced with the local variable contact. And finally, we're gonna say written contact. This will now go as a response in the form off. Jason, let's go and check the same thing since two is a valued I d. We will first check What is the current value off that? And remember, were working in in memory data. Even though I see six off them over here. It was the previous request. Since the sorrow restarted, everything in the memories reset. And now I have only four contact. So if I click on send, I should get four of them. And this is the current value for Sean. Whose ideas too. I'm gonna go and send this request now and now we can see the response came back with the modified content. If I go back over here and then click on send, you can see that the value off Sham has changed due to chance Inder and Charm Casey at gmail dot com. However, if I go and try toe update a value, which is that there for example, 25 25 is an invalid lady. No matter what I'm sending over here, I'm gonna get for not for over here because 25 is an invalid. I d If you want, you can also customize these other messages. We will have a separate section for handling these kind of errors and exceptions. So to summarize, we have toe write a function and decorate the same using at the rate put the put always receives a part segment over here, which is representing the I d off the person that we're tryingto edit, and that idea will be positive into a variable. The entire request body is also going to be received, which is going to be eventually updated. Toe our source data and in case if the idea given is wrong and you want to respond, the user with for not for all you have to do is tow throw a not phoned exception. So that's all for this lecture. In the next lecture, let's see how we can handle the patch. Http method where partial data can be updated without any problem. 9. Partial update using HTTP PATCH request: the extra DB Political also has a request Minted called Patch. The idea is toe do a partial update. So in this lecture, let's have a look at the same on First of all, let's create a new request over here. Select the patch method and send the same urine request, which is toe It's too typical and local host 3000 slash contacts slash some i D. But I want to send a body that contains probably partial data in case of the put, it would have completely replaced the contact details with one that they sent from here. But in this case, I'm gonna send only the email. But the name should not be touched. Let's give an example off Casey Sham at example dot com and let click on send. As usual, I should expect for not for because we don't have a corresponding handler function for the same. So that's going to create the one which can handle this particular request. So that's scrawled on. Over Here are a function called partial update. This function also has to receive these two parameters, so I'm gonna copy and paste the same thing over here. Also, the logic four dysfunction remains more or less the same thing as the update. So this part is gonna be the same thing. I'm gonna copy and paste that over here. But unlike the previous example where we completely replace the contact objectively given index with the new one this time we're going to simply overrate the existing fields, and that's gonna be very simple. So we're going to say you're distort contacts. Off Index is equals to a new object, but the object is gonna get values from the same object. So there is this start contacts off index as well as some of the values coming from the body. So we're gonna say spread contact. So remember this already has name and email discontents only email. So the email in this one would be overturned by this one, and that's gonna be a completely new object. And that new object is going to replace the one in the current index. Once this is done, we're going to actually return distort contacts off index. Of course, if you don't want toe, send the actual object and you want to send a shallow copy. It's always a good idea toe. Do the same thing. Just put the spread operator over here. One last thing that we have to do is tow map. This particular function to the http request mattered patch, and that's done by taping at the Rate Patch Press enter to automatically import. And then, just like the port are the slash colon idee because this is the one that we're tryingto receive toe this particular variable. Since my file is automatically saved, next year's would have automatically reloaded that there were also Let's go back to the Postman and see what actually is the current Valley for the I D to let's click on the send ones. Then you can see that the name is Sham Emily Sham at example dot com But we're actually changing the email tow Kingfish, Um, at example dot com. By sending this patch request, let's give it a try to consent, and you can see that the response comes back with the updated data. Name is not going to be disturbed, so it's also going to check that out over here. Click on Send and you can see that name Dimension. But email has changed Toe cassation. Example that come So this is how you handle a partial update using the patch http. Request matters. As for the http requests are concerned, the only thing that we have not done is the village on. That's what we're going to do in the next lecture. 10. Handling HTTP DELETE requests: In reality, it's very unlikely that you do actually delete operation, which is called harder delete. So you're gonna lose the actual record in the database if you are maintaining those thing in the database. But instead, probably you may want to do something called Soft Village, for example, if an employee quits the job instead of actually deleting the record from the database. What we can probably do is tow either flag, such as he's active and then turned the two false similarly, in a shopping cart application. If a product is not going to be sold anymore, probably because it's not being manufactured anymore, we might want toe add a field called Discontinued. And whenever the product is not being sold, we can simply say discontinued equals to two instead of actually diluting the product. However, for the sake of demonstration, we will implement a delete operation where we take an idea and then search that idea in our record, and then we will delete that on that particular index. Since we're using an array, we just heard of the motor element from the index. So let's go ahead and do the same thing in our BIA scored here. So we're gonna come down here at a function called delete Contact. It takes an idea as a perimeter, and we have to search if that I exist. If the idea doesn't exist, we're gonna throw a not phoned exception. But if the idea is found, we're going to remove that element from the sorry that we are maintaining. So to do that, I'm gonna simply copy this part which will take it off. Whether the idea is a valid one are not as well as it finds The index of the contact which contains the idea given on. All I have to do now is toe use a function called splice, which is part of an area. So I can say this. Start contact starts place, supply the index and then the number of elements to be deleted. Since I want to dilute a single element in that given index, we simply say one displays function also returns an array of all the deleted elements. So I can say here, let deleted equals toe and then assigned this entire operation. Dilated isn't sorry. I know that I've deleted a single element. I can simply say here, return dilated off zero because that's the one that I've deleted on now. My delete function is really all I have to do now is toe the decorator at the rate delete, as usual, supply the ideally in the form of a segment here and then received the same thing in the form off a parent. Second copied. It's on pace over here. It's Our function is now ready. We can go and verify the same thing. Let's go back to postman. First of all, let's see the details that we have. So we have four records. Let's I want a billet John Circle, which is three. So I'm gonna use the same Ural at a new time. Over here, solider. It's TDP Delete Method based, the you are in. And then we want to supply the idea of the person that we want to delete. Lets it 33 is John's idee bill. It is like get where we can't supply request body. We can't supply quietest in parliament that if we want, but in this case we just want to supply the idea in the form off segment here, let's click on send and see what happens. As expected, it is returning the details of the person whose data is deleted from the context. If I go back to the get request, send it again. You can see that we don't have the details off 83 on once again. If I send the same request again, it's gonna come back with former for because the idea is not found in the contacts anymore . Off course. If I restart subtler, everything will be reset again and then I'll be able to deal it once more with this. Now we have discussed elaborately about controllers. There are a few more things that we can discuss about controllers. Such a Squire listing perimeters are headers. How do we access them? How do we respond? The user with custom at airports are other messages. How do we respond? The user with custom status scores are status messages, which we will be doing subsequently, along with other concepts. 11. Overview of providers: in this lecture, let's discuss about providers which are a fundamental on an important concept in nest. Many of the basic next classes may be treated as a provider, for example, services repositories, factories, helpers and so on. The main idea off a provider is that it can injured dependencies, which means objects can create various relationships with each other, and the function off winding up off objects can largely be delegated to the Nestor runtime system. A provider is simply a class annotated with an at injectable decorator. In the previous lectures, we built a simple contacts controller controller should be limited toe handle. Http requests alone. Andi should delegate more complex US to the providers. This brings one of the most powerful design principles. Your application, which is called Separation of Concerns. Nest is built around the strong design pattern commonly known as dependency injection in nest. Thanks to typescript capabilities, it is extremely easy to manage. Dependence is because they are result just by type. In the example shown here, Nest will resolve the contact salaries by creating onder returning an instance of context at risk class are, in the normal case of Singleton returning an existing instance, if it has already been requested elsewhere, providers normally have a lifetime, also known as a scope synchronized with the application life cycle. The default scope of a provider Instances called Singleton, which means a single instance of the product class, is shared across the entire application. The instance Lifetime is tied directly to the application life cycle. Once the application has boots stopped, all the singleton providers have Bean instance created on these proto instances will only be destroyed when the application shuts down. However, it is possible to make the scope of a provider instance request to scoped as well. A new instance of the provided is created exclusively for each incoming request. On the instances, garbage collected after the request has completed processing on the responses given back to the plate. Using singleton scope is recommended for most use cases. Shading provided across consumers on across request means that on instance, can be cashed on its initialization because only once during the application startup. The technique we have used so far is called constructor based injection. Since the Providence R, injected by the constructor in some very specific cases, a property based injection might also be useful. For instance, if your top level class depends on either one or more providence, passing them on the way up by calling Super in the sub classes from the constructor can be very tedious. Take a look at this example where class has to dependencies. Service X. Enter his wife. If you create a subclass for Class K, let's a Class B which has a dependency off Servizi. Then in it's constructor, you have to ask for service, tax and service by along with Servizi. Since in JavaScript, a subclass constructor must involve the super plus constructor. I seen the super class constructor, high salaries, accents, every square as dependencies. You must to supply the same to the super class constructor as well. In order to avoid this, you can use inject decorator at the property level in the subclass. Since there is no constructor in Class B, there is no need to in work super class constructor and hence there is no need to possible class dependencies. Now that we have defined a provider and we have a consumer off that service, we need to register the service with nest so that it can perform the dependency injection wherever required. We do this by editing or model file. For example, Abdullah Module 30 years or contact start model Dirty s. And I didn't this Aries to the protests are off the act module decorator with this idea about providers. Let's create our contact service in the next lecture, along with its basic set up. 12. Creating the ContactService injectable: in this lecture. Let's create a new nest project toe, understand the use off Providence. So I'm gonna go into my stop and then create a new, less Js project by typing nest new and then give the name of the project. I'm gonna give a name called Nest Dash Providers Dash demo and then press enter. I'm going to select NPM and then press enter. The project has been created. I'm gonna city into the folder called Nestor Dash Providers. That's demo and then type NPM run start colon there, this is going toe watch all the changes in my cold. Also, make sure that the previously run project is stopped by pressing control. See, otherwise the port number 3000 will be blocked and you will not be able to run this current project. I'm gonna breast enter on. My server is up and running. I'm going to open a new tab and then type CD, desktop slash nest providers demo And then I'll that court dot that will bring up the Visual Studio Court on opens the current folder. Let me full screen this and close the welcome screen and expand the SRC where I have this app model. Dirty ears. Notice that there is already a provider over here. But let's not worry about that. Instead, let's create our own model a controller on the service. So let's go to the terminal on then type in the command nest, generate or just G and then type model. That's college has contacts. We created a contacts more deal, but that was in a different project. So this doesn't conflict with that. I'm gonna press enter. And as you can see, it has created a file called Context that model tortillas in a separate folder called Contacts and also has imported our new model in the APP Modern, which is called route model. So if you go back over here, you can see that in the list off imports are contacts, model has come up. Of course, the context model itself is currently empty because there is no other imports. There is no controller on. There are no service providence. So what I'm gonna do is I'm gonna go back to the command, prompt or terminal, and then type nest G and then type controller, and then I'm gonna our contacts. Now this controller is going to be a part of the context that moderate RTs as well This is gonna be the consumer off our for wider our survey. So I'm gonna press enter. You can again see that there will be a context controller tears as well as a corresponding test respect and it is also updated Our context modeled RTs that's very important. So if I go back over here, you can see that it has added an entry in the controllers are off at Model Decorator. Let's do one last task here in the command front or terminal. I'm gonna type your nest G and then type surveys even though what we need to create a provider. That command is nest G service. Now, this is because nest is heavily influenced by angular and even in angular. Though it is called US provider back chill command is n g generate service. The same thing is followed over here. So with a nest generate service and then we're gonna take contacts. Now, Since the name contacts is used over here, it assumes that it's going to be inside this folder and seeing the inside this folder there is already a Model five. This becomes part of the contact start model tortillas. I'm gonna press enter and you can see that the service class as well as their testes spec created on the context Art model tortillas has been updated. Onda update is nothing but in the area called providers and entry has been made over here. Now, this is what is called the destruction off the service our porters with the model. So inside this model, now any controller can have access to this wire dependency injection. Now to do the basic set up for our contacts. Our waste. Let's go to the source court off the scene on. Then we're gonna write some court over here on this time. Unlike the previous example baby used there in memory data. We want to use an array here, but the data is going to be persisted into a file. So I'm going to use the FS model which is not the model file system model off no jays which we can import in the form off imports Star as Fs from Fs Fs is one of the core modern which is built in tow. Norges And we get the members off that as fs and this efforts model provides functions like Read file right File Exeter, which are all asynchronous by nature. But if you want to read or write synchronously, then you also have the sink wash in. For example, there is a function called efforts dot reid. File Sync. Our efforts dot right find think are depending on your need. You can choose whichever you want, so in orderto persist over file, we need the name and location off a file. Let's define a constant filing equals two. Let's say in the project directly that DOT Slash would correspond to the project director that is our SRC folder on. I'm gonna give the name as contact start Jason, you can get the name of the file, anything you want. But since we want to store the contacts, I'm going to simply stay with us context or Jason on our contacts of his classes. Going to maintain an a day on the content of the area can be persistent into this file in the form off. Jason using the Jays on a P A. We'll have a look into that in a couple of minutes, But first, let's create an array representing the data even though I didn't use in memory periodical, it's going to be persisted into the fight. I'm gonna clear the variable called contacts, which is going to be assigned with an empty array here. Andi in the constructor. Let's try to read this file and then copy the content off that into this contact. But if the file doesn't exist out of the file contains nothing, then we're gonna just leave it as it is. So for that, I'm generator Constructor on the constructor is going toe. Make use of the F s model to read the file. I'm going to say let content equals two fs start read file Sync. Now the reason I'm using sink is if I use the a sink washing off dysfunction then of course , there is no return value, but the actual function is going to be executed only after the Constructivist called Andi. That would be a problem because we want that context to contain as soon as we read this. So that's why we want to use the reed finds. Think so. Let's go and use the same thing. This request couple of perimeter. The 1st 1 is the name and location of the fight. I'm gonna give the fine name which is declared in Lane number four. We also to specify what is the content to be read as I'm going to say utf eight, That is the character, including that I want to read now. In case this file doesn't exist, it's going toe throwing exceptions. Obviously there's no return value, but they will be an exception thrown. What I want to do now is to surround this with a try, catch blood. So I'm gonna cut this and then put a try block and then inside that I'm gonna paste and in the catch block where there is an exception. I just want toe leave their contacts, as is our reckon explicitly said this start contracts equals to an interior, But in case there was no other over here, I simply want toe assign the content toe this but the fs don't read files. Think Retton's a string if everything is OK But I wanted in the form of an a day. So I have to convert this string into a Jason which I can do by typing contacts which is nothing more. Distort contacts equals toe Jason dirt parts This is the Jason AP a function that we want to use on. I'm gonna supply content now in kids. If this doesn't contain anything, even this would have thrown an exception. And that exception will go into the catch block on off course I'm ascending. An empty are over here, which means if the file contains some content and that happens to be some valid Jason content that would be converted into a JavaScript object and will be assigned. But in case off any problem, this start contact is going to be an empty every now. That's what is gonna happen first time because I don't have this context or Jason in my source folder. So from now on, any function that is called toe read all right, it's actually going to access the content from context. Ari. Of course, if the contact is modified, we want that content to be updated back to the context or Jason on this is going to be done when I add a new contract or when I add a multiple contacts. When I updated contact out. When I do a partial update, our when I do a deal it I require writing the contacts in tow, the file on. That's why I'm gonna write a kind of a private function over here, which is like a utility function. So God is us, right toe find. And then I'm going toe simply take this contact, converted this into a string and then right to that and that can be done very simply by typing efforts dot Right file either a canoe, the right file, our rightful think the best suited method here is right for in sync on I'm gonna supply the perimeter. The part which is nothing but the fine name. The 2nd 1 is supposed to be the content which in the Demeter data I haven't other here called contacts. But that object I have spoken word this interesting. Once again, I can use the Jason a p I that has a function called string. If I, as the name suggested, can words any Jason object in tow? A string. And I hope this up like this dark context, the third perimeter would be a bunch of options like what is the character, including a By default, it is going to be a beautif age. I can explicitly specify utf dash eight like this. Now this is going toe right. The content off distort contacts in the string format to or context or Jason. But this is a simple utility function on a private member function off contact service, which needs to be used whenever required. Like I said, when we want toe, add update or deal it, that's when we're gonna make use off this. Let's now write another function, which is goingto take ideas. A perimeter on check whether the i d. That represents any contact inside this Harry on. I can simply call this function as exists on then ideas the perimeter. I have to now written tour falls depending on whether that idea is found in one of the contact in the area, and where you can do is you can actually check the index often object Whose idea matches with this. If the index is not equal to minus one, that means it is phone if it is equal to minus when it is not fun. For example, I can say this dot contact start find index Onda, like in the previous examples we have seen, Finding Decks takes a callback. The callback is given one element at a time. We take that one element and check. If it's idea is it equals to the idea that is supply, That's perimeter. If this is true, then the index off this object will be given as a return value. If that is funds than the finding decks continues the loop on, then use me the second contact and again we're going to do the same thing. If this is true, then the index of the second object is given. If no, it is going to continue the loop. So in case if none of the objects contain this idee, then it's going to give you a minus one. And that's what we want to check. We say here, Hey, is it not equals toe minus one? Then that means it is found, so I can simply say, return this. Enter expression. But in case if it is not fun, it is equal to minus one minus one articles to minus one. It's false. It will simples their return falls. So you're asking Hey, does this idea exist on you? Get the interest false. So that is a function that we can make yourself in our controller on the check if I d given by the user existing or did of it or not. Before we conclude this lecture, let's also right. One more function and dysfunction is supposed toe generate the next idea that can be given to a new contract, and this is required whenever user sends one contact or an area of contacts. We want to gender the next idee so we can write a function called Get Next Idee, which is simply supposed toe written the next Heidi. In the previous examples, we have seen how to convert an array of contacts into another of ideas and then take that, give it as an input to the mac dot max, which gives it a maximum value in the collection. And then we can simply return the plus one off the same. But before that, let's also check if the context is empty. Will template on the next tide is one, because that's gonna be the very 1st 1 So I'm gonna type here. If this start contact start Lent is equals to zero, simply return one that's going to be the new I D. But of course, if the contacts has one or more elements, then we have to find what is its maximum values. So I'm gonna say you're let ideas, which is going to be an array of ideas, is nothing but this start contact start map, which converts a given object in tow. Something else in our case, we're gonna convert a single object into an idee map, will convert all the objects in tow, a bunch of ideas, and that's going to return an array of all the ideas. That's what we have here, which is the area of ideas. And then I can say return one plus mad dot max, where I will simply spread, I least. So whenever we want toe find what is the next idea I can use for adding a new content? I simply have to call this function in year six. We also have a function that can be marked as they get to property. All I have to do is tow. Just use the key were called get. So I like to give a space here and then use a lower case letter as a convention. So use what's called camel caps. Now you see, we have a get function, so it's getting the key word. Now what? It does it it? No, it all knows us toe. Treat this as if it's a variable. So, for example, against the next tidy plus one, our next tidy plus two. So which means you can never call this as a function anymore. But you can treat this like a variable, but it's a really don't be variable. So this is very nice when we use this human. Understand? If you don't know this already Now let's go to our controller, which is there here As contact start controller Dirty s on. We're gonna know Ask for this particular context salaries. And I can do that in two ways. Number one is a constructor based injection. Number two is a center based injection. Settled best injection is by using a decorator called at Inject. But instead we're going to use the classic Onda suggested one, which is the constructor based injection. So I'm gonna tape your constructor and then inside the constructor, I'm gonna say surveys off my contacts service on the constrictor doesn't have any body here . It's only job is to receive available from next year's. However, if I read a function year For example, add one contact, which takes some perimeter. But that's gonna be for later here. I can't make it off this variable because the variable declared here the perimeter variable is local to this particular constructor body. Now, the only thing that I might have to do is to declare and new variable over here on. Then assign these dorks always equals to service and so on and so forth. So ultimately, we can simply mark this particular variable with private public are protected on den on words. I can use them here because typescript will automatically convert that variable in tow A member variable. So I'm gonna go in. Mark, this s private. And now I can come down here and then say this dot and you can t I have your access to service now that we have done the basic set up for our controller. We have registered that with our model and we have injected that service to our controller in the next lecture. Let's implement the handler for post requests for adding one are more contacts to our contacts database 13. POST /contacts controller and service: in this lecture. Let's write a handler for http. Post requests for adding one or more contacts, and that's gonna be dysfunctional controller. But before that, let's right. The survey scored for the same things. I'm going to switch to my contacts with tears. I'm gonna right here. Two functions, one function that can handle adding off a single content. On another function toe. Add an array of context to our contacts database. I'm going to write a function called Add one contract, which receives basically a single contact object. And here is where I have toe. Take that object, add a newly generated I D. Which I can make yourself from here and then push the same thing to our Ari, which is in memory data structure on. Then take that our A and right to the actual file for which I have written a function called Right to Fight. Once that is done, we simply have toe written this contract object with the auto generated idea. So let's assign the i d. First someone type your contact dot I dy equals toe this start and I can say next I d just like this notice. Next idea that function, but because it is a get function, I'm using this as if it's a read only variable, which is nothing but the return value off that function. I know that I have the i d. I can simply say this start contact, start, push and then I'm going to supply the contact. And now that the member variable contacts, which is an array, is modified, we have toe update this back to the file for which I can simply say this dot right to file function in case of dysfunction throws an exception. I'm not handling that over here. Whoever is calling this will have to handle that. And that's nothing but my controller. And if your controller doesn't handle this exception, then automatically nest will take care of that because there is a default error handling mechanism. However, we can also have our own exception handling mechanism which will see in the subsequent lectures. But for now, the last statement that I have to do here is to return the contact which now contains the newly generated I. D. Also likewise, I'm gonna write one more function called add many contacts on Dhere. I'm gonna type contacts which is supposed to be an every object, unlike the previous one. I have to know Newport, this Ari and then for each of the element in that area. How toe a Zander next idee. First, let's get the next idee by typing Let next I d equals toe distort. Next, I d notice that this is not a matter call to the function that we have written over here on whatever the return value is, there is a sign. For example, let's assume I already have 10 contact, so this would be 11. And now I have to go Increments is 11 and then assigned toe each one of these elements in the context array, and that can be done by typing contacts dot for each, which is going to take a call back on. The callback receives two parameters here. The 1st 1 is the unusual contact, and second, is the index off the contact. On using that, I can no manipulate that variable. See such a cedar i d equals toe the index plus next highly so the first index would be zero on that. Zero will be added to the next tidy, for example, 11. So the idea for this particular object would be 11. But as the loop progresses, it's going to be 12. And then it's gonna be 13 and so on and so forth. I made a typo here that's supposed to be a semi colon. Now that all the elements off this contacts are have ideas. I just had to push this to the member variable, so I'll see her distort contact. Start pushed. You can't simply take contacts here because then imagine this Door contacts has 10 unusual contacts that entirely becomes the 11th element. So we don't want that. We want to spread this arrest, so we simply have to type your triple dot So the members off this will be no added one by one to this particular contacts attic now that the contacts has been manipulated. So we need toe persist. This back to the file on the way I can do is this start right to file on return the enter our contacts, each of which have now a new I. D. So this is the business logic involved in adding the contacts and notice that we again followed a single responsibility principle where a function has a single responsibility not to responsibilities. So we have divided the task two separate functions, which is a good practice. Now let's go back door controller where I can make it off this surveys, and the first thing that we will do is tow. Add a decorator here at the right post auto import from next year's common No perimeters required for that. However, we want to read the entire body that's coming from the request. To do that, we're to declare a variable something called Body. The variable in can be anything, but it has to be decorated with that body like this. The body may contain one single contact object or an array of contact objects. All I have to do is to check if body is an instance off Ari. Then I'm going to say return. This starts are we start. Remember, we have a function called are many contacts, and that's where I'm gonna supply the entire body. This is not going toe loop over each of those elements as the ideas adds the polar database in the memory and then persisted into a fight and then returns that enter Ari on data is going to be returned back to the user. But in case if it's not in a way, I assume that it's one single contact object. I'm gonna say, Return this start service dot Are one contact and then I supply the same body over here. Now you can see that the responsibility off this particular controller function is very simple. It just taking the http content and then passing it toe more sophisticated service function for complex functionality. Human. It is one thing here that we're taking the entire body and assuming that it could be an area or it could be a one contact object. But it is possible that the user, while posting, might have supplied instead of a contact information, probably a book information out of product information. At this point in time, we're not gonna take care of those validations. However, we are going to take care of the validations using something called pipes which will validate the incoming request body against our schema. So that means that if I define a contact class and that said that though there is the first name, that is the last name does an email phone etcetera and the body doesn't conform to that, then it's gonna throw an exception. But at this point in time, let's go blindfolded, Lee, and assume that either it's a one single contact object or it's gonna be an array of contact objects. Now that we have written the controller on the corresponding service, it's time for us to check the functionality off the same. Let's go to our postman on. Then make a new post request. Over here on the euro is gonna be http. Colon double slash local host Colin 6000 is because in the main 30 years, the port number is 3000. If it all you want to ever change this, come here and then change. Restart the server are somewhere anywhere gets restarted automatically. The port will be changed automatically as well. So if I go back over here locals 3000 slash contacts. This is nothing but the controller that I've returned here on the note that the controller has been mapped toe contact. But since I'm doing a post request the entire post request, it's positive the dysfunction, whatever the body is there will be supplied to here. So I go back over here to send one contact object. I'm gonna select Body Rock. And then I select the Jason which acts and its TDP request header called Content type. With only off applications like Jason, I'm gonna use a curly bracket because I'm supposed to send one object, and I'm gonna simply give your name is not on the email is let's say we know at the rate we know dot co If I send it now, this being a single object here it goes to the Elsa section on. Then add one contact on. Remember, at this point in time, I don't have the file. So the final is supposed to be newly created on. We're gonna see that file over here, and the file is going to contain the data that I'm gonna supply along with the idea one. So let's click on, send on and see what happens and you can see No, we got the same details along with the idea One. However, if I'm gonna make another request, let's copy this at a new tab. Once again, it's going to be a post request. Same. You gotta go to the body fiction raw and then choose Jason This time I'm gonna send in a day off to values here, for example. I'll say one object with name off Laetitia on, then email off levitation at example dot com on another object over here on this is gonna contain name as that, said John on the email as John at example dot com. So I'm sending another because of which this is a function that's going to be executed on that function. Are many contacts is going toe loop over each of the elements gender. It's annuity for them and push us that. And remember at this time I already have one element in our context or Jason on. If you check over here, there is a file called Context or Jason. This was created because of my previous request. I click on this and you can see there is one value here. If I submit this now, I should get the same array with new ideas. Two and three on the same thing is also objected to the file. Let me form at this. You can press all shift F on Windows machines and option shift F on Mac to former the cord , and you can see now I have here formatted content, which contains I did want to three also. So with this now, our post request handler is done along with the service functionalities corresponding to the same in the next lecture. Let's right the controller and the service functionality for getting the list off all the contracts from our five. 14. GET /contacts controller and service: know that we have added few contact details to our file as a repository in this lecture, let's right the controller on service functionality for handling the get request to give all the context to the client. So to begin with, let's write a function in our service called Get All Contacts, and all I have to do is to return a copy of the content maintained by Distort Contacts. On I'll have to do is to use a spread operator over here and then say this dot contacts Notice. This particular function may not have any validations over here because there is no parameters coming in, and hence this function is very, very simple. So let's go to the controller on in the controller. I'm gonna write a function here called that they get all contacts and the name of the function can be anything you want on return. This starts. Surveys don't get all contacts that I'll have to do. But in order for the user requests to reach here, I need to decorate this with other it get without any perimeters on our get request. Handler, along with its service function, is really let's go to the postman and very for the same thing. So if I go on, copy this urine, open a new tab, make a get request this time basted Ural on Bentley Concern I should get the context that I have in my database, which are nothing but three. The course that I argued in the previous example Let's click the send button and now you can see we got all the context as another. So that's all for this lecture. In the next lecture, let's try toe Access an unusual contact object based on the I. D. And in case the idea is invalid, it should also give for not for error. 15. GET /contacts/:id controller and service: while we were ableto get all the contacts in this lecture, Let's tryto access and unusual contact data based on the i d. So I really I should be able to send in a request to the same mural. But of course, at the end, I should give slash and the 90. So I'm gonna open a new tab, select the get request on that. This is gonna be locals 3000 slash contacts on an i. D andan active Constand. It should stretch the details off that particular idee, but in getting the idea is not there. We should get a four, not four. So that's going to implement the same thing for us. Let's go to the service over here. I'll a function probably called Get one contact, which receives idea that perimeter I I have to know Search decided in this member variable . If it is phone, I should return that object. If it is not fun, it is okay, we're going to return undefined. So it's gonna be pretty much one liner over here and say return. They start contacts dark find, and then I supply a call back where I receive a single contract object and I check if it's I ve same as the idea that I passed the perimeter. If that is the case, it is going to return the object. But throughout the alteration, if it doesn't find that I d, then it's going to return undefined. That means if I have 10 objects and if the match is found in late to the 3rd 1 day duration stops over there and the third objective return. But if none other 10 objects match this condition, then at the end off the 10 reiteration, it's going to return an undefined. So let's go to the controller called dysfunction and see how that's gonna go. And this time, let me write a function called Get contact by idee, which takes ideas a perimeter, and this is supplied by the user. Why are the part perimeter of that segment? And if you remember, our contacts always had a function called exist. I can check your if this starts that we start exist and I supply the I D. If this is true, then I'm gonna say return. This starts are restored. Get one contract and then I supply the I D. But in case if it doesn't exist, then I simply have to come out of the if block and say through new, not phone exception Notice that I don't have to write an else because of the condition is true. It's going toe. Return the control away from this function and it will never reach over here. So only when the condition fails it comes here and then exception is thrown. And one last thing that we have to do toe map this function to the get request is to say that they get But we already have a get mapping here. This will be off no use. But we need to know. Say that head. The part may contain a segment which represents an I. D. And that is done by typing slash colon idee. This is your part segment. And then I'm gonna map that part segment to this variable by using at the rate problem and then supply the idea because whatever this segment name is there, that is the one that we have to use that would be assigned to this particular variable. And now let's go back to our postman and see if I'm able toe get the data for this contact to and the contact to currently represents Sham. Let's go here and then click the send and you can see that we got it on. If I supplies something, like, say to 22 which is an invalidity, I'm gonna get a for not for error. Here. There is a Jason object. Plus, you can see the status is for not for over here. 16. ASSIGNMENT Implement PUT, PATCH and DELETE handlers: here is a small assignment for you. It has three tasks. Number one task is toe Implement a handler for put request, which is supposed to take an entire payload representing all the details of the contact for a given 80. And then when I submit the current of details off, this particular person in the database should be replaced with whatever that I'm sampling as a payload. The second task is the patch implementation, where I can supply partial data Name our email for a given idee. It should read in the rest of the details, but only the one that I'm supplying should be overridden on 1/3 test is toe. Send in a delete request for a given. Heidi. There is no payload or body associated with a dilute request. A payload can be sent only where post foot or patch get and delete Do not have any payload . So when we send this deal, it request the data corresponding to this particular user must be deleted from our five. Also in all the three cases. If the idea supplied is invalid, we should get for not for adult status. You should be able to finish these tasks in the next 15 to 20 minutes. Once you finish that, please go through the next lecture where I'm providing a solution for the same. 17. ASSIGNMENT SOLUTION: in this lecture. I'm gonna provide the solution for the assignment that we discussed previously. I'm gonna implement three tasks in three different functions. So I'm right now in the service class for handling the put request. I'm gonna have one business logic function over here. I'm gonna call this US update full because it's supposed to update full contact details, which is going to receive idee as a perimeter along with contact objects. So the contract object Typical is the payload on ideas. What is coming as the request part perimeter on, The first thing that I'm going to do is to check whether this idea exists or not. And if it exists, what is its index? So I'm gonna type your let index equals toe distort contacts dot find index, which takes a call back, and the callback receives the unusual elements off the start contacts one by one. So I'm gonna say, see, Andi, I'm gonna check if see, that idea is it equals to the idea that I deceived. If the answer is yes, then I get the index. But if the answer is no, it will go through all the elements in this start Contacts and then gives a minus one as the values I'm gonna check your if index is not equals two minus one, which means it is found on. All I have to do is to say this start contacts off index is equal to a new object consisting off all the members off contact, along with the idea that we received over here. So in case did, the paler already contains an idea that will be overturned by this one. So this way, we are now having a new object in the given index which represented our search result. Now that the contacts is being mutated, we now have toe right the content of the file, and we have a function called this dot right toe file on. Once that is done, we can now simply written the value off this particular objects I'm going to simply say, your return on. We don't want to return the reference to the actual object, so I'm gonna return a shallow copy off the same thing. So tripled out this start Contacts off Index on our function update. Fel is ready. The next function is for the patch some right here, a function called abd it partially. Once again, it's going toe received the same perimeters. So I'm gonna copy this part. Close the bracket. We also have to actually get the index off the element that we want toe update. So this line, all soul's good. We have to check if the search was successful then only we have to do the patch. So I'm gonna baste it and then close the bracket for the same. However, we want to read in the current values off the search to object. But overrating the values in this particular contact. So all have to do now is to say, distort contacts off index that the search result is equals to a new object that should contain all the values from the current object which is nothing more. Distort contacts off index. But it should over right? Whatever is coming in the payload which is nothing but tripled out contact. And now, since the distort contacts is manu plated or mutated, we have to write to the file. I'm gonna say this start right toe fight and then return the modified variant off that which is currently kept in this one. So the line here is identical to this. I'm gonna copy and paste the same thing over here. So we there's no our update. Partial is done. One last function in the service class is toe delete. So I'm gonna write a function called Delete by idee, which takes an idea the perimeter to deal it an element in the member variable the area. We have the first search and get the index, which is same as this. So I'm gonna copy these two lines based over here on Glenn. Close the bracket for this and to delete the element. We're going to use the slice function. So we're going to say this start contacts, which is in a day. But I had a function called spice, where we need to supply an index on in their index. How many elements you want to delete, which is not the one we want to just do it One element. And after the leading, this is going to return on our day off. All the deleted element on since you were believing only one element. I can collect that one element that is dilated, which is at the index zero to a variable called C and then I can return that see, so that it can be given a the response back to the plane so I can say you're return. See? But no doubt this has happened only the memory. But in order for us to update this into the file, we have to call this function this dot right to fight. That's a space that over here on our belief by idea is also ready Now that our salaries functions already. Let's motor the controller first. Let's right the handler for put someone at the rate put remember, it's gonna take the i d. As part perimeter, so that's important. And then I'm gonna write a function called Update where whatever comes at a part perimeter , I wanna assign that to a variable seltzer at the rate for um off. I really on. Then I'll declare variable called idee, Andi. Then I'll also say at the red body, which is gonna be assigned toe a variable called body and now we have to check if this idea the valued one and squander that can make us off this functions, I'm copied it and then paste over here because we want to check if this idea exist, then only we want to do an update on the way you do. An update is distorts surveys dot update full, which takes idee and body as the perimeters of body contains actual contact distance. This comes back with the updated data on I can simply say return, but if the idea is not for me, I'm gonna simply say through a new not for an exception Over here on our update. Functionality is ready. Let's also the patch. Andi, I'm gonna right here at the rate patch again. The parameter is going to be a same thing, Colon, I really know that this idea itself can be something else. If you want to give, I'll say patch instead off update. I also received these two parameters, except that the body may consist off. Partial data need not be full data. The function is pretty much the same thing as the previous one. I'm gonna copy and paste the same thing over here. However, instead of calling the update full, I'm gonna call the function called Update Partial. On the rest, all is going to be seen. One lost is the delete handler. I'm gonna take here at the raid in it. The perimeter is still required. So colon idee the function name I'm gonna call it does delete contact or just to delete also is fine. And then I'm gonna type here at the right bottom off idee. Pass it on to variable called idee. There is no requirement of reading a body because delete on get do not have a request body . We just had to check if this exists, we want to do it. If it doesn't exist, we won't actually throw a not for an exception. So I'm gonna copy this in that section based over here. But instead of calling this, I have no call Dill it by idly and then supply the i. D. So with this now, all the three tasks off the assignment is completed. Let's go on Very for the same thing. First, let's go and get the data Seawater. The data on the data is same One is we know to Ishaan Trees, John. Know that name? Isham on the email issue, amit example dot com I go and send this detail where I'm tryingto change the name toe full name on email, toe a gym, a lady if everything is OK. I should get actually updated version. We can go on, verify the same thing over here on. Send this request once more and you can see it's been updated over here. Notice that the I. D. Has bean either their string here. But if you are very particular about the data type, then you can go back to your service function where we're actually adding that idea over here. This is the idea which came from the request part perimeter. I can convert this into an integer before I can pass it on over here so I'll type your ID equals toe parts into off idee. And if I go back to the postman, send this put request once again, you can t know that the idea came back with an integer off course. I can verify the same thing over here. Also not. I want to send the patch requests where only the name off this person I'm changing from John to John Doe. The email should remain the same thing. So if I click on send, you can see that we have updated the name successfully while keeping the email as east. We can also go back here and then very funny. So it was the previous I'll put John. But if I send a request now, you can see this John Doe when the email is intact. One last thing is to check the delete operation. So I go back over here. Three corresponds to John's record. Deleting it first earn should be successful, and you can see it is successful so you can go back here and then verify the same thing. Notice that the Johnson card is gone. However, if I go back and deleted again, this is going to be a four, not four, because there is no contact for I d tree. We can also very further working off this for not for for puttin patch also. So if I type here, for example 22 I don't try to send it supposed to come back with for not for because I did 22 is invalid. Likewise, if I go to the patch, let's give it us 33 click on Send since I lead 33 is invalid. Patch also comes back with four, not four. So this is my solution for the assignment. I hope you also would have completed the past in a similar fashion 18. Overview of Nest middlewares: middleware is a function which is called before the road handler. Middleweight functions have access to the request object response. Object on the reference your function, generally called as next which can be used toe in with the next middleware function if available, are the target controller in the applications request response cycle. If you are familiar with express Js, then a nest middleware is identical. Toe Express. Middle Way America can be used to execute any kind of court before the request, which is the actual controller. It can also make changes to the request or response objects. Our end the request response lifecycle itself. If the middle does not end the request response cycle, it must call the next function which passes the control to the next available middle. Where are the intended controller? Most common Use off middle where are logging the incoming request Details. Adding additional. Http response. Headers Checking for authorization header In the request, you may implement a customer anywhere in either a function are in a class with an illiterate injectable decorator. The class should implement an interface called ness middleware, while the function doesn't have any set special requirements. If you're implementing the middle where, where? A class. Then you may also ask for additional dependencies in the constructor, just like how we did in the case off controllers, although in the documentation it is mentioned that the middleware class must be decorated us at injectable, there is no place for a middle way in the act model decorator like services. Instead, we set them up using the conficker function off the model class. Now that we have a fair idea about middle bit in the next lecture, let's create and set up a middleware toe logged the incoming requests for our contacts controller. 19. Class as middleware: in this letter let's create a logger middleware which is supposed to love the details off the incoming request onto our console here. So I kept my postman on the terminal side by side so we can check if the request is being loaned as off. No, you can t I have a request here for locals 3000 clicking on send I will get the response here Hello world But I don't see any response on the console. Similarly, if I go to the local host 3000 slash contacts click on send I am getting the details over here but there is no response. This is what we want to address using a middleweight. So let's go to our were scored here on in the SRC I'm gonna create a new file called lager middleware dot es inside which I will export a class called lager middleware To do so. I'm gonna click on this icon and type logger dot middleware dot t s first enter Onda. This is gonna be a regular JavaScript or typescript plants. I can simply say export class and then it a pure logger middle way. But importantly, you have to say implements nest, middle way. You can see that they didn't auto import option. So I'm going to click on that and it comes from next J slash Common. I have to open the curly bracket for the class definition. And still I see one error because implements interface means you must implement the methods in this you can actually go to the error and then press command out on macintosh are controlled out on windows and that's going to give you the quick fix on. I can press, enter toe, implement that particular interface function. And what is the name of the function here is very important use which takes three perimeters request response on next, which is nothing but a function You can change the perimeters anyway. Here in the previous doctor mentioned that the nest middleware is nothing but the express Js middleware. So the arguments here off type of request and response and this is just a function so I can go in type your request here. I know that there are three different requests. The one that I want is I believe, the 3rd 1 here. I cannot see completely here, but I'm sure if I click on this. It's gonna show auto import from express interface. So that's what I want and you can see Regarded from Express. This one is also going to be from express module. The data type is called response. Once again, I have to select. I believe that 3rd 1 you can see that are to import from express. And the 3rd 1 is just a function. There is an interface called function. It's part off core, nor J. So you continue type here, function on that That's gonna be okay by declaring it off. Appropriate type via score can give you some interest, since that's the reason why we changed the data type. Otherwise it is. Okay, I'm gonna remove this throw statement on this is where we're actually going. Toe either check some details in the request or modify the response and finally called the next to function. Now, if you don't call the next function, then the client will get the response from the middle itself. The client request will never reach the actual target controller. Since we want to just a lot the details of the request we can simply type your console dot log on, then probably I want to print the method. That is the it's TDP method of the request. I can say arctic you dot You can see because I declared Arctic you off type requests we escort is ableto give me a list of all the possible attributes and I have to take your method that's going to give me Is it a get request? Posted questions to Trump. I also want to bring the actually oral being requested. So I'm gonna say are acute are you are? And likewise, you can give a couple of other parameters. For example, request dark. I believe you can say quietly which is actually going to give you the list off quite distinct perimeters, if you have similarly, you can all just a request our body, in case of a put turn post methods. I just would like to give the method and you are nothing else. I'm gonna put a semicolon. I'm not gonna make any change to the response here. Although I received three parameters arrest warrants, I'm not going to make yourself that at all Now I think I don't want toe end the response over here. I'm gonna call the next available. Middle if there is no other middle very simply going to pass the control toe the actual target. The client wants to go toe. Now that we have our longer middle class ready, we can now register this with our at model are one of the feature model like the contacts model. In this example, I want to register my lager middleware with the APP model ts. So I have already opened the out model ts over here on the north that I did not write this as an injectable. It will still work. How we were in the documentation there mentioned that you mark this as injectable. Although you market at that injectable, you're not going to make an entry in the provider section like the services. But instead you're gonna come here and then override a conficker function. Ofcourse, the conficker function is because off an interface, I'm gonna write your implements nest model. Next module has a function called configure. That is why I'm getting another. Once again, I'm gonna click on the debtor message press commander because I'm on Mac press enter. You can see that we got a function here called Configure the perimeter off that is called consumer off type called middleware. Consumer noticed that it is going to be imported from next Js common, but we already have in SJs comin over here. We can simply add this to that list and to do so, I'm going to simply remove this onda press command dot and say add middleware consumer toe existing import declaration from Agnes j slash common. Also, we don't need this true statement because we're actually going toe implement the court over here on the only thing that we do inside this conficker at this point in time is we take this consumer and Cala function called Apply, which takes a middleware as a perimeter. Now that's how you register remedy were with next year's to do that. Let's type your consumer dot Apply on passing a list off middle wears separated by a comma . It's basically a battered. You can see her. I can supply any number of middle bits. Where Emily, where can be a function are a data type. Nothing with a class. What we want to do now is toe supply our larder. Middleweight, all I have to do is to type in the name of the class, which is lager middle, and now our middleware is register with next year's game may also have to specify for which are out this longer. Middleware should work, so I'm gonna just type your dark far, wrote on then specify a list off road configurations on the road configuration here can be either a string or it could be a around conflict object which contains part and method, or it could be simply a controller. For example, I can tell you're contacts, controller and all the request to the context. Controllers will now be applied with this middle bit. Let's put a semicolon here since my file is automatically saved. Next, jets has automatically restarted the server. Let's make a request toe Locals 3000 which is not handled by context controller. So I deliver electric on this. I should not see any logs over here, So let's see that and you can see that we got the whole lower. But there is no all put here. However, if you go to the local owes 3000 slash contacts which they get require split consent, I got the output. I also got an output here on the console that says Get slash contacts. Let's check it out for the other one We're in, Say contacts likes to I got my response over here as well. I can see a response on the console log like where they forgo the patch. You can see that we're going to get the output over here on patch for which you are one. Last day they put And when I click on that, I should still see the log related to the request made. If you want, you can also go and say, What is the body? Let's give it a try. I go to my lager middleweight, and then specify here request dot body Go back over here. Let's send a put request on. You can see that this is the body which I'm sending in the form of JavaScript. Object. So you ready for Go to the patch, click on send the same thing we get here in the form off JavaScript object. We're sending a Jason string year. What? We got a jealous keep object. Suppose I want the logs to be printed only in case off. Put post and patch and not for other requests. What I can do is I can goto my at model ts on Instead of giving this contacts controller, let me commend this out on then give your dot for roads and then give a list off route in for object on If you see that far roads If a control click or command click on this, it's gonna take me to the definition. You can see that there is a road in for I can supply. Previously we supplied a data type like contacts controller. But this time I want to supply the route in for rooting for is nothing but an object that contains I thought the string and then a method off type called request method. So I like to specify what it apart. So let's go here now on then I'm going to give a couple off road in four objects. 1st 1 that it is supposed to intercept all the contacts. You are requests only for matter and then I can say request method dart All delete. Get head. Choose one of the http request that you want to handle. Since I mentioned earlier that I want to handle post four turn patch, I have to give one by one. So this is one road configurations. I'm gonna put a comma and then press our shift. Don't at all on Macintosh option Shift down arrow. You can see it's get duplicated again. I'm gonna do the same thing on one of them. I'm gonna change this to say Post. One of them is going to be put on. One of them is going to be patched. Let's go to the postman and then see if it's going toe. Give me any old put for put so off course put should be intercepted over here. And I should see a log related to that. And I don't see here because it's not for slash contacts, but it is Far slash contact slash star. So I'm gonna go give here for put method. It's gonna be context Last star for Patch. It is gonna be context Last star. But for posters just going to be contacts. Let's go back to Postman on check What happens? Know that the next day, sir worries we started, so I'm gonna click on send Andi. You can see that we gotta put slash contacts. Last two, we got the paler. I'm gonna go to the patch. Send it across. You can see that. I got that. I don't have a post request, but I'm sure you're gonna get that. But if I'm going to send the request toe contacts slash to We got the output here, but we don't have any logs. That's how you can filter certain requests toe be intercepted by our middleweight. You can also read the documentation for various other regular expressions that you can use . But this is how you can create a class based middleware on register with your APP model. In the next lecture, let's see how we can create our cars. Middleware cars stand for cross origin. So sharing that means if you're resting, point is being accessed by some other third party JavaScript climbs. Unless you specify that it is OK for other people to access by the four. Http protocol doesn't permit this. So in order to enable that we want to add additional headers, let's not worry about the cars itself, but we will see how toe enable cars in case if it's required 20. Function based and third party middlewares: in this lecture, let's read a function as a middleware on the register, the same thing with our model to do so. I'm going to go toe my SRC folder rightly can say new five on the name of the file. I want to give it US cars dot middleware dot ts and I just want to export a function and I can read the function either in the form of an adult function or a regular function. Let's prefer to use the arrow function. I'm gonna say you're export const Ongoing export a function called enable cost, which is nothing but an arrow function on another function has a bunch of parameters. In this case, it's gonna be request response and the next and then we're going to use an arrow and then a curly bracket on. This is where we have to actually do the job off modifying the response headers. And if you want to interlace since for request response, then better to declare that with appropriate data type. We know that Arctic you is nothing but off type requests. This is going to come from express. I pressed. Enter again. The response is also off type of response coming from the express model. So press enter. Next is just a function. I'm going to say your function which is an interface which is part of the core Norges. We don't have to import anything now that I have the request response and next number at the end, I have to say next that is going to be done first. But before that I would like to add some response headers. So I'm going to say rest dog header which takes a name and value. So the name is basically what is the head of name that you want to give on? As for us, cross our agenda. So sharing its concern, we have to give at least a three off them. Number one is called access Control although origin, which follows only certain origins toe make a request to our restaurant point Most of the time, If you're creating an AP which can be accessed by anybody, you should give star alternately. You can give a list off I peer doses which are white listed. The 2nd 1 is access control, although methods which is a list off a load. Http Medals from the client for example, you may want toe restrict the clients toe, make only the get request and not post put or delete. The 3rd 1 is an optional one, which is the access control although headers which can restrict a certain headaches Otherwise all the headers are a load. But with this now I can say only certain kinds of headers are alone Let's go on out one by one. So the 1st 1 is basically access control alot origin like this on the value for that I'm gonna give it a star You can just give a list of I peer distance which are separate, is in comma. I'm going to duplicate the same thing by using option shifted down Arrow are all shift down arrow on windows on the 2nd 1 is gonna be the methods on the Macuxi is going to be a list off methods. I want to follow all the metrics possible so I can say you get post put deal it on a patch . The 3rd 1 is access control alot headers on you can give a list off all the Lord headers If you don't give all the headers would be a load like star But if you want to restrict the plane to send only content except on authorization, you can give it like this content dash type. That's one header comma, I can say, except and then probably authorization with this. Now our enable cars which is a function you can see right translated. The function that's assigned to this variable on that variable is being exported from this particular model. Now I can go and import this and register the same with our model. The registration process is same as the previous example. So I'm gonna go to the app model ts. I can have one or more middleweights in this list. They're all comma separated. This is going to be the 1st 1 Andi, I can give a comma and then say enable cars as the 2nd 1 enable cards have to be imported. So I'm gonna press command dot and then say imported from our cars dot middle way. So whenever a plane makes a request toe, any of these your girls lager middleware is the 1st 1 to receive the request. Once this has done its job, it's gonna call the next to function, which is nothing but the next middleware, which is enable cars and enable courses gonna actually add those additional headers, calls the next function, which is supposed to invoke the next imagery. Where, as you can see, I don't have any other middle well because of it. It simply goes to the intended controller. So let's go and check it out. Let's go to the patch on. You can see that this was the previous awkward we had got. Not only that, we have the response body here. We can also see the response headers and in the list of head. As you can see, there is explored by added by Express that also content type, which was nothing but a decision by nest urges. When we returned an object, so had we returned a primitive that could have been probably text a slash plane. Similarly, we have some content land which was automatically calculated based on what the length off this entire response on their a few more like E tag and the date and connection this time electric consent because we're sending a patch request to contact slash star, we should see a lot over here and then additional headers. Let's hope that's gonna work like that. Click on send So you can see that there is a love over here on the additional headers that we added over here. So the access control Hello origin star A load methods These are the methods that I gave and then there is a alone headers Similarly, if I go to the put request over here on, then click on send You can see we got a love over here as well as we got the response. If you go to the response headers once again you can see that we are seeing these additional headers over here. However, if I goto the get request and then send my request neither I see a long not I see those additional headers while we are able to write our own middle ways using either a class or a function There are a lot of third party members are also available For example toe enable course there is a middleweight called cars on toe enable security related additional headers. There is a middleware called helmet, for example. If I open chrome and look for helmet middleware, you can see that we are taken to this helmet Js where you can get some documentation. They basically say, Do an NPM install on, then start using that helmet on. If you want to use this in our application, we can simply do an NPM install first important in our APP model on then just I This helmet in the list off middle best that were already register. So let's give it a try. So I'm gonna go back toe the terminal over here, open a new tab. So I'm gonna go into my desktop nest providers Demo. That's the project location. I'm gonna die pure NPM. I are installed and then type your helmet. Chris Ender, This is going toe not only download that our North Models folder, but also acts that entry into our packaged or Jason. Let's go back to our server. Longs on go to the visual studio code. And now this is where I have registered a couple off middle. It's I can now say that I want a middleware from helmet. So first of all, let's import helmets or to import helmet you say import star as helmet From off course, the model name is called Helmet on. All have to do now is toe find its location. Typically, death suggested that you make that at the 1st 1 So I'm gonna go type your helmet and then put a comma with this. Now we have 1/3 party middleware, one class based middleware, one function basement away. Let's go back to our postman and see if it works. I'm gonna go back toe the postman here, send a request to patch and see if I get additional headers added by helmets on you Click on the send on. I got another. It says that it appears you have done something like Abdullah use helmet, but it is supposed to be done like this, which is not a motor function Call. Let's go back over here and add a bracket here. So we're calling the helmet function, which returns them everywhere. And that middleware is gonna be registered without a model. So let's go back quickly. Send the request on you can see that I got my logs. I got the headers that I added, which is the cards headers. But you can also see there is this ex Deena's prefects control X frame options, strict transport security. Exe, download options. Ex content of options on X X SS Prediction. So all these are additional leaders added by helmet. So this is how many ways can be practically used somewhere down the line. In the subsequent lectures, we're gonna create another middleware onda, that Middlebury supposed to check the request header for authorization tokens. On that tradition, tokens were generated when the user logs in. So if it'll we have toe add modify our delete our contact details, the user must be longing on once they use a lodged in, the user gets a token and we will read a middle way to check if the request contains the header called Authorization with a valid token. So that's all for now. See you in the next lecture. 21. Standard exceptions: next comes with the built in exception layer, which is responsible for processing all unhand exceptions across your application. When an exception is not handled by your application called, then it's going to be caught by this layer, which then automatically sends an appropriate user friendly response in Jason Format. To understand the same. Let's take an example. I have created a brand new SJS project. It's called Nest Exceptions Demo. I haven't made any changes to this particular application, So when I make a request toe local host 3000 I'm simply going to get Hello World. Let's check it out. But let's assume that this is a secure resource and in order to access the same, why are the header I have to send here something called authorization talking. So in my controller here, I want to check if the request comes with a header called authorization. If it is missing, I want to throw an exception. But if the authorization had is present, usually it will be in the form off encrypted text. We want toe Take that. We want to decrypt the check if the user is a valid user and then we want all of the either to access our resource. In this example. We're only going to check if the header contains the authorization token. If it is not present, we want to throw an exception. So the first thing we have to do is tow access. The http requested a on to get the request object itself. You can ask for the dependency injection here, So the way you can do is at the rate R E Q, which comes from this chase common and then assigned to a variable called Arctic. You are request or whatever you want. Similarly, if you want a response object, you can declare a variable here and then a noted the same using moderate arias decorator. So let's come down here and then get the actual header value that soliders let out equals toe request. Our header on the head of that I'm looking for is authorization if this is not present so I can check here. If not ought, then I simply want toe throw an exception. You can throw any exception you want. For example, I can simply say throw new editor and then supply another message. Like for example, authorization header is missing in the request. But if the authorization token is there were simply going toe give the actual response. Ideally, we should check with other authorization. Token is valued, but that we will do in a different section right now. We want to see how the exceptions are 100 see them throwing it and not handling in our application. This is gonna be handled by the default exception layer I was talking with earlier. So let's go and check it out. So when I make a request to know your consent and you can see we got a Jason or put, we got the state escort as 500 internal server error. The state of school has given us 500. Message is Internet server error. But as you can see that I have given a message here, that is Authorization Header is missing in the request that did not come. So instead of throwing some arbitrary exception or error object, So let's convert this new editor in tow. New http exception. So the its GDP exception is again coming from nest Jay's common, but that takes two parameters, not one. There is a message, and then you also have to give the it's TTP state of school, which can be either a number are there is an http status plants which provides an alias for each of those intercourse. So I can simply say that this is gonna be a 403 because the user has not supplied the authorization other and it's supposed to be forbidden. So let's go and check now. What happens so earlier? I did not get my custom message, but now I'm supposed to get the actual custom message. You can see that we got the messages. Authorization headed is missing in the request. We were If I go to the header section in the request, send authorization as the name. Any value doesn't matter. I'm just going to type some gibberish value here and then click on send this time because there is a header present. I'm getting the actual all put on not an exception. But its GDP exception is taking two parameters here, the 1st 1 being the message. We have given a string, but if you carefully observed the actual signature, the response is nothing with a string are called record is nothing but an object. It can be a bunch off name value pills, for example. I want to give more detailed information about this so I can remove this from here. Let's say I'm gonna declare a variable called Yara and send the same here on Let's create the variable. Let's let Err equals to an empty object. And inside that empty object I'm gonna give, say, for example, court is 40 t This is the same thing as what we're sending. But of course, you can give a different name. Value pairs over here, for example. The default text was given us a message. Instead, I can say description and then give some value over there. Or if you want to have a description as an object, you can do the same thing. For example, I'm gonna cut this from here. Make that as another object. A shark message probably simply say is forbidden. Onda. Probably a longer description probably may give this entire message. You can also add additional stuff like, for example, a time stem, which is nothing but the date don't know which will give the times time. But if you want a readable date value, then probably you can say new date and then say dot to I s o string and that's going to give you a proper date value. Let's give it a try. I have to remove the authorization talking from here and then click the send. Now you can see we are able toe customize our response using the standard http exception. Plus, next year's provides a lot off sub classes for this http exception. Plus, here is the list off all those exception plus, is that you can make yourself. We have already seen, not phoned. Exception. You can also see that there is already a class called for but an exception which we could have used in the next lecture. Let's see how we can create our own user. Different exception plus. 22. Custom exceptions: In many cases, you will not need to write custom exception classes and can use the building nest http exception. As described in the previous section. If you need to create customized exceptions, it's a good practice to create your own exception hierarchy, where your custom exception classes inherit from the base. Http exception. Class With this approach, Nest will recognize your exceptions on automatically taken off the error responses. To understand this custom exception classes. Let's assume the user is going to make a request supplying a filing as a perimeter. And in case the file exists, we're going to send the data back to the user. But if the file doesn't exist, I want to throw an exception. But a custom exception called Fine Art formed exception. So let's go and write their handler for the same. I'm gonna write a function called Send File, which takes finding as a perimeter off type string. And here is where I want to get the content from the file and then return the same. So obviously, toe read the content from the file. I need the file system model, so I'm gonna go and type your import star as Fs from FS, and now I come down here and then say Let content equals toe efforts dot reid File Sync And then the fine name is nothing with the fine name sent by the user past that. As an argument included, the file exists. It's going toe written the content over here. But if the fight doesn't exist, it's going toe throw an exception. And since we didn't handle the exception here, it's going to be handled by the default exception layer on that's going to give the adult status as 500 description as internal server error. Let's give it a try, so I'm gonna go on type return content. We no need to map this function toe a u r l Some new type here. At the rate get the euro is going to contain the fine name. I'm gonna take your colon file name and that is supposed to be mapped to this variable. So we're gonna type your underrate bottom and then supply that file name, which is nothing with the You are a segment that is now being ascent over here. So whatever the find that the user is asking for, if it is not dead. We're going to get an error. Let's go and check it out. I'll stay here. Locals 3000 slash and then say we know dot Txt Because the five you know Doc txt doesn't exist. It's going toe. Come back with an editor and you can see edl is internals. Are were better. I never go to the terminal over here. You can see there is an error that says no such file. All directory open, we know dot txt and that's caused by efforts dot reid File Sync. And since this is not one of the standard exception, nest automatically genders. The response. Jason, which contains scored 500 status message as internal server error. But this is where I want toe actually create my own exception. Plus and throw an object off that so to do so let's go to the SRC folder, create a new file. Let's call it us file not found dark exception dot t s and then you're gonna say export class file not phoned. Exception extends its GDP exception exceeded. The exception comes from nest common, so we'll import the same thing and all I have to do here is toe call the super class constructor by supplying the message under state of school. Since finite phone is something to do with their not found, so we're gonna send us to the score. That's for not for. But I should be able to get some information which I can for the positive that it's GDP exception as message. So I'm going to read a constructor over here which probably gets an error. This could be a string are it could be an object. I will simply say any indicated the user has not passed. I can also assign some default, probably can't say file not found. And then inside the constructor, I simply have to say super and then I supply err on then for not for the incident, for not for you can also say Http status and then say dot You can see that there is not phone which represents former for. Anyways, Now that I have my own exception plants, I can go to my APP controller where I have this court, which might probably throw an exception If there is no exception, I would like to return the content, but if there is an exception, I want to handle that. So to do that, I'm gonna go and cut this. Now, put a try catch block over here and inside the try block. I'm gonna pace this, but in the catch block, I get the error object, and then I want toe construct my own error object and then supply that toe. Finer foreign exception, for example, I can say let at r equals toe an empty object. And then probably I can say time stamp. It calls toe new date dot to I s o string, like we did in the earlier case. Probably. I can also say message equals toe eat out message. And that's gonna be the text message I may get. Of course, this is not equal stupid. That's colon. And now I can say here through new file not found exception which takes an editor object. I have this, er that I'm gonna supply to check both the scenarios. We will cleared one file under our project military. When I access that file, I should get the content. But if that file doesn't exist, I should get the details at her message in the form off Jason. So I'm gonna create a new file over here, I'll say, we know dot Txt Let's have some basic information like my name, my email. Let's say I know want to access this u r l on the sea. But the scenarios I come down here how this we know dot txt Now, if I click on send, we should get the actual content. But I got this in what's called a buffer format. I want to get the textual value. So all I have to do is to supply the including here in the perimeter, off refiled. Think I'd say that this is a postulated as utf eight onda. Now I am supposed to get the content in text format. So let miss any day game and you can see we got the output. But if I type your say for example, we know dot j pick I don't have a file called you know dot jp on this should give me an exception. But this time it's supposed to be the Fine art fund exception the State Escort is gonna be still for not for, but I get the details here likes times time on the actual error message also. So this is how you can create your own custom exception classes. All your to do is tow extinct. The building standard http. Exception plants and then pass on the information to its constructor. 23. Exception filters: nest comes with a built in exception layer, which is responsible for processing all unhand ill exceptions across the application. We saw both those standard exceptions and custom exceptions in the previous couple of lectures. While the building exception filter can automatically handle many cases for you, you may want full control over the exception layer. Sometimes, for example, you may want to add logging or use a different Jason Schema based on some dynamic factors. Exception Filters are designed exactly for this purpose. They let you control the exact to flow off control on the content of the response sent back to the plaint. In this lecture, let's create an exception filter that is responsible for catching exceptions, which are the instance of the http exception class on implementing custom response logic for them. To do this will need to access the underlying platforms. Request and Response object, which comes from express model, will access the request object so that we can put the original you are early on. Include that in the logging information. We'll access the request objects so we can pull the original. You are all on include that in the logging information and we lose the response object to take direct control off the response that is going to be sent using the response toward Jason mattered. So the first thing we have to do is to create a class that implements exception filter, which must implement a function called Catch. So let's goto our SRC folder Onda create a new file on. I'm gonna call this as my custom exception dot filter dirty s a press enter and then I'm going to say export class my custom exception filter implements exception filter. So as you can see exception, Fielder comes from this chase common Andi. It also comes with an error because the class must implement the method defining this interface so you can go here and then press command dot on mac control dot on windows and leaners. You'll get that implement interface suggestion. Select the same. You can see that the catch function comes with two parameters. Number one is the exception. The exception is going to be the object that is going to be received depending on your configuration. The host is an object off type called arguments host, through which we can get different context. For example, if you're using this in an http or a Web socket. They're depending on your applications requirement. You can choose the Pont takes and get the relevant information. So we're going to see that in eminent. But we don't want this kind off imports. I'm going to remove this from here bigger and other, saying that arguments host is not defined. So we simply have to press again, commander, or controlled out. And then add this to the already existing nest Jay's common imports. One more thing that we have to do before we actually called our logic is to say what kind of exceptions this filter is supposed to handle on. Do we need to do a mapping with an exception? Plus, by using accurate catch decorator again, it is coming from the nest Js common here. We're going to specify one or more exception data types. Right now, I want to handle all kinds of standard exception. So I'm going to simply say here http, exception. Which means that the object I'm gonna receive here is always going to be off type http. Exception are one off its subtype so we can start over, go and say that this is nothing but an http exception. We don't want this throw statement, but instead we want toe respond to the user with their customized Jason information. So to send the actual response directly, we need the response object which can be obtained from this particular host. So the way you do is you first get the context. So I'll say here const City X, which is not the model context on their host to dot switch on. You can see that there is a two x TTP to RPC, and then there is a two web sockets. I'm going to select that to Http Now I got the context and from the context, I can get the request. I'd say city extort get requests like this, and then it's a constant response equals two city extort. Get response. I noticed that the return barely off. This comes as an ordinary object. So when I type your arctic your dot, I may not get any intel. Instance. However, if you want to get the intelligence, then you may also say that the request, whatever comes, must be costed toe the requested A from express. So to do that, I'll simply have to give here the syntax, the generates that I'm gonna use and say that data date that is going to be used this request coming from Express. You concede that the request is coming from different interfaces on the one that I want is from express the 3rd 1 here the same way I have to do it for this as well. This is gonna be the response on. Once again, Respond is supposed to be taken from the Express. Now, if I say request, start and you can see I get the intelligence response dot I get all the functions and attributes of the same. Now let's prepare our actual response to be given to do that, I'll say rest our status. This is the stages number like 200 fortnight for etcetera. I just want to borrow that from the It's TDP exception I got so I can simply say status, which is nothing but exception dot get status. So this will automatically get the status from the got an exception. But then I also want to send a Jason or put So there is a function called Jason, which takes the JavaScript object converts that into it. Jason acts the http header called content ICT application slash x Similar. That's value. So here is where I want to say times. Time, for example, is nothing but new date dot toe eso string like we used earlier. We can also send some message back to the user. For example, the message may be coming from the exception itself. Exception dot message. You can also are the original You are that caused the problem so I can say her part is nothing but are acute or you are on any additional court that you understand you can add here. So I lied one last, which is nothing but does status scored exception dot get status. Let's put a semicolon over here on our custom exception filter is ready, we know have to tell the next year's when to use the same. We can use it at a given function level or a handler level. All we can use it at the entire controller level are if you have multiple controllers and you want that to be used across all the controllers, then you can specify the AP level. So let's check one by one. I'm gonna write one simple handler here which is nothing but a hollow message and simply going to throw a forbid an exception without doing anything. So I'll say hello. Throw new forbidden exception. Remember, this is one of those standard exceptions on I'll simply map this year, part called Get Slashed. Hello. So if I go to the postman and then say here slash Hello here after local host Fritos and Slash this is coming back with an exception, because I'm throwing a forbid an exception. There is a state of sport 40 tree. There's a message forbidden. The same thing is visible here Also, however, I want to make use off this custom exception. Filter on to do that at a unusual handler level, you can simply are here at the rate use filters on then supply one arm or filter class are filter object so I can stay here. My custom exception filter Neiffer. Go back and send the same request again. You can see that I know how the times time, the message. The part on the state of scored all of them in a custom Jason here. However, if I go and change from hello toe little for example, john dot txt and the file doesn't exist. This is the other message we're getting. However, if I want to make it off my custom filter across my controllers, I can go to my court and then shift this line from the function to the actual class. So if I go back over here on, then send it now, you'll see that we get the exact same style of response even for this request. Similarly, if I simply access local host 3000 without the authorization token, you can still see that the details are in the same style as the previous one. So our custom filter is applicable for the entire controller. If I have a different controller and in that controller, I have a handler function, which throws an exception. This custom filter will not be applicable. If you want our custom exception filter to be applicable globally toward the application, Then we can go to the main dirty years where we have created our application as AP, and then we can register Abd art, use global filters and then supply my custom exception filter. But this one doesn't take a class. It takes an objects allowed to say your new my custom filter with the brackets as constructor. Now that I have you in the my custom exception filter globally here, I don't need to give it in my control load so I can get it off this from here. So I'm gonna delete that line, go back to the browser, make a request again. You can see slash 3000. I get that exception in this time. I goto john dot txt, which doesn't exist, and others are in the same style. I also go toe hollow, which is throwing a forbidden exception. The same thing I get once again. One last point I want to mention here is that except in the main dirty is were we created an object here. The rest of the places, like in the control of classes or in the handler level regionally give the class. However, we can also given object. But according to Nestor documentation, we have toe prefer applying filters by using the classes Insel off instances when possible , it reduces memory usage since nest can easily reuse instances of the same class across your entire model 24. Overview of pipes and using built in pipes: in this Jays pipes have to typical use cases transform import data toe the desert form, for example from string toe indigent are valued input data, and it's valid simply passed through unchanged other ways through an exception when the data is incorrect. In both cases, pipes operate on the arguments being processed by a controller. Road handler nest into possess a pipe just before the method is invoked on the pipe receives the arguments destined for the method on operates on them. Any transformation are validation. Operation takes place at that time, after which the route handler is involved with any potentially transformed arguments. Next comes with a number off built in pipes that you can use out of the box. You can also build your own custom pipes in this lecture. Let's see some of the building pipes to understand the same. Let's create a new project. I'm on my desktop. I'm going to issue the command nest. New messed dash pipes Dash Demo. This is going to create a brand new project. It's gonna ask me a question. Are you going to use NPM? Are young? I'm going to say NPM now that the project is really Let's clear the screen and city into our project folder, which is nothing but Nestor Dash pipes Demo. Start the development server by typing NPM. Run, start on, then colon Death and also open visual studio chord in the same project directory. Someone open a new tab. Check if I'm in the project. Military on I'm not so I'll say City Desktop, Nestor Dash Pipes Demo and then type called DOT. This will bring up the Visual Studio Court that's full screen and quickly make some changes to our APP. Controller tortillas will add the controller road called contacts. Let's get it off all the court inside this class and under a copy and paste in our A off contacts over here and write a function called Get By i D. Which takes ideas a perimeter and I'm supposed to return one of the contact based on the I D. So the idea is going to come from the You are a segments I'm gonna take here at the rate get slash colon I d. And this is something that I have to map to this whatever that is. Part of the you are a segment we can accident by using at the rate bottom and then take the name off the perimeter, which is colon idea given here. That's what I have to give. Whatever I have passed, that's going to be the suit into this variable. Now let's say if this particular idea is phoned in this Ari, we will assign that to a variable. Let's call it R C one equals toe the start contract. Start find we get one object at a time and then we're gonna check you see that I d triple equals toe idee. Then we will assign that to see one. And if C one is undefined so I can check here. If not, see one, we will throw an exception called new, not phone exception. This will give you for not for better, along with meaningful Jason content. But if C one exists, we're gonna simply say return See one. We have returned such a court earlier, but let's go and try the same thing in postman now. So I'm gonna type your http colon. Local host Colon 3000 slash contacts slash some number Notice that I have here 12 and three . So any number I type here I should be getting the details, however, when active consent it's coming back with for not for the reason, Father Days. Whatever I sent as part of the http request, everything will be considered as a string. For example, if I come down here and then just type a console log saying tight off Ivy ease and then I'll type your type off i d. You will see that on the console. It's going to tell that it is a string, whereas here digital numerical values, let's go make another request and see what happens in the console. You can see that it says type of idea is strength. So one of the solution we worked around earlier is that user double equals toe instead off single equals toe. But then the problem is that even for a string value, this will simply throw not formed exception. But I want to tell the user Dart strings are not alone. Only numerical values are expected. Let's give it a try and then check. When I type two here, you can see that it's going to work. That's because even though the input is still a string, we're actually checking whether string toe is equals toe numerical, too, but we're only taking the value, not actual data type. That's why we're actually supposed to use triple equals two, which is a strict comparison with value as a less data type. So if I go here and then look for Let's say is DF again, this airs De of his taken of the string on that string is comfort with each one off this, and eventually it's going to come back with another. On the other would be for not for not another that indicates it's an invalid input. So let's give it a try and check on. You can see that we got for not for, but not something that felt that it is an invalid data type. To fix this problem, we can make use off one of the building pipe called Parson Pipe on the way you can use is very simple for agday rate Param, along with the perimeter idea, you can also say here parts into pipe Parson pipe is defined in the nest, just common package. So we have imported the same thing over here. Now you can see it's going toe. Give another. If I do triple equals and supply a string. If I supply a number, it is received as a string. But this will convert that string into an integer and that is going to be given over here. So the pencil log should now say that type of idea is in number, so it's give it a try. First, let's send a valued idea. Let it to click on send. You can see that I got the data, and if I go to the console, you will see that it is type of ideas number. But if I go and type in a value off, let's say is dear and click on Send earlier we got for not for. But this time you can see we Garden Editor Court as 404 100 correspond toe bad requests, and it also gives me a meaningful message here that says validation fail numeric string is expected, So this is supposed to be a numeric string value over here. Let's take one more example. Let's say I have a handler in our controller, which can give me list off all the contacts, but I want to supply the page number on how many values that should come in a particular page. This is a very common concept called imagination. On the typically, these values are passed as quite distinct parameters. For example, contacts, question mark underscore Page equals to, let's say, one as a less underscore limit equals 2 10 Nowadays, I don't have a handler for this particular you are. Let's go and write the same. I'm gonna right here a new function that says Get all, which is supposed to take two variables. Let's call it a page on limit. However, the perimeters are nothing but underscore page on underscored limits so to us than the questing perimeters. First of all, it's our that they get. So this is a get handler for slash contacts, but they should correspond toe the quietest ing perimeter on just like how we used at the rate problem we can use here on great quality. The quietly decorator takes the name of the perimeter on notice that we have used underscored solar. It's parts that underscore Page, and similarly, we can stay here at the red quality and then supply underscored limit like this once again . Anything that you supply, whether it is quite a sting perimeter, are you are a Sigmund's are headers. Everything come to the store as a string on. But that is where I can also use here, the past in pipe. So I did a PR parsed into pipe and the same thing I'm gonna copy and then paste over here and just to check whether the transformation has taken place or not, Let's written an object that consist off page and limit their value and the data type. So I'm gonna take your page, Colon. I'll say value is nothing with the page variable. And then I take your type is nothing but type off page. That's nothing but a number. Our could be string if I don't use the parson pipe. So I'm gonna copy this and then paste over here, change the page toe. Let the limit Onda. Now we have a meaningful return value. Let's remove the last comma on. Go back to the postman and then send it request once again and you can see that we are able to get the value for page is one the value for limited stent. Both of them are number types. And if I go here, make this as two on 20 and click on Send. We do get this. However, if I don't supply a value, let's say I'm not supplying. Limit the consent. You can see we got 400 indicating that the value was expecting to be numeric. There was no value, so it is actually centre than none on. I'm getting that error. And this is where we can also use one more standard by which is called default value pipe. So I can say that, Hey, if there is a value missing for this page, we can tell that the page must be one. If there is a value missing for limit, I can say the default value is 10. To do so, you might have to use another pipe here called Default Value Pipe. But if you give a class here, the class is going to be instant stated by nest. But Nest doesn't know what value to supply, so instead we can take control and say Instead of supplying a class, we're going to supply an object so it's a new default value pipe off. 11 is going to be the default value in case of pages missing. Similarly for limit. Let's give a default value. Often I'll put a comma new default value off then. However, this is also going toe given Adul. If I ascended across, you can see that we got the same error. And that's mainly because the pipes are evaluated in the sequence. So when passed in pipe is developing value for limit, it finds that limit is not being supplied to. It is none on now cannot be converted into an integer. So this is very important for us to supply the pipes in a sequence. So I have toe give the default value first on, then the actual parts in fight. So I'm gonna cut that from here, faced the same thing over here. Now, if I send this, you can see that I'm only sending page not limit. But I do get a limit, which is nothing but 10. That's the default value that I have given. Similarly, if I remove this underscore page, you will see that Page also will come with a value off one, which is the default that I have given. Let's go back to a visual studio. You can t in both the cases. I'm using the pipes along with the decorator at the rate Param, or in the great quality, even for at the rate body at the red Header, you can supply additional pipes. However, if you have a scenario where the pipe has to be a player on all the perimeters off your function, then instant off giving it over here. You can also give it at the function level instead of perimeter level to check this out. Let's remove this past in pipe from both the perimeters over here and here we come and then say use pipes and then give an R E R A sequence off pipes. Either pipe classes are pipe objects. For example. I can stay here farce into fight, and if I go back over here, let's check it out. Question mark underscored. Page equals toe, say three Onda underscore. Limit equals toe fire. Click on send. You can see that we got the data type converted in tow number. With this approach, we may have one small issue. Nor does the parts in pipe is executed first, So if you have not supplied a value for underscored limit or underscore page, there is no default value at this point in time parts in type will throw an exception. Even if I have given this default value pipe. For example, if I go here and then remove underscored limit and then click on send, you can see it through an exception, and then we got in other 400. So in scenarios like this, using pipes at the method level may not be useful in some scenarios like this, where if the user has not given any value for I D. I really want to throw an exception. That is, when I can use the parson pipe at the method level instead of perimeter level. We will see such an example when we're working with custom pipes, but for no, I will remove this and then use the same thing at the perimeter level after the default values given. I would like to give the past into pipe same thing for limit as well. Next comes with six different pipes out of the box. There is something called validation pipe, which can be used for validating the inputs. There is part star pipes, for example, parts in pie parts bullfight forced a pipe and parts you yo I d pipe another one that we have seen so far is the default value pipe. So that's all for this lecture. In the next lecture, let's see how to create our own custom pipe. 25. Creating and using custom pipes: in this lecture, let's see how to create a custom pipe. A pipe is a class that is annotated with injectable decorator pipes should implement the pipe transform interface to understand the requirement off creating a custom pipe. Let's first create a handler for receiving a payload that consists off a contact object so that we can add it to this particular context at it. You will not be doing the functionality off adding the contact into the context today that we have already done. We want to see some basic set off valuations. So first, let's write a function. Let's call it dies, create contact it receives a body and let simply it on the body without doing any change and decorate dysfunction with other great post onda. This perimeter with a great body. So let's go to postmen. Send that post request and see what happens. So I'm gonna change this toe post. Remove this question mark on perimeters. We want to send the body raw on. That's going to be a Jason content. So let's read a name on email. I'm going to send my name. Email is going to be, Let's say, you know, I'd be no dot co. If I click on send, you should simply get the data back. But let's assume that when I'm posting this data, this particular payload must to contain minimum name, email and phone number. In case if I don't supply that, I should be getting another. We can achieve this by creating our own pipe and pass it toe at the rate body as a perimeter. Because the pipes get executed before the actual control comes to the handler function. We can do certain validation and then throw an exception in case of the validation face to do so. Let's create a file under SRC. I'm gonna call this as mandatory. Dash feels dark pipe dot ts and then export a class called mandatory themes. Pipe, which is supposed to implement by transform and by transform, comes from at the redness J is common. This is forcing us to write a function called Transform. If you're from angular Baghran, this is pretty much the same thing. So I'm gonna press command art on this error on it says implement interface by transform that select the same thing and also import arguments moderate up from the import that already exists, so once again, I'm gonna press command Dart are controlled out on Windows Cintas Center. You can see it has gone over here. As you can see, that the transform receives two parameters on if you're from angular background. You know that designator is little bit different here because you can have any number of perimeters how we were here. A pipe always works on a single input. The input could be a quiet resting perimeter. It could be a You're a segment which is not the perimeter itself. What? It could be a body. That information is available in the metadata. For our example, this is off no use. Also, the pipe transform can define the data. Type off this value and the return value of dysfunction. So you can, for example, say that this should be an object. So I can say any as well as the return value is supposed to be any. But in this case, we don't want toe do this. That's get it off This We will try that in another example. And to use this pipe. Let's goto our up controller 30 years and in the body here, I can say that I want certain number off feels to be checked in the body so I can't simply supply the class name because if I supply the last name, then next James will have to instant. Yet we need to supply the list off. Feels that we want to check on. That could be done through the constructor. So let's type your new mandatory fields by and then I can supply an array off fields. For example. I want to check if name is present. Email is present as the last phone is present, but right now I'm getting another because mandatory fields five doesn't take a constructor with an R E. So let's go and fix the same thing here. That's right. A constructor on the constructor is going to receive an array. Let's call it us feels on. That is supposed to be an array off string type Onda. We will not write any court inside the constructor, but then the fields is going to be a local variable of the constructor. I cannot use that over here, so make use of the fields in other functions you have to mark this as private and now feels become a private member variable off this class and I can start using the same thing over here on the very first thing that I want to do is to get off this default court. I have to write some code, so I don't want to really throw just like that. But in case if the payload is not coming with any content, I want to probably throw an error saying that you must supply payload as an object so I can say here, if not value. That means if value is undefined, are type of value is not equals toe an object, then I want to throw another on the editor or exception that I wanted through. If it is an unknown exception, then you will simply get another court of fire under description. Off internals are better, however, if you want to supply more meaningful messages, you can always throw http exception or it's a plus off the same I'm gonna simply say, Here, throw new http exception on the first perimeter is the message. For example, I can say payload must be an object on, but then I can give a 400. As an editor of 400 status scored represents bad request, which is meaningful in this case. However, if you have received a valued object now we have to check whether or not the object. The paler contains all the fields which are mandatory and deal of the mandatory fields which are there in the constructor in the form of a private variable on this logic can very from developer to developer. What? I'm gonna do it. I'm going to create a local variable called missing fields, which is going to be an empty agree on. Then I check whether each of these fields in this member variable is it present are not in this value. If it is not presented in the missing field, I'm gonna add that toe the local variable. But otherwise I'm just going toe. Leave it as it is, which means at the end of this process you're missing, feels is either zero elements are it contains one or more values. I'm going to create a variable called missing fields, which is an empty ari. And then I'll say you're feels dark, forage, and then I take one field at a time, and then I'll check if this field is present in this value. If it is not, I have toe add this toe the missing fields. So I'm gonna use a curly bracket over here to check. It's not value off field. That means that the value object doesn't contain this field. Then I want to say missing fields dark, push off feed. So this entire condition when you check if the field is not there in the value that is the payload by missing fields, will be pushed with that field that is missing. Now I can come down here and then check if missing field start length is greater than zero . Then I said throw new http exception and I need to give a message. So I use this template string format and then give the 400 as the state of school on here and say, Hey, Lord should include and then I'll give dollar. What are the missing? Feels dot join Giant will convert that into a string with this deal emitter, whatever the deal emitter you give, that will be added on eventually. A string is going to be substituted over here. But if everything is ok, there is no allegation problem unless implicated in the value as if nothing happened. So now you see that I told her that name, email, phone are mandatory. They're going to be checked. If the payload doesn't contain any one of them, you're going to actually get this exception being thrown. Let's go on very for the same thing Now, I already have a payload that doesn't contain phone number. Let's implicate. Click the send button over here and you can see that we got the state of scored 400 on a message off. Payload should include phone, and if I remove name and click the send button, you can see that it's going to say should include name and phone off course. If I don't send any data at all, then you will see that it's going to be a message that says payload should implored name, email and phone. However, if I think all the three data, let the name Ramesh email Ramesh at example dot com for some number. If you are sending additional data, for example, like this, that's absolutely no problem. However, minimum mandatory feels are supposed to be included in the request, which we have done, and now you can see we are able toe get our payload back because that's exactly what we're doing in our handler. So if there is a problem, this pipe will take her off the same. If there is no problem, we're simply returning the body. One thing you can observe in our mandatory fields pipe is that, according to the documentation, our class is supposed to be decorated with accurate injectable. I haven't done that. You saw that it works, but in the documentation, it is very clearly mentioned that you have to use at their it injectable. So let's go and use that as a best practice like this. Now let's create one more pipe. But this time, instead of we creating a file over here, let's make use of the nest, generate command toe automatically gender the pipe for us. So let's go to the command front. I have a new tab over here where I am in my project directory. I have to give the command nest G pipe and then give the name of the pipe. Let's say we want to create a pipe called uppercase pipes. I'm gonna simply type your upper case and then press enter. This creates air filed for uppercase by 30 years on a test case for the same Let's goto our cord. Onda, Look at that. There is a uppercase dot by dot es It is an injectable. It implements pipe transform. There is already a transformed function. But this time I want to say that the transform should take string as an input and then string as an output as well because we can convert only strings into uppercase. So obviously the value here should be off string type, and then the written type also is gonna be off string type. This is gonna be very simple. Pipe. All have to do is to check if value is presented. Then we want to convert that into an upper case. We know for sure that it's gonna be string, because off this other ways, it would given other enemies before we actually do that. Let's print what is the value on whether it is coming as a quiet resting perimeter? Our body, our visitor part perimeter. We can check the theme by doing a console log. Let's do that over here. Consoled a long that's a value camo value and then consoled out law, you can also check. What is the data type off that. Of course, it is gonna be a string all the time. However, we want to say whether it came as a perimeter are requesting or is it a body? We can stay here. Meta data dot Right, He is nothing but meta data dot type. So this is going to be consisting off one off those three values. You can just go and do a command. Click on this, our control. Click on that and you can see that there is a read only type. This is the one that is going to be either body quietly. Param are any other custom perimeter. And of course, there is other thing called meta type as well as data. So we're more interested in the perimeter type, so I can just type that over here. Let also print a line separators. So we get our output clearly on the console, and now we'll do the actual logic. Over here, we say, if not value, we're gonna simply return value. But if the value is present, we're gonna say value dot to upper case, and that's a built in string function which converts the input in tow and upper case and just for our demonstration. Say, Let's write a new handler for receiving little, for example, some kind of qualities. So I would like the new function. That's gotta disquiet. E Let's say we want a quiet contacts based on city, state and country will declare three variables like this on simply return the same city, state and country. Notice that I'm not giving a name Value pairs over here, but this is same as a property call city with a value off city like this. So whenever you have a variable colon, the same variables value you want to produce, you can just reduce the toe variable like this so it is equal enough. City colon, whatever the city is that ST Paul and ST Country Colin Country. Now let's map this function toe get handler on. Since we already have a get contact, let's have one more that s slash Q and then map each one off them with, Let's say, added it quietly. And then the quality corresponds to Kristen. Tell a meter called City on the same thing I'm gonna copy and then page for all of them. But make the necessary changes here. So state on this is supposed to be country. So let's make a request toe contacts slash Q Caution mark City equals toe. Let the bangle or on state equals toe Karnataka on a country equals toe. India were supposed to make a get request, not post. Let's click on send and see what happens and you can see we got the response as city, state, country with the respective values. No, it is when you're sending get the payload is off. No use. So even though you see here it is never being sent, For example, I can copy this from here and based over here and click on send we still get the same output. So get on the deal it do not carry a payload. Payload is only meant for post and put. Now suppose I want to convert city in tow uppercase so I can simply come down here and then in the quality decorator I can add comma upper case pipe press enter If it has not imported , you can just go and are that by pressing Commander are controlled out on Windows and Linux Express enter. You can see it is important. Now I go back, click the send button. You can see that city is in upper case. But if I want to do the same thing for all the three imports, what you can do is you can go back and then remove it from here and then stop. Lie that at the function levels, I can take her at the rate use pipes. Notice the decorator use pipes this floral. That means you can give one or more pipes on. I want to give here uppercase pipe. And now when I send the request, you will see that all the three off them get converted into uppercase. Now, since we use the pipe one time over here, but it is applied on on the three perimeter, you must guess that the transform function off the uppercase pipe is executed three times and that's where the large were given. Here can help us understand the same. So if you go back to the console where the server is running, you can see that we got the pipe transformed function executed three times and in each one of them the metadata. That type is qari, indicating it is coming from undated quality. In other words, quiet resting perimeter. So the most common use cases off pipes are transformation on validation. Now, even though you can create your own pipes for basic primitive transformation, we have the past into possible part a and part you ready pipe, but for validation. You also have validation pipe. Instead of writing our own pipes for validation, are making use of the building valuation pipe, which is very minimalistic. There are third party pipe that are available, which we're going to use when we are building our rest full Web services in the subsequent process. So that's all for now. See in the next lecture. 26. Using ValidationPipe and class validator library: in this lecture, let's understand the use off valuation pipe for which I've created a brand new this chase project or the next validation demo. And I opened the same thing in visual studio court where I have a controller for locals 3000. I don't need any off these things. So I'm gonna get it up the same and then also provide a part here so we can receive request for local streeters and slash contacts on. I'm gonna write one function here for handling the post to submission, and we'll call this US created contact, which is supposed to receive the payload, which is nothing but the body off the request. Andi, toe associate the request body. I'll be using the body decorator toe a variable for contact. And then all I'm gonna do is to simply written the same thing back to the user. But I want toe validate the data sent by the user toe match my own data type. But I don't have a day that I've yet. So what I can do that can create a regular jealously plus over here are types of plus called contact and then say that Hey, the body must match the fields defined in the contact. Plus, first of all, let's create a contact last. So I'm gonna go to the terminal and then tape next G four generate and then tape seal our class and then I'm gonna type your class name called Contact. This is simply going to create a tight script File, Corp. Contact tortillas and contact Dark Spectre tears. Now let's go back to our court on then open the contact, our tears, which is right here. It's been exported as class contact. That's a couple of members here. So for our contact object represents Islay name and email where when the user sense the data, it is only the name and email. So I'm gonna create two variables here. Name off type string on, then as a email off type string as well. But I may want to do some validations for days. For example, name is mandatory field, as the less the minimum number of characters for name expected is three maximum, you misapply. Probably 20. Email is also a mandatory field, but also it must be a valid email with under it on the dot to do all these validations, we made different on the validation pipe uploaded by next Jerious. But Validation Pipe uses a very powerful, jealous replied very core plus validator, which is over here, as you can see the documentation there given how to work with this. So the first thing I have to do is tow NPM, install class validator, and then I can start using the decorators that they're provided, like Lend for a string and I can say the minimum length is 10 characters. Maximum is 20. In our case, I may say three comma 25 probably. We may also use at ease email on the email field so that it is supposed to be a valid email . I'm like this. There are many decorators. Probably you can have a look at the same here, so the first thing we have to do is to install the class validator. So let's do the same thing. I'm gonna type your NPM I class dash validator. Also, let's add another library called Class Transformer. This is useful for transforming a string toe respective journalistic object off our class data type press enter. Now that the installation is done, let's go back to be a score on the first of all, let's add an empty import statement like this and say import. And in tickle abrogate from Anakin, state class validator is over here. And now I can come down toe this name and then they at the rate he's not empty. This will ensure that name is not empty. The same thing. We're gonna play for email also. So I'm gonna copy this. Based the same thing over here. Onda. Let's make some room for me. Let's also are another decorated that the minimum lent off. This is three letters and maximum is 20 or 25. So I can say that the red lent and then type here. Three Come on, 25. Similarly, I can come to the email and then say it must be an email. Second tape your east email. We can also say that they all have to be string data types so I can take your activate these streams, Andi, that will ensure that numerical values are not applicable for these variables With these decorators on these fields. Let's go back door at controller map dysfunction of the post request handler so that I can do by typing at the right post. Andi also will say attended Use pipes on the point that I'm interested to use is the valuation pipe import the team from next year's common on automatically. Our payload will now be validated against the data date that I'm going to specify here things. I didn't mention anything here. The valuation pipe doesn't relate this object with the contact last year. So I have to say your contact colon off type contact. I know my model class that I have created has all the valuations on that would be now validated by this validation pipe. If there is any valuation errors, it will be automatically reported to the user with error. Court 400 Because it's bad requests on bad input. Let's go check it out. First were toe start the server. I'm gonna type your NPM run start colon del press enter understand what is really Let's go to the postman. Make a request for the Ural. Using the post on the Ural is nothing but http equal and local host Colin 3000 slash contacts I have to send in a body on the body is going to be a raw data in the form off Jason. I'm gonna simply send an empty JavaScript object and click on Sane because there is a valuation tool applied. I should get some errors and you can see that the head of state escort is 400 the messages and ari off all the violations that I violated. For example, as for his name is concerned. Name must be a string. It must be longer than R equals 23 characters. Name should not be empty. Likewise, you can see that it's his email. Must be an email. Must be a string as a less. It should not be empty. So if I simply send here name, colon and interesting email, colon and industry name must be string on email, most blistering. They are satisfied because I'm sending a string, but the other ones are not satisfied, so they will still remain as errors as you can see. But if I send a valued name, that's maybe not and take on send. My name is okay, but email is not okay, so email should not be empty. So let's send in an email. Let's just be know that check coverage cause you can t now the errors are reduced to only one and says email must be an email. So I'm gonna send your We know that we know dot co now everything is okay. The same data is going to be returned back to me by the handler there every time. However, if I let they give a very big name over here. So which is more than 25 characters over here? This will come back with one other message and says that name must be shorter than r equals toe 25 characters. So just where adding the class validator and plus transformer libraries to our project on, then just by adding this pipe validation pipe along with the appropriate validation annotations were ableto automatically validate the incoming data and ensure that our data conforms to the rules defined by my model. 27. A quick intro to Mongodb: in this lecture, let me introduce you to Mongo DB, which is the most popular no sequel database management system. It is a cross platform, document oriented database management system classified as a no sequel database program. Mongo DB uses Jason late documents with optional scheme. US Mongo DB was developed by engines after company in 2007 as a component off a platform as a service product. In total nine, the company shifted to an open source developing Modern. And in 2013 tension changed its name to Mongo, DB Inc. The name manga TV is derived from humongous TV Onda, as indicated, he is used for storing huge amount of data. Unlike arguments where you perceive the later in a tabular format with rows and columns in Mongo, DB restored the later in a so called document format, which is nothing but a bunch off key value pairs. A document in Mongo DB is equal in tow record off the table in an Audi bemis, but all records often are DBM, a stable are identical in structure, whereas documents in a collection may have different structures. A collection in Mongolia V is equal in tow, a table in our IBMs. A document is like a Jason object, but internally it is stored in a format called Visa, which stand for Binali Jason. We can perform all kinds of quality operations and a collection just like how you would do that in an alley. BMS. But unlike arguments mongo DB, it doesn't support transactions on joints. The idea here is toe. Retrieve the data quickly and efficiently, since joint operations are the biggest pain points when it comes to performance in arguments, since we tend to store huge amount of daytime mongo db toe, increase the performance and mitigate fail owers, mongo DB offers charting and replications for storing, manipulating on accessing data in a mongo DB collection by our nest application. We don't necessarily need to know mongo db in detail. However, in the next couple of lectures, I will walk you through the basics off mongo DB shall commence 28. Downloading and setting up Mongodb server on our local machine: in this lecture, let's tow the installation off mongo db on our local machine. The installation on Windows Mac, where's our Lennox? Will remain the same because when we don't Lord, we get a ZIP file. All we have to do is tow. Unzip that file in, tow some location and make sure that our Mongo DB commands are in the pot. In the later sections. We will also start working with Mongo DB on the clothes. But for now, to make ourselves comfortable with among would be command, let's have a local copy off Mongo db two. Don't load mongo db first with it. Mongo db dot com in a browser. And then, if you go to the home page here, you can see that there is a software section. It says communities are world that is also an end to place their work. This is basically commercial. We will don't let the community server clicking on which it will take me toe a page where you can choose the downloads. As you can see that there is a current question, which is four door to door seven. You can choose older Russians if you want, as well as the platform, which automatically has been detected here. And then, of course, what kindof download you want? So if you're selected, Windows probably would have got a mess. I are probably a zip file. I click on download. I'm going to keep it on my desktop. So once the download is done, let's open the same thing in Finder and unzip the file Instead of keeping the binary files on desktop, I would like to keep it on my home directory, so I'm gonna drag this and then drop it on toe the home directory here. And then I have to ensure that the Mongo DB Bin directory, which contains all the executable, is in my part. This varies from operating system toe operating system. However, if you don't want to set this part, no problem. You can still run the command from the BIN directory itself. And inside the BIN directory, you can see there are some executable. The one that represents the server. Is this mongo D on Windows L. A mongo did r E x e. By double clicking this, you may start the server. However, it looks for a specific folder called DB slash data in your installation drive. However, I can also run this from a command front and then supply that option manually. Once the server is up and running, there is no security enabled By default, you can connect to your server, which is running in 27017 port and to connect to the database and issue some commands, we can use this mongo as a shell. This is a client. Instead of using this mongo shell, we will be writing a nest application toe store the true and manipulate data on the mongo DB settlers. So let's go open a terminal verified a mongo DB insulation also start among go to be server . Before doing that, let's also create a folder on our desktop. You can keep the folder anywhere you want. You need to create a folder that has all the data that gets created when you are servant is up and running. So I'm gonna pierre a new folder over here on the name of the folder. I'm going to give it as mongo db dash data. You can name it anything you want. Let me open a terminal on, then seed in tow. Mongo db installation folder that contains a been directly that consists off all the executive ALS. So I'll say Siri been. And then if you check the content, you'll see that all the executable czar over here, As I mentioned earlier, we have to run this Mongol de Command, which starts the server at Port Number 27017 But we may have to specify the name of the folder, which is going to be used for storing all our data. So let's clear the screen and take the command mongo D Dash. There's Devi Pot and then the name off the folder so I can give either an absolute part on a religion pot. Let me give the absolute part as slash users slash we not come out slash desktop and then slash mongo db Dash data I pressed. Enter on. You can see that disorder War is up and running To verify whether the Sarwar has started properly or not, we can open another tab by pressing community and now issued a command mongo, which will try to connect to the Mongo DB Server once again. If you look at my world military, I'm already in the BIN directory right now and now I can type your mongo and then press enter. This is gonna buy, therefore connect toe the local host to 7017 But during the start up of the server, have you given a different port number? You can specify that also, by typing dash, dash sport and then a different port number by the four little also connected DB called the test. But if you want to connect your different database, you can give the name of that d be as well. But since we don't loaded the Mongo DB just now and then started the server, we don't have any data basis. So let's simply press mongo and press enter. See what happens on Mac OS if you get this particular dialog box. That, says Mongo, cannot be open because developer cannot be verified on. This is mainly because McElroy's is trained to validate the one that you downloaded from the Internet, not from the APP store. So what you can do for that is cancelled for no on, then goto system preferences under security and privacy. It is telling me that Mongo was blocked from use because it is not from an identified developer. So that's OK. You can simply click on a low Anyway. Close this on. Go back over here and then type the command mongo once again. You can see that now. It came up with a different dialect boats. It says that Macron's cannot verify the developer off. Mongo. Are you sure you want to open it? I'd say open. And now it's gonna connect on. You should see a farmed. You can clear the screen by pressing control and l on Mac OS, and then you can now type mongo. DB commits. No, this is not your UNIX comments over here. Now it's a mongo. To Michelle, it is typically like a job, a structure many of the Java scripts commands work like, for example, I can declare a variable. I can run a far look over here, however, I'm more interested in the Mongo DB Command, and the only command I want to see right now is show DBS on. That's basically like shoulder data basis, and you can see that there are three databases called Item in Conflict local by default. In the next lecture, let's discuss about most commonly used commands and make ourselves comfortable with the Mongo Division 29. Getting familiar with basic Mongodb shell commands: in this lecture, let's learn about some of the basic commanded mongo DB, although in orderto work with Mongo db, Why are less chairs? We don't really need to know this, but in case if you're adding data, why are Nestor's? We can verify that by coming to this convention and then checking our database. So the first comment we have already thing called Shore DBS our debates, which is nothing more sure. Data basis, which shows the list of databases that are currently available in the mongo DB Server. However, in the beginning I mentioned that when you typed among go command and president or it'll connect to a DB called the Test. But I don't see that over here because they're either tested every but because there is no content in it. It is not being listed out here, so it's not actually committed to the secondary storage. But if I want to know what is our database that I'm currently connected toe, I can take the commander db and press enter. Basically, DB is an object on when you take the object. It actually shows what is the name of that object, and it is test if you want to switch to a different database. For example, if I want to connect your database called training, I can type your use, training and press enter. And now it's a switch to the TV called training and by typing DB pressing enter, you can see that it is a new database called training. However, if I typed the command show, DBS are DBS, it will still show me only the admin, confident local, not the training. And that's primarily because I don't have any data in the current database, which is called Training. Unlike RGB means you don't have to create a table, which is called US collection. Over here in odd ones, you can simply start adding a data toe. A non existing collection, a collection get automatically created. You also have a command called debido Create collection, but we don't have to necessarily give that. So in order to create a database collection called contacts, I can simply type here db dot contacts and then say, Don't we can issue commands like save or insert so I can type your sale and then I need to supply a job basket object. Are Jason object? It's not necessarily a Jason. I can simply give a javascript object. For example, Jason objects will have the key value pairs where keys are always gonna be string. But in Javascript. Just a identified, for example, are type Your name is Let's be Not on email is let's say we know at the rate we know dot co close the curly record andan their own bracket for the same function. Nor does that say, with a function. And I'm supplying a JavaScript object over here when I pressed. Enter it, SIMPLEs Is that right? Result. An inserted number off inserted record is one, which also means I can insert multiple records as well. Now, if I type short DBS are short DBS. You'll see that there is also a database called the Training, and no one works. This chaining delivers I can access from other applications. Also, we can also add a new document, which is equal in the very card in RD Bemis using the insert command so I can type your David or contact, start, insert and then supply. Let a name that start Sham e mail. Let's give Sham at example dot com Onda, Unlike are the women's where the columns off multiple rows are supposed to be identical. I can give different values. For example, I can also say city off bangle and then close the curly bracket and press enter. You'll see that it is inserted. Number of records is one just like the previous one. There is a minor difference between insert and sale, which is nothing but insert always tries to insert at a card, whereas Sale tries to update a record. If the record already exists based on a property called Underscore 80. What is that? We didn't give any special primary key kind of stuff, but by default Mongo db documents have a underscore idea property. If I don't supply that didn't get automatically created. Soto, view the content off our collection Right now, I can issue a command called find our find. One find will give you the list off all the documents, but eventually will only see the 1st 2 20 off them here on the console. But find one will give the very first document that is inserted. So I'm gonna clear the screen once and then type here show collections, which is going to tell you what are the collections that exist in the current DB. So now I can say db dot contacts Don't find one no notice find one is given in camel case. If a press enter, you'll see that the very first to document I inserted is listed out with the three properties while I give only to off them I gave name and email but there is also an underscore 80 and then underscore idea is supposed to be unique across all the documents off a single collection. We can give any kind of values. But if you don't do an object off a classical, objectivity will be created. And I really speaking this is the actual idee on These are the rest of the properties that I give. If I want a list of all the documents in the contacts collection I can say here db dot contact start, find But this will give you in an unformed it'd way. As you can see, it is showing you like this. But if you want oh, former daddy can also are there another function called called Pretty on. This will probably former that and then show you in a different way while executing the find command. You can also supply some conditions. For example, let's say I want to find the document where email is sham at example dot com. I can basically copy this particular Kiva loop here and then clear the screen type David or Contact start find. And then I'm gonna supply JavaScript. Object with this key value pairs, and now this will be considered a rare condition, so it's equal in tow. Select. Start from contacts. We're email equals toe sham at example dot com I pressed enter and you can see I got the result once again if I wanted to do the formatting, either again, use find one are I can use find dot pretty so I can take your find dot pretty like this. That's enter all I could have used something like Find one because I know that based on an email, I may have either zero or one record. So when I pressed Enter, you can see a similar put over here, although we can perform lots of operations like update or remove our indexing and many other things. Those are beyond the scope of this particular training because we want to do all those things using a nest application rather than the Mongo DB shell. But if you're interested to know more about this, I do have a course on Mongo DB fundamentals, which colors many commands and features, including indexes. So that's all for this lecture. In the next lecture, let's create a new next year's project that can communicate with this mongrel bizarre work for working with rest endpoint. 30. Creating a new Nest project with required dependencies: in this lecture. Let's create a new next year's project and add the required project Dependence is that include class validator class transformer on a library called Mangoes and unassociated library called at the rate next year slash bongos. I have opened a terminal and I'm already on my desktop and I'm going to give the command called nest new and then the project name. I'm gonna call it US nest dash mongo db dash demo press enter As usual, this is going toe. Create some source Cordes. And then it'll ask me, Do you want to use NPM Our yard? I'm gonna press enter because I want to use NPM. This is gonna take a couple of minutes and I will come back once the installation is done. So the installation is complete on the first Come and I have to execute is to city into the folder. Ramona. Type your city. Nestor Dash mongo db Dutch demo press entered. Let me clear the screen and then type the command NPM. I are in stone class dash validator class dash transformer, Mongoose Onda after it next year slash mangoes press enter class validator and class transformer. We want toe use so that when they're the post put our patch, we can validate the data sent by the user agonist or schema. These two have nothing to do with the Mongo DB itself. However, we want to build a complete arrest endpoint in this particular section, and that is the reason we're using that. In order to connect. Among would be, we need to use some library. There are many libraries available on mangoes. Happens to be the most popular among the rest of them. So now that the installation is ready, let's bring up the server by typing NPM run. Start calling Dell, which is going to start the development server occupying port number 3000. Also in another time, I want to see in tow my desktop where my project is there, which is called Nest Dash Mongo DB. That's demo and then type court dot that brings up visuals to the Accord and loads the current project. So that's all for this lecture. In the next lecture, let's create our contacts Model controller on service on Do the initial set of required for Mang goes 31. Creating contacts module, controller and service: Now that our project is up and running, let's create a model for our contacts application. I've written Toller on a service to the same model and to add a new model called Contacts. Let's type the command nest G G four generate Oregon State, the Complete World generate. And then I take your model, followed by the name of the model I want to create, which is nothing but contacts. When a press enter, it's going to create a folder called Contacts On Inside that it's going to create a file called Context dot model Dirty Years as well as it makes an entry in the abductor model 40 years, which is our route model. Let us now create a controller. Once again the command is nest G and then see for controller Oregon type the world controller itself and then the name of the controller we want to create. Once again, I want to give it us contacts because it is goingto be dumped into a folder called Contacts and updates the model file, which is present in that folder, which is nothing but context model ts. So we have added a model and a controller on the only thing that is left is to create a service that's created by typing nest G service. And then the name of the surveys once again is going to be contacts I pressed. Enter. It's going to create a class along with its a speck and then update the contact start model that tears. Let's go back to our area scored and verify whether on the court is gendered it properly. So if I go back toe beer scored at SERC Main Dirty years, no change over here. I were in the at modernity, as you can see that it has imported the context model. And then in the context model, which is under contacts, you can see that there is a controller on a provider, which is nothing but your contacts always over here before we proceed for the let us make our app configured toe work with Mongo DB, which is running in local host to 7017 To do that, let's go to the ATM Adu LTs. And then in the import section. Let's import the Mongols model and configure the same. To do that, I'm gonna come here and then press enter, make some room here and then type here. Mongrels model 0.4 route and they type in the string, which is nothing but your connection. String to mongo db. So I'm gonna take your mongo db colon double slash local host Poland to 7017 Now, this happens to be the default port for mongo db so you don't have to explicitly mention But then you need to give their DB that you want to connect, which is nothing but training. Let's give a comma here because it's an area and it says that mangoes model is not available. So let's go here and then import the same. I put an empty curly bracket and then say from at the rate, Nestor Js slash mongrels. And if I now come down here, you may see that there is a intel isn't available. I can even press command dot and then it says add mongrels model to the existing import declaration. So I'm gonna select that on automatically that comes up over here. Once our application is relieved, we will be connecting this toe the mongo db a plus, which is nothing but among would be cloud and all. I have to do is tow. Come back here and then change this year or early that connects. Stood among would be a class with the user name and password. So that's all for this lecture. In the next lecture, let's create a contact model, plus that represents our contact the resource and then consider the same toe work with mongo db using mangoes. 32. Contact model and schema: in this lecture. Let's create a class that represents our contact object. There are two reasons why we're doing this. Number one is for validation Purposes. When the user sends a post are put to request the paler can be validated against this contact. Plus, as a less mang goes requires to work with a schema. We can use the same class and provide that as a schema. Now, with the steam on among those can power operations such as save or find etcetera. So let's go clear our contact model. Plus, I'm going to right click on the contacts folder over here and then a new file on the name of the file. I'm gonna give it us contact dot schema dot ts. The name of the file itself can be anything you want, but so make sure that we understand that this is a skim off while we're gonna give the name s contact our schema tortillas on Ala Moana Tory's tow export. A class here called contact. Unlike the previous examples were only name and email be used. This time, we will also make it little bit elaborate. So we'll clear the name off type string. We're gonna have another email we're gonna have. The phone number, which is all going to be a string type, will also have city off type string state again, off string and then country off course. That is also going to be a string. However, we also want toe ensure that the user enters proper data for each one off them. So I'm gonna add some decorators here first, let's at a empty import statement. So it's a import empty calibrated from class validator. Now the reason why I do this is whenever I had a decorator, it'll automatically be taken from here, for example, for the name and email. I want this to be a mandatory one, so I should say that they should not be empty. I can see here at the rate is not empty on Not that automatically. It went inside this bracket. Likewise, I also want to say that the length of the name minimum three letters maximum 25 letters. I'll say underrate lent in bracket. I need to give the minimum, which is three maximum 25. As for US, email is concerned. We can say here at the rate is email and we'll also say at the rate is not empty for four number. We can always stay here at the rate is phone number and in case, if you want to restrict the user toe, enter the country core. You can put a region as that said, This will ensure that the user has passed the country court along with the phone number. Once again. If this is a mandatory field, you can always say here at the rate is not empty for city, state country. I don't really want to do any validations. So the first part off this model plants is really the second part of this model classes, where I want to make it off this contract loss as among goes schema so that I can perform the crowd operations using that. To do that, I can make it off some decorators, probably by next Js Mongols as a less mangoes. Let me add that over here, I'm gonna add import an empty curly bracket from a drape nets Js slash mangoes and then another one import an empty curly bracket from moderate mangoes itself and from mangoes, we want toe use a class called document for which this class after the subclass. So I'm gonna go on type your extents document. The import did not come here, so let's manually add that. And then we need to decorate this using other it schema. Next. We also have to tell which off these fields represent. Mongo, db schema properties nothing but the properties off a mongo DB document. And in my case, all of these are property. So allowed are a decorator, Your advocate drop like this and copy this and paste for each off these and one last thing we have to do is to create a schema using this particular class definition and then export the same to do that. Let's come down here and say export Const. On the name you can give anything you want, but something to do with the contact would be useful. So I'm gonna take your contact. Schema equals toe schema factory don't create for class and then the name of the class that we have, which is nothing but the contact with this. Now our basic schema set up is ready in the next lecture. Let's create our post request handler where a user can submit a contact details that could be validated as well. As if validation is successful, we would be interested. Toe Add that to the Mongo db server. Using the Mang goes on that court, we will be writing in our service function. 33. Adding a new contact via POST request: In the previous lecture, we created this contact schema, and now we can use this contact schema and create a model definition. Register that with bongos so mangos can do the dependency injection toe our services. So the first step is to go to the Contact start model Doctor. Yes, and then including imports section, wherein we can give a bunch off other models our model configurations. In this case, we're gonna use a model called Mongoose Model dot far feature on, then register a bunch off model definitions. As you can see, it's an Audi on each model definition. Correspond toe. A collection in or mongo DB database as well as this key mother were created. Since we have a collection called Contacts were going to give a name off the model called Contact in Singular. This will be automatically pluralist for the name of the collection, which means if they're given here contact. It will be mad to a collection called Contacts. And if you're given a name here called person automatically, mongers will look for a collection called people, and if the collections don't exist, it'll automatically be created. Also the second perimeter to the model definition is the scheme. I excels, which is nothing but contact Schema on our model definition is really we know can goto our contact service and then ask for the dependency injection off this model and at a constructor and in the constructor, we're going to declare a private variable on the variable represents a class which is nothing but our contact model. So I'm gonna take your contact model off type model. And this model comes from mangoes. It is generic. So I have to specify what did the structure off a document here. And the structure of the document is there in our contact schemer. And it's nothing but the class called contact. So I'm gonna go here and then type contact. Make sure that import from contact that schema Onda. Then, of course, I have to give the open and close bracket model needs to be imported from Mang goes so well , they hear from mangoes and then go on And are the model over here. If you carefully observed in the context model, when we register, we have registered and a day off model definitions. When we are asking for a model here, it is possible that there may be multiple model definitions on the one we want. Nestor toe inject here is the one that has this name called Contact Ondo. Specify that we use a decorator called at Inject Model, and this comes from next year's Mang Goes on. I'll have to do is to pass the name of the model, which is nothing but a contact. And with this now our dependency injection is really we can now use this particular class and then perform the current operations. So let's begin by creating a function for adding a new contact. Let's call this as our one contact which receives a contact object as a perimeter off type contact inside dysfunction. Let's create an object off contact model. So I'm gonna say here, let C equals toe new distort, contact modern And then I can supply the contact as the perimeter to the constructor Or I can create a new object. Spread the value off this and the spread operator is usedto avoid the mutation. So this particular perimeter, now that we have the c, I can simply say, si dot save, which actually saves the data in this particular variable, which is nothing but a copy off this contact comes back with a new I D. Which is the underscore. Any property we know can simply return this scene on. We're done with this particular function to make it off this function. Let's go to our contacts, controller and write a function that acts as a post request handler. So that's call this function as create contact, which receives a body from the request. But we want this to be off type contact and contact needs to be imported from contact dot scheme or 30 years. And to insert this data into our mongo DB collection, we first need toe. Get this contact services a dependency. Let's go and add a constructor over here and in the constructor perimeter. We're gonna receive a service off type contact service. Of course, if you want to make it off this service in other functions were to mark This s private, our public protected. And now that we have this service, we can say this. Start service dot Add one contact and let's apply the body in orderto map dysfunction to the http post we have toe add the decorator called a direct post. There is no need to give any perimeter to this because we want to handle the request for slash context. However we want toe are the two more decorators here number one decorator To say that this variable should receive the content of the request body and that's done by typing at the right body. The 2nd 1 is to say that the body should be validated against this particular data type. And Father, I can simply come here and then say at the right, use pipes on the pipe that I want to use is nothing but validation. Fight. If you want the validation pipe to automatically transfer the payload into the contact object, we can also say new elevation pipe and then supply contract object that says transform is nothing but true. So with this now, our request handler is also ready. Let's first go check word of the content available in our mongo DB Davis collection and you can see that we have these two. So let's go to the postman on at a new contact First, I'm gonna select post from this drop down the you release http Colon double slash local host Colin 3000 slash contacts and then the body is nothing but raw. Jason, if I don't supply any values, I should get an editor because we have used the validation pipe. Let's click on, Send in, check the same thing and you can see regard an error 400 as expected, on a bunch off error messages. So that's going, Are they object? Over here? Let's supply and name and I'm gonna supply my name. We know command and then the email, which is nothing. But we know at the rate we know dot Co. That's also at a phone number. Notice that phone number should be supplied with the country court. If I don't supply the country court, then there'll be an editor. Let's give it a try. I'm gonna supply the phone number without the country core. And let's also supply a couple of other fuels. Although they're not really required. I'm gonna take your city Bangalore on Let's say, for example, country India If I send this now, although not send the state, it's really another requirement. When I click on send, it should now come back with another message because the phone number is not valid according to the requirements, so Let's click on Send and see the same thing and it comes back with the method saying phone must be a valued phone number. So let's go Another country court here. How to say plus nine one on, Probably a space click on send on. This time we didn't get any error message. Plus, the status is 201 created. This comes because there is no response body. However, if I go back to the mongo db shell and then very fight that documents over here, let me clear the screen and then issue the command. Once again, you can see that the new document has been inserted with an idee. Now, if you wanted this to be the response, you can go back to the V A school on return the same like this that's going check it out once again, I'm gonna go back Toe Postman are another record. Maybe the same content. Let's click on send. So we got a response. After adding the data into the Mongo DB collection to verify the same, let's go back to the mongo db Shell issue the command Once again, you can see that the new document has been inserted successfully. I really we don't want emails and phone numbers to be duplicated, but I self no, we already have added the duplicate email and phone number so toe alive these first, let's drop the collection on recreate by adding a new one. But this time we want to ensure that phone number and email are unique. So to drop the collection, I'm going to say, db dot context dot drop and thats going toe. Drop the collection. You can check it out by typing show collections, and you will see that there is no collection anymore. So to indicate that our email and phone number are supposed to be unique, let's go back to our contact schema and then wherever we have added the ad rate prop over here for email and phone number, we now have to say here in curly bracket, which is not the murder configuration object will stay here. Unique is nothing but true and the same thing I'm gonna copy and paste for the phone number , and now mongers will take it off, ensuring that this is a unique value. So let's go back to over Postman Onda. Try sending this once so the first time. It should be added. If I go back to the shell and then check the show collections, you can see that we had given the name of your model as contact so it would have cleared a collection called Context. And if a type here, David or contracts start, find or find one. Let's have find dot pretty press enter. We got this. If I go back to the postman and then try to send the same data again, you will see that it is coming back over here. However, you can see that it is not under this second record. It's the same document gets updated once more. However, if I go back to the Postman, probably changed the email. Let's say, for example, in Slough. We know that you know dot co and say that this is We know that example dot com and then probably change the phone number from this to, let's say, for example, Double zero click on Send. This time it should be a new document, unlike the previous one. So let's go back to the Mongo DB Shell and then try the same thing. I'm gonna clear the screen and then enter the same command will see that there are two documents, not one. So this is how you can use among goes toe. Add a new document to your existing collection on. If the collection doesn't exist, it gets automatically created in the next lecture letter than its TDP. Get request handler to get the list off all the contacts in our mongo DB collection. 34. Get all contacts via GET request with pagination: in this lecture. Let's try to get request handler for getting the list off all the contacts. But since we have only two contacts first, let's add some data toe or existing mongo DB collection, for which I will make yourself a website called marco dot com. Here you can generate up to 1000 documents in different format. For example, you can see that there is a CS, reformer, Jason, former SQL and other formats. We want Jason format, and also we want to customize the fields. I don't need the idea, so I'm gonna get enough that I need the name instead of first names. So I'm gonna changes toe name on the type toe full him. So if I can type your full, you can see that you get the full name. I don't need the last name. I need email at only gender, but I'm gonna have phone number instead of gender. But the type off the value that I want is also a phone numbers. I'm gonna go and select your phone number. The former of the phone, remember, we have to include the country cool so I can go here and choose one off these three until it the 1st 1 I don't need the I p address, but instead I can say I want city changes to city. That's at another field called ST Click Here Toe change this toe state and one lost. I want country and select country. And now I can click on this download data Britain Toe Don't look the same by default. It comes with a name called Mark Underscore Data. Jason, I'm gonna keep it on my desktop. Click on Save the Filings. Don't load it. Let's go to the Mongo db Shell exit from there. And then from here we can executor recommend car mongo import to load all the data from or moderator Jason into our collection called contacts. To do that, let's type in the command mongo import, and we have to give few options. For example, we have to specify what is the name of the DB by typing national TV. DB Name is called Training Dash Dash Collection. This is going to specify what is a collection that we want toe import into. But if I don't mention this, the name of the file will be considered as the name of the collection, which is mark on the score data. But since we already have a contacts collection, so I want to import the data into context. And finally we have to specify that the content of the file is a Jason Terry because it can also be a CS three data. So I can say here, Dash just Jason Day and finally, the filing that I had to give, which is on my desktop. I am giving a religion part from my home military, the stock slash mark data Georgeson. When I pressed Enter, you can see that it is connected toe mongo db colon, double slash local host and 1000 documents imported successfully. So if I get inside the mongo shell on my DB is called training Now you can see that if I say show collections, I already have the collection called Contents Heavy work. If I say db dot contacts dot com, I'm gonna get 1002 as the count. The command db dot context don't find will only display the 1st 20 off them because find returns and it'll later which can display the 1st 20 I press enter and you can see we got 20 documents. You can count it if you want, but in order to get the next batch of 20 I can take your I D and interest enter. Now that we have over 1000 documents, let's read get request handler, which makes us off our service function to get the data from the mongo db. So let's go to the visuals to the accord. First, let's write a handler for get request. So I like to start by typing at that it get press enter to automatically import the same and then the function name. I want to call it us. Get all right now, we don't want to receive any pattern readers, but later we will are few parameters that will help us do the pagination on inside this, I can say return this start service start. Probably get all contacts. Notice that we don't have this function. That's why we're getting another. I'm following a top down approach over here, so let's go and create a function called get all contacts in the service class. I'm gonna copy this name, go to the contact service tortillas, onda paste that open and close curly bracket to get all the documents from the database. It's very simple. I have toe make yourself this start contact modern don't find which doesn't take any perimeter. However, if you want to do some filters, you can supply the filter condition as perimeter. Let's for a cynical and and also at the return key word here so that when we call this function, we get all the documents. So two very for the same let's go toe postman on. Then send in a request to the same mural using the http, Get requests. So I'm gonna copy this yarn on, then create a new tab base this Ural, it's already get Request your click on send, and hopefully I should get the list off all the documents. As you can see, I got all 1002 documents. It's very difficult to come, but since you can see that there are a lot of documents, we can take it for granted that it's 1000 documents. Now. This is OK for 1000 plus documents. However, what if we have millions off? Documents are probably billions of documents. You don't want to really send all the billions of documents toe the client because that's going to take a lot of bandwidth as well as a lot of processing power. Plus, the users may not be interested. Toe see all the document as a less the users Browsers also may not support to display those many documents so that a lot of factors for which we know have to probably say, I don't want all these documents. Gimme here. Probably a bunch off 10 documents at a time. And to control that, we probably can send in a perimeter here. Question mark underscored. Page equals to probably one on, then probably underscore. Limit equals toe. Say, for example, 10. I also want these two well used to be the default. So if I don't supply these, it should be assumed as page number one and then the limit off 10. So let's go to the controller and add these two parameters. I'm gonna create page off number type and then limit also off number type, and then the same thing. I have to supply toe dysfunction, which currently is not receiving any such perimeters. However, we will send it anyway and make the necessary changes in the service class. So that's giving another because we don't have the parameters defined in that particular function. Let's go to that function on, then receive those two variables wanting animal colleges page off number type and then limit also off number type. Now to make it off this in our fine function, we simply have to say here dot limit, which is not a model limited self. So this is going to restrict the output toe only the specified number off documents. But we also want to specify an offset that starts from this particular page. So if you are on the page, number one the officer to zero. But if you're in the page number two then offset is nothing but the limit. So because of this, I can say dot escape, which is to mention the offset I have to say page minus one. So if you are in the first grade, it's gonna be one minus one, which is zero. But if you're under page number two, it's like two minus one, which is one multiplied by limit. So if your limit is 10 and you're saying page number 33 minus one is 22 into 10 is 20. That means you're gonna skip the 1st 2 20 documents. That means that in the beginning of the third page, so which is what we want anyways? Now the service function can give me the paginated data. But we still have toe map, these two variables to our controller function arguments. So let's go to the controller. We have these variables to map this. I just have to say obdurate quality and then specify that the quality perimeter name is underscored page. So that's going to map it. Likewise, I'm going to stay here at the red quality underscored limit. But we also probably want to say that in case if the user doesn't supplied underscored paid are in school limit, we wonder to be assumed as one ended 10 respectively. For that, I can make it the default value pipe over here. I can say new default value. Pipe off one for the page on the same thing. I can copy this and paste for the other one, but the value here would be 10. We also want to ensure that the U there is entering only a numerical value for those two, for which I can add one more here, which is called parse into pipe the same thing. I'm gonna go and give it toe the other perimeter also. And now our controller as well. A service functions already. So let's very for the same thing. By going back to the postman, the tree, move on these perimeter values and then send in the request, See what happens. It's like consent on as expected. You can see that we're only having a handful of them, which is not about 10. Document the 1st 2 off them I inserted earlier using my post. The remaining ones are the documents I imported from the mark data. Jason, let's go on. Add a page number. Now I'm gonna go here and then type Question mark underscored. Page equals to two. I'm supposed to get a different documents than these two. Let's click on send another concern. We we got a different set off 10 documents. But what if I want a page number two where the content part page is gonna be 20 documents? No problem. We can go here and then say 1% underscored. Limit equals to 20. Click on send. Now. We got some different data. Also, we got more number off documents So this is how you can implement the pagination using the mang goes ap I. So that's all for this lecture. In the next lecture, let's write a get request handler wearing the user may be able to supply an I D. And if there is a corresponding document, let's respond with the same thing. Models. We will respond with four, not four state of school. 35. Fetch a contact by id via GET request: in this lecture. Let's straight a get request handler toe, send in an idea as a part perimeter Onda, get a corresponding content object. And in case there is no document corresponding to the i d given, I should get the state s Korda's for. Not for first. Let's create a http get request supplying the I d. So I'm gonna copy this. You are all here and then go to a new tab. It's going to be a get request. The U released this slash and I D Let's border and I leave from here, so I'm gonna select the 2nd 1 Copy this and then paste over here. Since I don't have a handle for this, this is any We're going to be 404 Let's click on Send Onda. Fix this by going to the controller, adding a new function over here. The function is supposed to be decorated as at the red get with a part perimeter called idee. The name of the perimeter itself can be anything but We need to map this idea toe the variable, which can be given as idea again. I'm gonna call this as get one contact. Let's say I did it, but, um, which is gonna map this dynamic part? Perimeter toe variable. So I'm gonna say, here I d and then declare a variable called idly off string type. Let's open and close the bracket for the function on. All I have to do is tow make yourself a satirist function which currently doesn't exist and returned the value given to me by that function. So I'm gonna say here, return this dirt survey start get one contact or any other name. Doesn't matter because this function doesn't exist yet. So I'm gonna supply the perimeter I d. That I received. And then click your press commander dot on Mac controlled out on windows. You can see that It says declare a method called get one contact declared property called Get one contact. I want to create a method. So I'm gonna sell it this and go to the contacts terrorist RTs The function is added over here on the top. So I'm gonna cut this from here and then based at the end, the sequence of the functions do not matter. So let's get it off the throw statement from here. And I want to make is the contact model on written on object Corresponding the i d received as perimeter. So all day return this dot contact model dot Find by the This is the function bloated by mangoes, which takes ideas. A perimeter. Andi returns the value the return value is received over here. And then further written toe nest nest is going toe respond the user with the Jason washing off their object. So let's go back to the postman sending this request and see if we are able to get the actual data. So I'm gonna click on send and you can see we're able to get the contact corresponding to the idea I supply. However, if I supply and I did, that doesn't exist. For example, I'm gonna make some change to the last three characters. I'm gonna type. You're a one D, which is a valued Exodus Immel number as well as a valued mongo db object Ready, Hollywood. There is no data corresponding to this while I expected for not for you can see that I still get 200. Although there is no content. The reason behind this is if I go back over here, the return value from this particular function is not really a contact object, but a promise object. A promise has to outcomes. Either the promise gets a result. That means I get a contact object or the promise gets rejected. And here, since we're returning this back toe nest nest identifies that this is not a regular JavaScript object. But this is a promise object and Nestor's will result. The object which eventually becomes either a valued contact object, are an industry, and the same thing is returned back to the http client. So if I want to handle the promise resolution by myself, then I have toe collect this promise. So I'll say Let probably let's call it S p r equals two. And if PR is result to a valid contract object, I have to return. The same fpr is result to an empty string. Then I have to throw a not phoned exception in the earlier days of JavaScript working with the promise object waas Little difficult, but with the introduction off a think await keywords, handling promises becomes very easy. For example, we know that on the right hand side is a promise that is ascent over here. But Instead of assigning the promise to this, I can say let the promise be resolved so I'm gonna evade that process. So which means that the promise will be resolved first and the resort where you will be assigned today. So no, this is no longer a promise, but this would be a valued contact object. And now I can check your If see, that means it is a valid contract object. Oregon's A if not see where it is an empty string are undefined, and I can say throw new, not phone exception like this. And in case if C is a valued contact object, I'm gonna say, written c, you can see that there is one other over here. That's because if you're using an await keyword inside a function, the function has to be marked as he think. So I'm gonna do the same thing. And now my function is really let's go back to the postman and try the same thing. So this is a non existing idee I click on send. I do get for not for but if I send a valued request, then I should get the corresponding contact object. You can also try sending some arbitrary value here. For example, a SDF No, not that This is going to be assumed as a valued mongo DB object really format. But this is not. It is supposed to be a 12 bite hexi decimal value. This will result into an exception. Buy mangos on that exception will cause ever 500. When active consent, you can see that we got status called 500 internal server error. If you want, you can write your own subclass offer http exception plus and then throw the same thing to get a customized other message, which we have done in the past. So that's all for this lecture. See you in the next one. 36. Update a document via PUT request: Let's say we want to update the details off a document or contact object based on the idea given we have to supply the idea as a part perimeter on the details off the contact that we want to update using the request body our payload. The body may or may not contender underscore Heidi. Even if it contained the underscore 80 that should not be considered for quieting the I. D. Supplied as part of the part perimeter should be used for searching and updating. So here is the result off a get request for this particular Ural that contains this. Heidi, we want to send a put request for the same by sending a payload that contains modified details over here To do so. Let's copy this yarn and then go to a new tab. Select the court request. Basically, you're in. Select the body, make sure that it is raw, and then the Jason form it over here. That's also copy the current value off the contact object. So I go back over here, copy this, come back to the port and in the body were going to send it, and I don't need to send the underscore eighties. I'm gonna remove that part and let's say we want to change the email. I'm gonna change this part of the email and say that this is going to be gmail dot com And if I send it, I'm gonna get a fortnight for because we haven't implemented the put request as off now. But that's what we want to do now. So let's go to our rituals to their core and implement a handler for this particular request. First, let's go to the controller at a day rate put decorator. It's important the same and in the black idea to give a string that represents the part perimeter. I'm gonna call it as I d and the name of the function. I'm gonna call it us off date contact, and it's going to receive two parameters. One is the idea, which is the part perimeter on the 2nd 1 is the body, which is nothing with the request body. In order to map the part perimeter toe this variable, we have to say a direct problem. Press enter and in brackets specified the part perimeter name. And here we're going to say at the red body to associate the request body with the variable body. Unlike the previous few request handlers. This time I'm not going to return any value from here. But I'm simply going to call the update function from the salaries. Andi in the service. We don't have the update function yet, so I'm gonna call a non existing function. I'll say this start service dot update contact, and I'll supply the same parameters I d and Body, as you know, that we don't have this function. So we had to create one. So I go back over here. All right. A function called update contact that receives idee and a contact object. We can also defend our data tape off this idea, which is nothing but the string on the contract itself should be off contact type and in the functions body. We can say this Start contact model dot update, which takes two parameters. The 1st 1 is a javascript object that acts like a filter condition, for example. I can say underscore idea is nothing but this idea Over here. We told the document that matches this particular condition that will be updated with the perimeter that I'm sending over here. if there is no problem in updating the contact, the control simply comes back toe here. And since we're not returning anything, there is no response. Body. However, by default they'll be a response. Status Court off 200 the http response code for indicating that the data got updated is 204 It's also called no content. We can define that in AD wants by saying whenever the responses, given that it's TDP court corresponding toe. This is supposed to be 204 African. Is the http status dot no content. Also, we want toe into the very the proper validation. For example, when the payload is received, we want to validate this against the contact. We can say your body is off type contact and then we say here at great use pipes and in the perimeter, I can say new valuation pipe In cuddly bracket, we supply a conflict object transform colon truth. One thing you must know that this function returns that promise. The promise has to old comes If the promises rejected, then there'll be an exception. If the promise is result, then that result value will be given back to the user, but we're not getting anything from the function, so the next chase is never going to decide the promise, and it never handles that. If you want to handle the exceptions by yourself, then it is better to say await, which will resolve the promise. But if the promise has been rejected, then they'll be an exception. We can surround this with a trick at, so I'm gonna just, temporarily cutest put a try, catch block and then paste inside the tribe. Log on in the catch block. I get an exception object. And then I said through new http, exception are since the era is most probably because you have given a duplicate email or duplicate phone number. This could be a candidate for bad requests. Exception, which will automatically send the response court off 400 await keyword can be used only if the function has been marked. Boesky think so. Let's do the same thing. One last thing is that since we added the await keyword, that means this function should return something which is supposed to be a promise. But if you go to that function, you see that we haven't returned anything, so I'll have to do is to say return from here now in the controller calls, dysfunction would return a promise. That promise is going to be a result. And in case if there is no problem, the user will be given a response off status scored 204. But if the promises rejected, there'll be an exception. We are further throwing a bad request exception, which will result into a state escort off 400. So let's go to the postman and check it out. So I'm gonna send the same request once again and you can see that we got the response scored off. 204 which means it has been updated successfully. There was no exception in order to check if we have got the email properly, let's copy this I d. And then go to the Mongo de Bischel and verified by ourselves. So I have the shell open here. I can say db dot contact start signed or find one where Underscore Idea is nothing but object idee off this value. And then when I pressed enter, you can see that it has been updated toe Jimmy. We can also very for the same thing from postman. By sending a get request for this Europe and take on send, you can see that we got the updated data back. However, while sending the data if I did not send the email are probably it is not a valid email. Then you will see that you get the validation error because we're using the validation pipe . Also, if I send an already existing email, for example, if I remove this and put my email, which is already there, we know that we know dot Co. This is also going to be another because duplicate emails are not alone. Also, duplicate phone numbers not alone. If I click on send now, we're going to get the state of scored as 400 because there is a bad request. We threw a bad request exception. We got one with this Now our put request handler easily In the next lecture, let's read 100 for delayed request 37. Delete a document via DELETE request: let's implement the delete feature in the bottom up approach. So I'm gonna create a service function first. Unlike the previous examples that they delete contact and then take idea the perimeter off string type and inside the function, I'm gonna say Return this start contact model dot Delete one. We have to supply quality. That filters one record based on the idea. So I'm gonna say, Curly bracket, which the Jason object, I'll say underscore. Ready colon idee. Let's put a semi colon And now my surgeries function for the leading A document is really the function returns a promise object. The promise object is supposed to be received in the controller. And then either we can return the promise directly toe nest, which eventually will result that are we can resolve it by using the casing await keyword just like the way we did it in a couple of examples, and in case if there is any exception, we can throw the same thing. So first, let's write the ad rate delete and in the bracket, we're gonna receive a part perimeter colon I D. As in the previous case, if this operation is successful, let us simply respond the user with 204 which indicates everything is okay as the less there has been an update on the backend. So I'll say here at the rate, http, Cool and then directly I can say 204 r As a good practice, you can say it's GDP staters dot no content and the function. We will start with a think because we want to write a weight cable inside the function. Let's write the name of the function as delete contact and then the perimeter. Whatever that we have got over here that has to be assigned to a variable cell, say moderate bottom off idee should be assigned to a variable. The variable name itself can be anything. I prefer to give idea itself on off the type string and inside the function, we're going to say Let the return value from the service function. We want to say a weight because we don't want a promise. We want the promise to be resolved. I said this start service dot delete contact and we supply the idea we received. This is supposed to give me a promise object which is going to be resolved And if the promises results successfully, the result While it will be assigned to this, this is not actually the Mongo DB document, which represents our contact, but instead it represents some kind of a status object. This will have a property called dilated count. So if I have deleted multiple documents than the deleted account will indicate how many documents have been deleted in the baby aisle, said the Delete one. So it is going to come as one, but in gratified supply that wrong i d. There will not be any exception, but the dilated can will be zero. We will capture that information on then check if red dot deleted account. This is the building property that Mom, who's gives us on mangoes gets that information from the manga levy. If this is equals to zero, that means the idea that you supply is wrong. It was not phoned, so we will throw an equal, an exception called not phone exception. And now our comptroller under service function. Both of them are ready. Let's go toe postman sending a deal it request for an existing document. First in I should get 204 if I send the request once again. Then it should give me a four, not fall. So let's go to the postman. Send in a village request for this itself. Currently, if I click on the send button using the get request You see, I'm able to get the data. I'm gonna sell it this deleted from here. Send it. You can see we got to not four, which says no content. That means the record has been successfully deleted. So if I go and ask for days, you should see that I should get a fortnight for as well as if I send the deal it request once again because the document doesn't exist with this, I d the should again come back with a fortnight for and we got it. So this is how you handled the delete request in a nest application? 38. Partial update of a document via PATCH request: Now let's throw it the partial update facility, which is nothing but hits TDP patch request. And this time we are supposed to receive the part perimeter as well as the body. But the body may not be exactly same as the contact model, because I might have sent only the email are only the state. It depends. So we're gonna write a patch handler like this at the rate patch, and then the perimeter is slash colon idee. Once again, we want toe send a no content. When we're doing an update, we simply want toe send the state of Skordas 204 So I can say I did. Http, Cool off its TDP status dot No content. And as in the previous cases that also read than anything function called us patch contact , which takes I d and then body are probably concolor. This prompts because they're just bunch of properties. I need to map this part perimeter toe this variable and then body toe This. So let's add a great bottom and then say that it's gonna be i d. And here we're gonna say at the red body, which reads the request body and assigns a javascript object toe props and tow. Handle any promise rejection. We're gonna put it. Try catch in at once. We will say, Wait, this start service dot Probably I call it us Patch Contact itself, which takes idee and props as perimeter. A distant dysfunction doesn't exist. That's what we're getting. Another. We will click your and then press command out are controlled out. Declared a method. So it adds an empty metal in the service and in the catch block. Let received the exception. Andi read Throw the same in the form off new http Exceptions All said, throw new http exception It takes exception are a message of the first perimeter on a state of scored. I can say http status dot internal Sarwar era, which is not about 500. So let's go to the contact Service where we have a empty patch function over here. I'm gonna Curtis and placed it at the end. Although the sequence is not important, let's get it off this throw statement and we don't this start contacts Model Dart. We have a function called abd it, which takes a couple of perimeters. The first parameter here is nothing but the idea that we are going toe search for which is not underscore idee colon i d the second perimeter. If you supply the props, the entire contact object that was searched will be replaced with props. But we want to do a partial update. That means whatever the key value pairs that are represented by props, that we want to overrate our ad retaining the remaining properties intact to do the same. We have a property called dollar set and then we have to supply What are the key value pairs that we want to update, which is not too much prompts with this now, our patch contact function is already let's go back to postman, send in couple of requests and verify the same thing. I'm gonna send in a get request for local host 3000 slash contacts that will give me on the existing document. I will pick one off the I D. For example, I'll take this one and then send in a patch request by changing its email. So I'm gonna goto a new time, select a patch request. Over here it's TTP Locals 3000 slash contacts slash the i d. But in the body as raw. Jason, we want to send in letter, for example, and email. Currently, the email happens to be this one. However, we want to change this toe Benjamin at example dot com. So I'm gonna say your email is Benjamin at example dot com. Probably I can also change the state. Let's say, for example, toe Texas and take on send. You'll see we got 204. No content. But if I send in the get request now for the same Ural, we should get the updated email instead. And as you can see, we got the updated email on updated state. And, as usual, if I'm going toe, send in a patch request by sending the existing email, making it a duplicate that will throw an exception, which is going to bay returned to me as a Status 500. With all the exception details. Let's try sending my email, which is we know I'd be no dot co click on send. I should get the exception, and you can see the detail editors are coming. It also say the exception state does this 500. So this is how you can implement partial update using messages. Mongo db mongrels combination 39. Connecting our app to Mongodb Atlas (Cloud): Now that our application is really on also has been tested with the local copy of Mongo DB Server. Let's now try to connect toe a mongo DB Cloud server, which is provided for free. Of course, by mongo db To do so, visit mongo db dot com On on the home page on the right side, you have a try free button. Click on that on. Then you see three options. You can see that the green color bought here indicates this is the one that is selected by the front earlier. We don't order this one. Andi set it up on your local machine. We used it. Not this time. We want to sell it the club. And here you might have to do a couple of details. Number one is the company which says optional. So I'm not going to give the same. I'm gonna get the email as Kamar at we know Darko. First name. We know last name common password. You have to create a new one. Minimum eight characters are required. Agreed to the U. S. And privacy policy Get started for free. Since we are being presented with different options, I'm gonna go with the free cluster over here. So the Mongo DB Server is hosted on AWS Google Cloud as well as Microsoft Azure. And the default selected here is terribly ISS Andi. It also asked me to select a different region. I would like to live it to the default and then click on Create Cluster over here. And as you can see that it says your cluster is being created. We may have to wait for roughly around 1 to 3 minutes after a couple of minutes. It has bean created on. No, there are a few options for me. The first option I have to choose is the connect and then it'll ask you what is the white list connection I p addresses since we are running it from our local host. At this point in time, we may have to add the I P address off our computer other ways, you might have to give a different I p address. For example, when we deploy this on toe heroic Ooh, are any other clothes or worse, we may have to add a different I p address, but for the time being, I toe add my current I p address. So when I use postman toe, make a request over Resting Point running on local host that local host will intern. Connect to the server. So I have toe this I p address. If you only can also give a description saying that, for example, we know it's laptop click on Add I P address and that is now recorded. It also expects a Mongo DB user. And if you have observed that in our local installation off Mongo DB, we don't have any user name or password here. We're going to give a user name. I'll give the user name as for example, I mean and then let's give the password. And, as you can see, it also suggest a strong password. We can use the same thing and click on the generated one, and then it says, create mongo DB user. Let's click on the button, and in the next step, it says, choose a connection mattered. So let's click on the same. It says you can connect with the Mongo shell like what we have right now among Ghoshal running on our local computer. We can use that took on it are you can take connect your application. This is what we want to do because we have return a software application. That application has to connect to this mongo db. So let's click on this one. And it says here, this is the U R L that we have to use when we're tryingto connect toe this Mongo DB Plus, Let's click on the copy button toe, copy the store clipboard and then take on clothes. No, the door cluster is really let's goto RVs scored open at modernity is and this is where we had given earlier. The local host you order will replace this with the actually oral to our mongo db a close. I'm gonna pace that we have to replace this password with the actual pass were So let's do the same. And also it says, What is the name off the DB, which I'm going to give it as a phone book Now our next year's application is going toe connect toe the remote mongo db server. Now that we have made the necessary changes toe the mongo db, you are Onda nest J sir, what has already been restarted? Let's go toe postman and send in a request to get the list off all the contacts. Because the mongo db Star work cluster is a brand new one. There are no contact, so we should get an empty list. So I'm gonna send in a request toe Http equal and local host Colon 3000 slash contacts Click on send. You can see that we got a m d Addy. However, if I'm going to send in a new contact where the post matter, this will be sending a request to the remote mongo db server on a new document should be added over there. So let's change this toe post sending a body raw. And then Jason, let me send my details. So I'm going to stay here. Name is we know. Come on, he made we know I did. You know dot co phone number is plus nine one. The country cord is important. I'll add 9 71 424784 These are the mandate refuse on. Also, we have satisfied the valuations, so let's click on a send and see what happens. As you can see, we got a response 201 created as well as a new I. D. has been generated. If I'm gonna make a good request once again for local host retailers and slash contacts, click on Send and you can see we get an array off one document. We can perform all other operations. Like, for example, I want to send in a patch request now. So I'll say patch and then send in, Let's say, for example, city off bangle on. Then let's a country off India. I also have to send in the I d in the park perimeter here. The idea is right here. I'm gonna copy this. This is the response from the Post. I put a slash here based it now effective consent. It will come back with 204 which says that no content, but if I'm going toe, make a request for the same. You should see the rest of the details along with city and country as well. Now that we have added one document and then send in a patch request let's go to our actual mongo DB cluster on DSI that there is a button called collections over here, clicking on which it will take me toe the list of collections and you can see that there is a deep vehicle phone book. If I expand that there is a collection called Contacts Clicking on which you can see that it shows me the list off all the documents, which is not about one single document at this point in time. So by just changing one single line off court over here, you can see that our application now works with really mongo db server on the cloud in the subsequent lectures that's building deploy our application itself on toe 1/3 party rial Sarwar like hello. 40. Creating an account with Heroku: now that our application is really it's time for us to deploy the application on any cloud platform. Onda Hello co dot com offers one such. It is a platform as a service based on managed container system with integrated data services and powerful ecosystem. For deploying on the running Modern APS, you can send up with Haruko for free. On day, you will be able to deploy I maximum of five applications. These applications may include no Jace applications or springboard applications on a verity off other products. So let's go ahead and click on the sign up. Fill in the name I'm gonna take my first name, last name email address. I'm gonna use my Gmail for this company. Name optional. You can leave that role that select hobbyist country India. Select a language nor Jace. Let's confirm that we're not a robot. Selecting few cars. 123 Very fine Creative free account. And here it says, Please check your email to confirm your account. So here is the mail. I just had to click the link that is given over here. Let's create a password and come from the same click on set password on log in. I know it is a new account for higher tired are we not? A gmail dot com is all set up. Click here to proceed for their and here it is. You don't have any applications yet. Every happened by plane you create or become a collaborator on will appear over here. We have already created an application using next year's on our desktop. We want that to be deployed over here. And to do that, we are going to make us of something called heroic Aussie Ally, which will go in the next lecture. 41. Installing Heroku CLI: in this lecture, let's install head Oecussi a light. The installation procedure is a bit different on different operating system on. They're all very well explained over here. So if I click on this download and install link, you can see that it is on backwards. I have to copy and paste this command on the terminal, but as on Windows, you have a 64 bit installer. Download this and double click the installer. It'll open up. A reserve finishes the task on Lenox operating system like pronto. You can copy this and based it on a terminal press. Enter. The installation is going to be done. Apart from these three, there are other methods. For example, we have install NPM. We can use the NPM install Dash G Haruko Comment to install the C. L. A. As well here. It says it's strongly recommended that you use one of the other installation methods is possible. This particular installation matter does not auto update and records you to use your systems washing off Noches which may be older than the Washington Haruko develops the cli agonist. However, in the beginning of the course, we installed the latest version of Norges. We probably may not run into this problem, so I'm gonna use this NPM install Dash G. Hiroko Since I'm using mac ways, I have to also perfect the same thing with pseudo. This is same thing, even for a bento or any other leaners For Windows users, you can just open a new command prompt and type in this command. So I'm gonna go to the new terminal, type in the commands pseudo npm install dash G Haruko with and don't enter the Super User password. It took a couple of minutes for me toe finish the installation. Now I can type your hair Coco dat stash Watson and we see the Washington installed. Now using the heroic Basilea, we have to log in to the conduct we have created. So I'm gonna take your heroic ooh space log in press enter. So it says, press any Kato, open the browser to log in our Q toe exit and press enter and it has opened this dialog box all have to do is to click this logging thereby were attended gating heroic OSI Lato access our confidence and it says you can close this page on Britain to your sea life. So that's going to close this one and you can see it is long. Dennis Chire tired. What we know at gmail dot com Now that we have the heroic Aussie ally ready and logged in, we can now push our court from our desktop to the Haruko Sarwer. 42. Deploying our application to Heroku: in this lecture, let's deploy our application toe Hello. Coup on. But there are few changes that we may have to make in our so scored as the less mongo DB server. The first thing you have to do is tow not assume that this port number will be available in Haruko. We want toe ask heroic. Oh, that. Give me the port number. If you don't give them, I would like to use sport number 3000 to do that. Let's declare a variable called port equals toe process dot e and b dot port. If there is not available, let's take 3000 And now I'm gonna use the variable port instead of 3000 over here. The second thing is that when we deploy our application toe head aku, typically we access these restaurant points using applications like angular, our reactors deployed on a different server. So you won't be able to access this unless you enable something called cars. Cars stand for cross origin. Associating all you have to do is to say at dot enable cars. This will take her off, enabling cars by Aisling additional response headers. There is no other change required in our application. Our application is ready. However, when we deploy our application toe Haruko, the application running on Haruko will try to connect Mongo DB on mongo. DB will not allow that to happen. And this is family because in Mongo db we have enabled only the local I P address. Either we have to give the Heracles I P address are we can say, let our database be accessible from anywhere. So let's go to our mongo db dashboard on. You can see that there is a option toe. Connect the metrics collections. We have seen all these things here. There is an option toe change the network access. Let's click on the same as you can see. There's one entry here, which is nothing but my i p address my laptops I p address. I'm gonna delete this and then click on Add an I P address. And here is an option to say hello access from anywhere. Ideally, you shouldn't be doing this. He should give the actual white list address so that your baby is secure. But this is for a demo purpose. Instead of finding out what is the I. P address of Hiroko and adding that over here, let's click on confirm and now our Mongo DB database is accessible from any I P address before we actually go and start the deployment process. We also have to create an application in Heracles. So let's goto a new tab and then goto Haruko dot com. Since I already loved in, it takes me directly to my dashboard where I don't have any app. So the name of the APP must be unique among other applications deployed on Hiroko not only hours but by other developers Also. So, since my application is about next year's on the phone books, I'm gonna give the name as nest JSP phone book. Andi it will give me with that. It is available or not, it said. It's not days, so let's change the name, toe nest dash phone book and it says this is available. Let's click on Create Up. The next step is toe Link, this nest phone book application on the Hiroko toe, our application that's currently available on our desktop, and that is done with the help off the heroic Aussie ally that we have installed. So let's go to the terminal and issue the 11 commence. The first thing I have to do is to ensure that I'm on my project medically, which is the stop slash nest dash mongo db. That's demo. You should first use the gift, innit? Command toe initialize this. When we created the project, there was already a get initialization on just to make sure we're gonna initialize once more so you can see it says Grealish. Allies existing git repository on the second command usedto use the Haruko, see a light toe. Connect this application to the application that we have created on our Haruko dashboard. And that is done by typing the commander Hiroko space. Get colon remote dash a on the name of the application were created So the name is nothing but Nestor Dash phone book press enter and it is now said the get remote as get dot Haruko dot com slash nest dash phonebook target There a couple of steps that we have to take before we push our court to Haruko First we need to make sure that the environment is configured correctly by running these commands. The number one command is Hiroko Config Colon set NPM underscore conflict under scope production equals toe once, and the second command is Hiroko Conflict Colon set nor underscore. PNV is nothing but production now. Most likely this has already been set, but we're just making sure that it is said to production. Heroic also expects a file called Rock File. This is the file that acts like the initial file to be read by Haruko. And this is where we mentioned what is the actual Commander Hiroko should run so that our application starts. And here I can simply type equal Web colon on the Commander's NPM Iran start colon prod. So we want to run the production wash in. This has to be appended to a file called Brock. Fine. And if the file doesn't exist, it gets created. Let's press enter. And now we are ready toe push the court from our desktop toe the Haruko get repository and this in walls typically three commence number one is toe Add all the files that we want and we want to add all the files and the fights that we don't want to send their already being listed in the get ignore. If you go back to the court, you can see that there is a get ignore on the slash days to slash North models. All these fights will be ignored and only our source code would be added toe the Haruko repository. So let's press enter. The second command is toe commit so the commanders get commit dash M and some message in it to give. This will help us identify different get comets. Let's pressed. Enter the last comment toe push. Our court is get push heroic. Oh, and then master. So when we presented our it's going to start the deployment process. Rest enter and you can also go back to the browser on If you go back to your nest phone book or probably few refresh over here, you can see it's this building progress. So let's go back to the command front on Did saying here will be succeeded. So it has given us a Ural here hits to TPS Colon double slash nested ash phonebook dot Haruko at dot com. So if I try to access this Ural on the browser, I should get the hello world message as well. If I say slash contacts, I should get the list off on the context that we have in our mongo db. So let's go to the browser and test the same thing. I'm gonna open a new tab based that press enter. You can see you got a lower message. And if I type your slash contacts, I have only one contact, and that comes as an area here. Let's go toe postman either contact and very for the same. So let's copy this. You are Goto Postman at a new tab. Let's make a post request toe this year. Orel, that's like the body wrong. I'm gonna select Jason from here. The minimum requirements are name, email and phone. Of course, if I don't send that data, we should have some others, and you can see that it is Name must be there as well as email. Must be. Their phone must be there on the validations that we have created. So let's go and type in a name. Let's say show female. That's give some at example dot com on a dummy phone number. Make sure to include the country cord because that's as part of the validation. Let's give some arbitrary numbers. Click on send on. I got another saying Phone must be a valid for number because I missed the one digit over here. So let's have some dummy number. Click on send again and you can see we got ourselves a new document. So if I copy this on goto a new tab, make a get request, we should see two documents. So congratulations were successfully able toe deploy our application on toe. A very popular cloud based server car. Heroic. Ooh.