How do I practice NestJs? — NestJs + GraphQL + TypeORM + MongoDB
“ I wrote this topic to record my own self-learning journey as well as share anybody about them. ”
1. Requirement
- NestJs
- GraphQL
- MongoDB
2. Table of contents
- Initialize NestJs project
- Create folder User
- Demo query “Hello world” with GraphQL
- TypeORM connect MongoDB
- CRUD with object User
3. Practice
A progressive Node.js framework for building efficient, reliable and scalable server-side applications.
Setup
// Setting up a new project is quite simple with the Nest CLI$ npm i -g @nestjs/cli
// or
$ yarn add global @nestjs/cli// Create new nest project
$ nest new project-name
Run It!
// Development
$ npm run start
// or
$ yarn start// Watch mode
$ npm run start:dev
// or
$ yarn start:dev
Logger
GraphQL
Next, we will integrate GraphQL with nest via here
First of all, we must config tsconfig.json
Second, we need to install the required packages:
$ npm i --save @nestjs/graphql apollo-server-express graphql-tools graphql$ yarn add @nestjs/graphql apollo-server-express graphql-tools graphql
Nest offers two ways of building GraphQL applications, the schema first and the code first respectively.
In this example, I will use schema first
I use Nest CLI via here to generate code.
$ nest g mo user
$ nest g r user
$ nest g s user
Next, I touch user.graphql in user
$ touch src/user/user.graphql
Finally that we have a new folder structure like that.
Demo query “Hello world”
We declare query hello below
Yeah that’s working
TypeORM connect MongoDB
Base on nest via here, we have to install all required dependencies:
$ npm i --save @nestjs/typeorm typeorm @types/mongodb mongodb
// OR
$ yarn add @nestjs/typeorm typeorm @types/mongodb mongodb
CRUD with object User
Read more TypeORM entity via here
Back to a user folder, we touch 2 files user.input.ts & user.entity.ts
$ touch src/user/user.entity.ts
$ touch src/user/user.input.ts
Create User, UserInput, users, createUser in user.graphql
Then we provide user entity for user.module.ts
At user.resolver.ts, we will inject user.service.ts and declare query, mutation
Similar, we will inject the user entity in user.service.ts
we will use uuid v4 for user._id
$ npm i uuid
If you want to perform updates and deletions, you can refer to the source below
Thank you for reading this
I am Chnirt and I will see you again in next episode.