Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications.
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 main reasons why you should consider to use NestJS as framework in your projects is because it’s very powerful but super friendly to use, documentation is very easy to understand, provides very easy development and testing, supports Typescript and GraphQL etc.
In our project we are going to build simple backend application for storing and retrieving notes.
At the bottom of this article you’ll find sample code, so you can check it in case if you have some problems with following the steps described in this article.
In order to create new Nest application, we’ll install Nest CLI and execute command for creating new Nest application:
npm i -g @nestjs/cli
nest new nestjs-mysql-typeorm-sample
And choose npm as package manager.
In the app, we are going to use MySQL database and we are going to use TypeORM library for storing and retrieving data from MySQL so we need to invoke the following command in order to install these libraries:
npm install — save @nestjs/typeorm typeorm mysql
In order to setup TypeORM connection to MySQL, we need to create ormconfig.json with appropriate MySQL configuration data (please make sure that you specify the right username, password and database name):
TypeORM configuration data will be loaded from ormconfig.json file, so in in main application module file (app.module.ts file) we have to import ‘TypeOrmModule’ by invoking ‘forRoot’ without any options:
As we can see, NestJS app structure is made of three core files:
- app.controller.ts - basic controller with single route
- app.module.ts - the root module of application
- main.ts - the entry file of application which uses the core function NodeFactory to create Nest application instance
Because our application will provide only one feature and that is creating, updating, retrieving a list of notes, we are going to create appropriate notes module, service, provider and controller (all of those in separate notes folder). By doing that, we are clearly separating notes functionality from other functionalities that application might have and we are making the code cleaner and more readable.
We’ll put some validation of model fields, so we’ll need to invoke the following npm command and install ‘class-validator’ library that will validate our model object, when user will try to insert new or edit an existing note object in database:
npm install class-validator
We’ll also install ‘class-transformer’ package that will allow us to transform plain object to an instance of class and vice versa:
npm install class-transformer
Before we are going to create controllers, services and other classes, let’s us create our main data class, Note entity object (in ‘notes/Note.entity.ts’ file):
As we can see, Note entity class contains different decorators. TypeORM related decorators are: ‘@Entity’, ‘@PrimaryGeneratedColumn’ and ‘@Column’. Class validator related decorators are all other decorators related to data type and value validation, for example ‘@MinLength’ or ‘@IsString’.
The next class that we are going to create will be notes service (‘notes/notes.service.ts’ file) which will be responsible for providing methods that are retrieving or storing data in MySQL database, to our notes controller:
As we can see in notes service, there is a lot of methods that are responsible for storing or retrieving notes from MySQL database, all done by using repository data pattern provided by TypeORM.
The next class that we are going to create will be notes controller and his main responsibility is to handle incoming requests and return response to the client:
In constructor we are injecting notes service, that will handle MySQL database operations, via notes repository. Every method in service has it’s own appropriate decorator (like ‘@GET’) and it’s assigned to appropriate method which this decoration handles. Each method with decorator is handling appropriate HTTP method call (like ‘@Get’ decorator handles ‘HTTP GET’ call).
By now we have created notes controller that will handle incoming requests and it will return response and note service that will be used for data storage and retrieval.
The last part is to create notes module that will make keep notes-related dependencies organized under the same file:
and we need to import notes module in app module:
In the main entry file of our application (file ‘main.ts’) we need to set that app uses ‘ValidationPipe’ which will ensure that all endpoints are protected from receiving the incorrect data. Also we’ll enable ‘CORS’ so we can access our backend app endpoints from frontend applications.
Make sure that port is set to ‘3001’, because our frontend application that we are going to create in this article will point to port ‘3000’.
So, now we have prepared everything that is required for our backend app to work and we can start it by invoking the following command:
We can try to insert new note via Postman:
and we can also check if validation works by providing the invalid ‘description’ data:
Congratulations, we have successfully created NestJS backend app that stores and fetches data from MySQL database.
In the next article we are going to explore how we can display notes data in React frontend app:
Source code of sample app built in this article: https://github.com/zsasko/nestjs-mysql-typeorm-sample
Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!