Create an API via NestJS Part V
In this part, we'll create a User module.
Firstly we have to set up the scaffold
nest g module user — generate module
nest g controller user — generate controller
If everything is alright you should see the new folder in your src/. It must contain files:
- user.controller.spec.ts — tests for controller
- user.controller.ts — the controller file (for more information follow the link)
- user.module.ts — the module file (for more information link)
After that, we can create the service file
nest g service user/user
This command will create a subfolder in your user folder named user. It quite comfortable for me but if you used to flat project structure you can run this command just: nest g service user/
Now let's create DTO and Entity files for user module
touch src/user/user.dto.ts
touch src/user/user.entity.ts
Finally, install necessary packages
yarn add jsonwebtoken @types/jsonwebtoken
yarn add bcrypt @types/bcrypt
Let's describe the user data model
Open user.entity.ts and write something like this:
Line 12 — declare new entity named 'user'
Line 14-15 — create autogenerated column for user id
Line 17-18 — create column to store date user had register
Line 20-24 — the unique column for user id, it needs for decline registration with the same username
Line 27-27 — column for password
Line 29-32 — function witch called before password could store. This function hashes the user's password before we stored it in the database
Line 34-41 — this function will return UserObject after registration
Line 43-53 — getter function for JWT token
Line 55-57 — password comparator
Not to forget add your SECRET string into .env file, it should be like:
And import it into user.module:
Describe UserDTO
Create some methods for user module
Open the user cntroller and create register, login and get all users command:
let's implement our service methods
Firstly you could create dummy functions
Now we can implement getAll() function:
We use responseObject(false) because we don't need to get JWT token in this case
Next we must implement login() function:
And finnaly implement register() function: