This is first part of series "How to build graphql API with mongoose and NestJS"
Not a long topic, but I wish to keep it simple and brief.
Before we jump in, I assume you already have an idea of Typescript & OOPS has it installed on your machine.
Part I:
What is NestJS?
It is a framework to build server side applications. Thereby provides robust and scalable applications. It has a ton of features built in & is also capable of custom plugins.
TL;DR - Angular for backend
NestJS can use express or fastify. You need to define it explicitly which to use while setting up your project
How to install?
To install nest:
sudo npm i -g @nestjs/cli
To create a new nest project:
nest new <project-name>
A basic nest project structure:
dist/
node__modules/
src/
- app.controller.ts
- app.module.ts
- app.service.ts
- main.ts
test/
.eslintrc
nest-cli.json
package.json
Readme.md
tsconfig.build.json
tsconfig.json
I won't go deep with "NestJs project structure", but this is something you should understand to further advance in this series.
NestJS comes with facility to write unit tests and do end-to-end testing as well.The main core lies in the src
folder where all the magic happens.
How nest carries a request?
This is an example of how a request is processed
Controller class will route the request according to the method.
Service class will manage the business logic and does the math.
Module class is responsible for importing all dependent modules, classes & bind them together.
This will ensure we can quickly develop modules in organized fashion and readable code.
If you encounter some line of code like @Injectable()
are decorators, it will basically just inject dependency modules into your class so you don't need to bother importing all those same modules every time. If you can, just do a web search about dependency injection
. It is a great read.
If you're new, just do npm start
and run the server. Open your browser and navigate to http://localhost:3000
and try to make sense of the controller, service structure.
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
@Get()
getHello(): string {
return this.appService.getHello();
}
}
@Controller
routes the incoming request with base url ending with /
to it's particular method.
In our case, it is GET
and function to be called is getHello
.
This function invokes the method called getHello
in app service class.
Image credits: Santosh Yadav
Now, I'm bluntly assuming you have a basic idea of how nest can produce a web app. You can peep into package.json
file for all scripts to run the application.
If you don't want to reload your server for every change, you can run server in watch mode like this :
npm run start:dev
Stay tuned for next part of the series where I discuss how to use MongoDB to build GraphQL APIs.
It's an immense pleasure to know what you think in the comments below. Peace βοΈ
Top comments (0)