Part 2. Clock-in/out System: Basic backend (I) — AuthModule
Tags: javascript, typescript, node, nest
Published: 2019-02-26 23:02:51

---
title: Part 2. Clock-in/out System: Basic backend (I) — AuthModule
published: true
description: In the first post we described the different components of our clock-in/out system. So, if you don't understand the architecture of the system you can read that post because I've described each component of the system. In this post, I’m going to describe the basic backend using NestJS. The first step is understand which is the directory structure.
tags: javascript, typescript, nodejs, nest
series: clock-in/out system
canonical_url: https://carloscaballero.io/part-2-clock-in-out-system-basic-backend/
cover_image: https://cdn-images-1.medium.com/max/1000/1*KhCkmbtORw2Ux3n5WCrtzA.png
---

This post is part of a Series of post which I’m describing a clock-in/out system
if you want to read more you can read the following posts:


* [Part 1. Clock-in/out System: Diagram.](https://dev.to/carlillo/part-1-clock-inout-system---diagram-4kgj)
* [Part 2. Clock-in/out System: Basic backend — AuthModule.](https://dev.to/carlillo/part-2-clock-inout-system-basic-backend-i--authmodule-d2l)
* [Part 3. Clock-in/out System: Basic backend — UsersModule.](https://dev.to/carlillo/part-3-clock-inout-system---basic-backend-ii---usersmodule-5hf5)
* [Part 4. Clock-in/out System: Basic backend- AppModule.](https://dev.to/carlillo/part-4-clock-inout-system---basic-backend-iii---appmodule-5anb)
* [Part 5. Clock-in/out System: Seed Database and migration data](https://dev.to/carlillo/part-5-clock-inout-system-seed-database-and-migration-data-320m)
* [Part 6. Clock-in/out System: Basic frontend.](https://dev.to/carlillo/part-6-clock-inout-system-basic-frontend---angular-28pg)
* [Part 7. Clock-in/out System: Deploy backend (nestJS) using docker/docker-compose.](https://dev.to/carlillo/part-7-deploy-backend-nestjs-dockerdocker-compose-3cmb)
* [Part 8. Clock-in/out System: Deploy frontend (Angular 2+) using environments.](https://dev.to/carlillo/part-8-clock-in-out-system-deploy-frontend-angular-6-using-environments-nog)
* [Part 9. Testing: Backend Testing — Unit Testing - Services](https://dev.to/carlillo/part-9-clock-in-out-system-testing-backend-testing-3imk)
* [Part 10. Testing: Backend Testing — Unit Testing - Controllers](https://dev.to/carlillo/part-10-testing-backend-testing-unit-testing-controllers-573a)
* Part 11. Testing: Backend Testing — E2E Testing
* Part 12. Testing: Frontend Testing — Unit Testing
* Part 13. Testing: Frontend Testing — Integration Testing


In the first post ([Part 1. Clock-in/out System: Diagram](https://carloscaballero.io/part-1-clock-in-out-system-diagram)) we described the different components of our clock-in/out system. So, if you don’t
understand the architecture of the system you can read that post because I’ve
described each component of the system.

*****

Originally published at [www.carloscaballero.io](https://carloscaballero.io/part-2-clock-in-out-system-basic-backend/) on November 25, 2018.

*****


In this post, I’m going to describe the basic backend using NestJS. The first
step is understand which is the directory structure. If you use the NestJS
starter project to start a project you could to do the following steps:


After that, we need create our own modules structure inside **src** directory as
you can see in Figure 1.

![](https://cdn-images-1.medium.com/max/1000/0*GqK5UyoKrtcTMre4.png)

In this moment the server is running in port `3000` and the endpoint
`http://localhost:3000/` using the verb `GET` is working. If you navigate on
this address you get a message of `Hello World` as shown in Figure 2.

![](https://cdn-images-1.medium.com/max/1000/0*k2aQ_wzJv4RLrcoP.png)

### List of modules of the backend

The next step is define which are the modules need to our backend:

* **DatabaseModule:** This module is used to shared the database connection
between different modules.
* **AuthModule:** This module is used to register in the database when an user
clock-in and clock-out. The service **AuthService** will be the responsible for
save in the database when an user check-in and check-out. This module there are
not accesible since external. So, there are not a controller to communicate
using API.
* **UserModule:** This module is used to manage the user information. The
service **UserService** provide two important methods: **1. getUsersWithoutKey;
2. addUser**. These method are used to know that user have not a valid ID Card
and add an user to the system.
* **AppModule:** This module is the main module which will be communicate with the
frontend. In this module the others modules will be imports, so the services of
these modules can be used in this module. The main controller in this module
have the following endpoints:
* **POST: /in:** This endpoint call the method **authIn** from the
**AuthService**.
* **POST: /out:** This endpoint call the method **authOut** from the
**AuthService**.
* **GET: /users:** This endpoint call method **getUsersMustBeWorkingNow** from the
**UsersService** and combine the information together the **timestamp** of the
server.
* <br> 

### DatabaseModule

The module database is used to shared the DatabaseConnection. We’re using
TypeORM as ORM which is integrated perfectly in NestJS. So the definition of our
database.module is the following:

![](https://cdn-images-1.medium.com/max/1000/1*Nl8aQN58SwaIxHQ3IQJ_-g.png)

In the provider we’re defining our `DbConnectionToken` using a factory. In our
case we're using `Postgres` as database. So, the most interesting part is the
definition of entities which are automatically detect in `TypeORM`. Although
NestJS include a specify module to manage `TypeORM` connection, I prefer
configure the provider using directly the method createConnection from typeorm
library.

In this point, we must to install the following libraries in node:

`npm i typeorm pg`

![](https://cdn-images-1.medium.com/max/1000/1*-nncmGY2WJ3sPeXaXrjGJw.png)

So, the next step is install a database Postgres in your machine but I think
that the use of Docker is better option because you can get a clean environment
to develop which will be the same when you deploy.

So, the docker-compose in which you will be a container called
**PostgreTestClock** using the port 5531 is the following:

![](https://cdn-images-1.medium.com/max/1000/1*jVFM0iV6dwkcSOcIZX2Ksg.png)

So, to start the database of the system only run the command `docker-compose
up`. This module will be used by other modules to connect to the database.

### AuthModule

The second module that we have implemented is AuthModule, this module have the
structure show in the Figure 3. You can note that there are several directories
as constants, DTOs and entities which are used to organised a module
independently as a service. The idea is build as module as a service because any
day you could build microservices. However, in this project all modules are
relation between them because is architecture is very complex to this project.

![](https://cdn-images-1.medium.com/max/1000/0*xry_GvhDz7kzZKtg.png)

In the definition of **auth.module** you can see that imports **DatabaseModule**
and **UsersModule**. The DatabaseModule is used to connect to the database (show
previously) and the UsersModule is used to check information about the users in
the AuthModule. In this moment, the module UsersModule is still under
development (following post). The service AuthService is exported because the
future AppController will use this service.

![](https://cdn-images-1.medium.com/max/1000/1*qjZy1roqvEdEfhrMZh4r6Q.png)

### Entity

The next step is know that information is saved in the database. That’s define
using the file user.entity.

![](https://cdn-images-1.medium.com/max/1000/1*AAX9R7SUV8OmNyFATyozRg.png)

The fields the class AuthEntity are the following:

* **id_key**: That’s the UID’s table. This field is generated automatically by
TypeORM.
* **reader**: That’s the device which send the user’s key. In this project there
are two readers — Input and Output.
* **user**: That’s the relation between Auth and User. In TypeORM you can use the
decorator @ManyToOne to define that there are several entries in authentication
for each user. The relation is doing using the field key of the user. In the
User entity is required define the field key with the inverse decorator
(@OneToMany). In the following post we will describe this module (at the moment
is commented).
* **timestamp**: This is the moment in unix timestamp that the input or output was
done. So, that’s very important because we need know the exact moment which the
user clock-in/out in the system.

Finally, the provider file export two repositories to fast access to the
database. The pattern used is the Repository. So, you can inject those providers
using their token (AUTH_REPOSITORY_TOKEN and USER_REPOSITORY_TOKEN) in any
service or controller.

![](https://cdn-images-1.medium.com/max/1000/1*y1eQp2vAtQXDIqKBYAF6mA.png)

### Constants and DTOs

Now, I’m going to show the most easy part of my code but very important. The
constant file and the DTO. The constant file is very useful when you want to
coding clean code (is a good practice don’t use strings or numbers in your code)
and the DTOs define the information which is exchange between client-side and
server-side. ‌

The auth.constant file only have STATUS_CODE_RESPONSE to the Arduino system
which understand 0 as KO and 2 as OK and several moment formats.

![](https://cdn-images-1.medium.com/max/1000/1*CppqShOBJPuZe3FUkykO-w.png)

The following DTOs are very simple because only show the interface of an input
(**AuthDto**) and an output (**AuthResponseDto**).

![](https://cdn-images-1.medium.com/max/1000/1*3GyY0PREofo-ZIvs_8i6lA.png)

### Service

The AuthService should has two important methods:

* **authIn**: This method received a signal from the Arduino and save the
information when a user **clock-in** in the system. The service response with a
welcome message.
* **authOut**: This method received a signal from the Arduino and save the
information when a user **clock-out** in the system. The service response with a
bye message.

The code of this methods are the following:

![](https://cdn-images-1.medium.com/max/1000/1*FMRFH5Hm3YcC9Vre6nFgPA.png)

In this class, I’ve inject two repositories (authRepository and userRepository)
which are used to communicate with database. The code is clean because I’ve used
simple async/await and private methods (**saveTicketing, welcomeTeacher** and
**byeTeacher**). So, the methods **authIn** and **authOut** are simple to
testing in the future. The response of the both methods is an
**AuthResponseDto**.

The private method **saveTicketing** is very simple too, the first step is get
the user which the key is associated (auth.key come from the Arduino). After,
you can save the information of authentication:

* **key** and **reader** from auth.
* **user** from the database (UserEntity).
* **timestamp** which is calculated from the library momentJS.

![](https://cdn-images-1.medium.com/max/1000/1*6o3vC5cGHe8sFnJcUvFt8g.png)

Finally the two methods which show the message to the user (that’s show in the
Arduino screen) are the following:

![](https://cdn-images-1.medium.com/max/1000/1*gcKTE_XescVuTx0A9c7gJA.png)

Finally, if you want to see the complete code of AuthService is the following:

![](https://cdn-images-1.medium.com/max/1000/1*9I7Y-LPm0fMLqBDNPo7kdw.png)

### Resume

‌In this post I’ve explain my AuthModule which is very simple because I’m using
clean code in my coding. This module is used to save the information about
clock-in/out.

In the following post of this series I’m going to explain the UsersModule and
AppModule.

The GitHub project is
[https://github.com/Caballerog/clock-in-out](https://github.com/Caballerog/clock-in-out).<br>
The GitHub branch of this post is
[https://github.com/Caballerog/clock-in-out/tree/part2-basic-backend-auth](https://github.com/Caballerog/clock-in-out/tree/part2-basic-backend-auth).

*****

*Originally published at [www.carloscaballero.io](https://carloscaballero.io/part-2-clock-in-out-system-basic-backend/) on November 25, 2018.