GoBarber Backend - Fundamental Concepts
This project is about practicing the basic concepts behind NodeJS that were learned during the second module of GoStack 10 - Bootcamp.
- Install dependencies:
yarn
- Start the back-end:
yarn dev
-
How does it work?
- Creates isolated environments (containers)
- Isolated environments contains tools/technologies that will not change/edit our server's behaviour
- Installing/updating/removing becomes too cumbersome through the traditional way
- Containers expose communication ports
- Creates isolated environments (containers)
-
Main Concepts
- Image
- It's a tool/technology (e.g.: MySQL, MongoDB) that can be placed inside a container
- Container
- It's an instance of an image
- Docker Registry
- Docker Hub
- Dockerfile
- 'recipe' to create your own customized docker image
- Image
- Creates an instance of PostgreSQL named postgresdb.
docker run --name postgresdb -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
- Lists active container
docker ps
- Stops the container
docker stop postgresdb
- Lists all containers
docker ps -a
- Stars a container
docker start postgresdb
- Displays container logs
docker logs postgresdb
-
ORM (Object Relational Mapper): way of abstracting a database
- Changes the way the application communicates with the database
-
Tables are now represented by Models
-
Manipulate Data
- No SQL (most of the time)
- Only JavaScript code
SELECT * FROM users WHERE email="user@domain.com" LIMIT 1
User.findOne({ where: { email: "user@domain.com" } })
-
Migrations
- Version control for databases
- It's a way of maintaining the database updated
- Each file contains instructions to create, edit, or delete tables or columns
- Each file is a migration and migrations are ordered by date
- What is a 'rollback'?
- When you start a migration and something goes wrong you can perform a rollback, make changes to the table and start the migration again
- When a migration is completed, it cannot be edited. Any required changes must be done through a new migration.
- Every migration is specific to a table!
- Version control for databases
-
Seeds
- Populate the database with mock data for development
- Used frequently to create data for testing
- Executable only through code
- Should never be used for production
-
MVC Architecture
- Model
- Models are responsible for storing database abstractions
- They are used to manipulate the data contained in the database
- They have no responsability over our application's business rules
- Controller
- Controllers are the starting point of our application's requests
- Routes are usually associated with a method from the controller
- It's possible to include most of the application's business rules in the controllers
- As the applications grows, business rules can be detached from the controllers
- View
- Views are what is being displayed to the client
- In applications that don't use the REST API standard (JSON), that could be HTML
- Model
-
More about Controllers
- They are represented by Classes
- Always return JSON
- It will not invoke another controller/method
- It should only contain 5 methods (index, show, store, edit, delete)
- Tools that will maintaing the code standard
-
ESLint
- It will perform the 'linting' of the code.
- Verifies if desired standards are being followed
yarn eslint --init // Creates the configuration file
-
Prettier
- e.g.: Checks the sizes of lines of code
yarn eslint --fix src --etx .js
-
EditorConfig
- It will help maintaining the same code standards/styles throughout different editors
- Creates the migration file for the users table
yarn sequelize migration:create --name=create-users
- Performs the migration
yarn sequelize db:migrate
- Undo the last migration
yarn sequelize db:migrate:undo
- Undo all migrations
yarn sequelize db:migrate:undo:all
- It will connect to the database and load our application's Models.
src/database/index.js
- Generate password_hash
yarn add bcryptjs
- The field/attributes in the Model do not need to reflect 100% of what is in the database.
- Hooks are a Sequelize functionality
- Parts of the code are executed automatically, based on the actions that are being performed by the Model
-
It's a way of authenticating in RESTful services
-
JWT Authentication
- [POST] http://api.com/sessions
"email": "user@email.com", "password": "password"
-
After user credentials are validated a JWT Token is generated for the user's session
-
Structure of a JWT Token
- Headers (i.e.: what algorithm was used to generated the token)
- Payload (Additional data: id, name, email)
- Signature - (Makes sure the token cannot be edited)
-
yarn add jsonwebtoken
-
All jwt token has an expiry date
-
src/config/auth.js
-
Update route can only be accessed by users that have been authenticated
- It protects the route from being accessed by users that have not been previously authenticated
-
A middleware must be used
- It can be local or global. If it's a global middleware it will only be triggered by routes declared after it
-
JWT Token must be sent through the header (e.g.: Bearer 7812yhdahsBysahjdahskdas...)
-
src/app/middleware/auth.js
const decode = await promisify(jwt.verify)(token, authCOnfig.secret);
yarn add yup
- Schema validation library
import * as Yup from 'yup'
- Does not has 'export as default'
// An object will be validated (e.g.: req.body)
// shape({}) represents the 'structure' the object needs to have
const schema = Yup.object().shape({});