Simple NestJs App With MongoDB



Most of you interest in NodeJs frame work must have heard about NestJs ,but what is this?
NestJs is a simply Nodejs framework built on ExpressJs.
On the contrary of Express Js NestJs uses Typescript and that means more safety and less bug.
There are many advantages using NestJs for Api;

1-)Efficient,scalable Nodejs server-side applications

2–)Uses typescript safety but in the same time it allows you to use vanillascript

3-)The architecture and the way NestJs suggest to us is highly testable, scalable,structured.

4-)One of the most importing things is that popularity and resources of the NestJs.The documentation includes everything you may require to know.Also if you have issue or bug you can easily find that on Google.Bcz i tried :D

5-)The other thing is like multer,cors or so on you dont have to install most packages because they are coming within NestJs.

To now we have talked about NestJs ,but how we can build a Restful API?

We are using CLI(Command Line Interface) of NestJs and we should install it firstly;
npm i -g @nestjs/cli


For creating a new project;
nest new project-name


Now let’s look into the file system of it…
Test folder is for testing our API ,but for now don’t think about it because the magic is happening in “src” folder.

If you don’t know Typescript it can look a little bit strange ,but ı will simply expalin it.When we run our application the CLI converts them to Javascript.

So,the first file will run is main.ts file.In here we are setting up our base module.Then listening the port we want.

For starting our backend app;
npm run start:dev

So now;

Our server should be started.
Like you see in src folder there are 3 other files other than main.ts.
Let’s examine them huh?


app.module.ts

This file works after than main.ts and module file is basically introduces our file to our Nest application.Like that Nest knows where to look for controllers services or other things like that.

app.service.ts

This file the place where we are gonna sende database requests.

If you are not familiar with decorators the @Injectable() must be look weird.
Injectable decorator practically tells NestJs ,yeah this class is a provider for our server.

app.controller.ts

This file handles the incoming requests.If the database request should be necessary we call the service class’s functions.

And that’s it basically you have an API which handles only ONE GET request and this endpoint’s response to you is Hello World! :D

Credit Source: Musa Şahin Kundakcı
Previous Post Next Post