💬 About
🔨 Tools
👁️🗨️ Phase I - Creating the Backend
👁️🗨️ Phase II - Creating the Backend
📫 Postman
😄 Thanks
This is the back-end for a future movie rental application.
Currently, the search for movies and series is being carried out by connecting to the free API the Movie Database.
This project is part of the GeeksHubs Academy Full Stack Developer Bootcamp.
Phase I Start date: 19 / May /2021 Deadline: 23 / May / 2021
Phase II Start date: 24 / May /2021 Deadline: 30 / May / 2021
Contributors:
To create this project we worked with these tools and technologies:
Click to expand
- (We must have installed Node.js)
Using npm init from the command line initializes the project’s package.json file.
npm init -y
Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.
npm i axios --save
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the fast development with Node based Web applications.
npm install express --save
"dependencies": {
"axios": "^0.21.1",
"express": "^4.17.1"
},
/node_modules
To know more about this See Creating the Backend below.
npm start
To know more about this see Postman below.
Click to expand
- We have to call Node Express
const express = require('express');
- Save and execute.
const app = express();
- Also declare the port where we are going to upload the server.
const port = 3000;
- Save the constant router and match it to the require method and tell it that we import it from router.js.
const router = require('./router');
-
Express provides you with middleware to deal with the (incoming) data (object) in the body of the request.
-
Express.json() is a method built into Express to recognize the incoming Request Object as a JSON Object. This method is called as a middleware in your application using the code.
app.use(express.json());
- We build middleware for all application paths with.
app.use(router);
- Lift and initialize the server.
app.listen(port, () => console.log(`Node server running on http://localhost:${port}`));
- We have to call Node Express.
const router = require('express').Router();
- Call the files on the folder routes.
const moviesRouter = require('./routes/moviesRouter');
const seriesRouter = require("./routes/seriesRouter");
- This says that when the user puts the path where it should go.
router.use("/movies", movieRouter);
router.use("/series", seriesRouter);
- Finally export the file routers.
module.exports = router;
In this file we create the functions that we need to export in other folders. In this case, the (checkId) function transforms the users' words into genre identifiers through a for / if loop, which allows the identification numbers to be searched in the Database to be translated.
We added a case-sensitivity so that no matter how it's written, it can be found anyway. Finally we export this file, so that we can use it in other files.
const checkId = (nombre) => {
let traductorGenero = [
{
id: 28,
name: "action",
...
{
id: 37,
name: "western",
},
];
for (let i = 0; i < traductorGenero.length; i++) {
if (traductorGenero[i].name === nombre) {
return traductorGenero[i].id
}
}
};
module.exports = checkId;
Controllers contain callback functions which we pass to the router's methods.
We will need one for each, Movies and Series.
First call Axios, this is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.
And the function export in utiles.
const axios = require("axios");
const checkId = require("../utiles");
Then we create the callbacks funtions with the endopoint to the The Movie Database. This is an example in class Peliculas, a function to search the Top Rated Movies.
class Peliculas {
async findTopRated() {
let res = await axios.get(
"https://api.themoviedb.org/3/movie/top_rated?api_key=210d6a5dd3f16419ce349c9f1b200d6d&language=en-US&page=1"
);
return res.data;
}
let moviesController = new Peliculas();
module.exports = moviesController;
A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), a URL path/pattern, and a function that is called to handle that pattern.
const router = require("express").Router();
const moviesController = require("../controllers/moviesController");
We have one for each Series and Movies, this is a example of one of this to search Top Rated Movies.
router.get("/", async (req, res) => {
try {
res.json(await moviesController.findTopRated());
} catch (err) {
return res.status(500).json({
mensaje: err.mensaje,
});
}
});
module.exports = router;
Click to expand
npm install sequelize --save
npm install sequelize-cli --save
npm install mysql2 --save
sequelize init
Sequelize init: It will create the necessary folder and files. Sequencing model: generate: will create the model and the respective migration. ... Sequelize db: Migrate: Undo: All: Will revert all migrations executed. Sequence Seed: Generate - Will create the fake data seeder.
First you have to install sql with workbrench.
MySQL Workbench is a unified visual tool for database architects, developers, and DBAs. MySQL Workbench provides data modeling, SQL development, and comprehensive administration tools for server configuration, user administration, backup, and much more.
Change password and database information
{
"development": {
"username": "root",
"password": "db_password",
"database": "db_name",
"host": "127.0.0.1",
"dialect": "mysql"
},
Expand the see the code
const config = require('./config/config.json');
const {Sequelize, DataTypes} = require('sequelize');
const sequelize = new Sequelize(
process.env.MYSQL_DATABASE || config.development.database,
process.env.MYSQL_USER || config.development.username,
process.env.MYSQL_PASSWORD || config.development.password,
{
host: process.env.MYSQL_HOST || config.development.host,
port: process.env.MYSQL_PORT || config.development.port || '3306',
dialect: 'mysql',
operatorAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
}
);
module.exports = sequelize.authenticate()
.then((db)=>{
console.log('MYSQL connected');
return db;
});
We generate two models, User and Order. We have to write the attributes of each one and the migration associations. Then we could check the relation on workbrench like this.

Creating new endpoints so that users can register in our database and be able to login with their email and password.
Click to see the endpoint samples.
// Modify orders
router.put('/', authenticate, async (req, res) => {
try {
const cuerpoDeDatos = req.body;
res.json(await orderController.modifyOrder(cuerpoDeDatos));
}catch (err) {
return res.status(500).json({
message: err.message
});
}
});
// Delete orders
router.delete('/:id', admin, async (req, res) => {
try {
const id = req.params.id;
res.json(await orderController.deleteOrder(id));
}catch (err) {
return res.status(500).json({
message: err.message
});
}
});
- First we install the bcrypt dependencies.
The bcrypt hashing function allows us to build a password security platform that scales with computation power and always hashes every password with a salt.
npm i bcrypt --save
- And the jsonwebtoken
A JSON web token, or JWT (“jot”) for short, is a standardized, optionally validated and/or encrypted container format that is used to securely transfer information between two parties
npm install jsonwebtoken
For explample in the login function we use both, bcrypt and jsonwebtoken
const userController = require('./usersController');
const bcryptjs = require('bcryptjs');
const jwt = require('jsonwebtoken');
const secret = "Esto es lo mas dificil del bootcamp";
class LoginController {
async validate(emailCheck,passwordCheck){
let user = await userController.findByEmail(emailCheck);
let password = user.password;
let verificar = await bcryptjs.compare(passwordCheck,password);
if(!verificar){
return new Error("El password o el email no coinciden");
}
let payload = {
userId : user.id,
createdAt: new Date,
isAdmin: user.isAdmin
};
return jwt.sign(payload,secret);
}
}
let loginController = new LoginController();
module.exports = loginController;
Postman is a collaboration platform for API development. Postman's features simplify each step of building an API and streamline collaboration so you can create better APIs—faster.
Example of endpoints on Postman
Or click here to the API Documentation
We would like to thank our teacher, David, for his help and dedication. And to our bootcamp partners for all the help and every suggestion received.