Skip to content

Commit 601f2fc

Browse files
author
Royer Reyes León
committed
Sequelize ORM #1 Integración con ExpressJS.
0 parents  commit 601f2fc

File tree

6 files changed

+1554
-0
lines changed

6 files changed

+1554
-0
lines changed

app.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const express = require('express')
2+
const app = express();
3+
const sequelize = require('./database/db');
4+
const User = require('./database/models/Users');
5+
6+
// CONFIGURACION
7+
const port = process.env.PORT || 3006
8+
9+
10+
11+
// RUTAS
12+
app.get('/insertar' , (req , res)=>{
13+
User.create({
14+
name:"Royer",
15+
birthday: new Date(1997, 11, 16)
16+
}).then(user => {
17+
res.json(user);
18+
});
19+
})
20+
21+
app.get('/listar' , (req , res)=>{
22+
User.findAll().then(users => {
23+
res.json(users);
24+
});
25+
})
26+
27+
28+
29+
// INICIANDO SERVIDOR
30+
app.listen(port , ()=> {
31+
console.log('> Server is up and running on port : ' + port);
32+
33+
// CONECTAMOS A BD.
34+
// sequelize.authenticate().then(() => {
35+
// sync({force : false}) crea las tablas
36+
// sync({force : true}) elimina y crea las tablas
37+
sequelize.sync({ force:false}).then(() => {
38+
console.log('Conexion exitosa a BD');
39+
}).catch(error => {
40+
console.log('Ocurrio un error al conectar a BD: ', error);
41+
})
42+
})

config.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
database: {
3+
username:"root",
4+
password:"",
5+
database:"company",
6+
host:"localhost"
7+
8+
}
9+
}

database/db.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const { Sequelize } = require('sequelize');
2+
const { database } = require('../config');
3+
4+
const sequelize = new Sequelize(
5+
database.database,
6+
database.username,
7+
database.password, {
8+
host: database.host,
9+
dialect: "mysql" /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
10+
}
11+
);
12+
13+
module.exports = sequelize;

database/models/Users.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const { Model, DataTypes } = require('sequelize');
2+
const sequelize = require('../db');
3+
4+
// CREAMOS EL MODELO Y CADA UNO DE SUS ATRIBUTOS CON SUS TIPOS DE DATOS
5+
class User extends Model {}
6+
User.init({
7+
// ATRIBUTOS
8+
name: DataTypes.STRING,
9+
birthday: DataTypes.DATE
10+
}, {
11+
sequelize,
12+
modelName: 'user' // TABLA DE BD.
13+
});
14+
15+
// (async () => {
16+
// await sequelize.sync();
17+
// const jane = await User.create({
18+
// username: 'janedoe',
19+
// birthday: new Date(1980, 6, 20)
20+
// });
21+
// console.log(jane.toJSON());
22+
// })();
23+
24+
module.exports = User;

0 commit comments

Comments
 (0)