From 740e52a46bd762e4f96238100d7110be43514085 Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 28 Apr 2018 12:30:46 -0500 Subject: [PATCH 01/10] Ejemplo de buenas practicas en controllers e implementacion de mongo --- app.js | 13 ++++- controllers/ejemplo.js | 14 +++++ models/Ejemplo.js | 12 +++++ package-lock.json | 120 +++++++++++++++++++++++++++++++++++++++++ package.json | 1 + routes/api.js | 54 +++++++++++++++++++ 6 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 controllers/ejemplo.js create mode 100644 models/Ejemplo.js diff --git a/app.js b/app.js index 91c8bea..549eeb8 100644 --- a/app.js +++ b/app.js @@ -1,10 +1,13 @@ +//van dependencias var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var galleta = require('cookie-session'); +var mongoose = require('mongoose'); +//se jalan rutas y archivos var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var apiRouter = require('./routes/api'); @@ -18,13 +21,21 @@ app.set('view engine', 'pug'); app.use(galleta({ secret: 'Supercalifragilisticoespiralindoso', name: 'galleta' -})) +})); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); +mongoose.connect('mongodb://localhost/carrito', function(error){ + if(error){ + throw error; + }else{ + console.log('Estas conectado a la base de datos no relacional mas famosa'); + } +}); + function validateSession(req, res, next) { if(req.session.usuario) { next(); diff --git a/controllers/ejemplo.js b/controllers/ejemplo.js new file mode 100644 index 0000000..b4d63c7 --- /dev/null +++ b/controllers/ejemplo.js @@ -0,0 +1,14 @@ +var Usuario = require('../models/Ejemplo'); +var controlador = {}; + +controlador.obtener = function(req, res, next){ + Usuario.find({}, function(error, resultados){ + if(error){ + res.json(error); + }else{ + res.json(resultados); + } + }) +} + +module.exports = controlador; \ No newline at end of file diff --git a/models/Ejemplo.js b/models/Ejemplo.js new file mode 100644 index 0000000..fa08e3b --- /dev/null +++ b/models/Ejemplo.js @@ -0,0 +1,12 @@ +var mongoose = require('mongoose'); + +var Usuario = mongoose.Schema({ + nombre: {type: String, required: true}, + apellidop: {type: String, required: true}, + apellidom: {type: String, required: true}, + email: {type: String, required: true, unique: true}, + password: {type: String, required: true}, + edad: {type: Number, required: true} +}); + +module.exports = mongoose.model('usuario', Usuario); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 9827de2..66c43e4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,6 +71,14 @@ "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=" }, + "async": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.1.4.tgz", + "integrity": "sha1-LSFgx3iAMuTdbL4lAvH5osj2zeQ=", + "requires": { + "lodash": "4.17.5" + } + }, "babel-runtime": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", @@ -104,6 +112,11 @@ "safe-buffer": "5.1.1" } }, + "bluebird": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz", + "integrity": "sha1-eRQg1/VR7qKJdFOop3ZT+WYG1nw=" + }, "body-parser": { "version": "1.18.2", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", @@ -121,6 +134,11 @@ "type-is": "1.6.16" } }, + "bson": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.0.6.tgz", + "integrity": "sha512-D8zmlb46xfuK2gGvKmUjIklQEouN2nQ0LEHHeZ/NoHM2LDiMk2EYzZ5Ntw/Urk+bgMDosOZxaRzXxvhI5TcAVQ==" + }, "bytes": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", @@ -456,6 +474,11 @@ "promise": "7.3.1" } }, + "kareem": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.0.6.tgz", + "integrity": "sha512-/C+l8gABdHsAIfNpykJNWmYodpTnDRyn+JhORkP2VgEf1GgdAc+oTHjVADwISwCJKta031EOIwY6+Hki5z8SpQ==" + }, "keygrip": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.0.2.tgz", @@ -479,6 +502,11 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" }, + "lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=" + }, "longest": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", @@ -517,6 +545,46 @@ "mime-db": "1.33.0" } }, + "mongodb": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.0.7.tgz", + "integrity": "sha512-n/14kMJEoARXz1qhpNPhUocqy+z5130jhqgEIX1Tsl8UVpHrndQ8et+VmgC4yPK/I8Tcgc93JEMQCHTekBUnNA==", + "requires": { + "mongodb-core": "3.0.7" + } + }, + "mongodb-core": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.0.7.tgz", + "integrity": "sha512-z6YufO7s40wLiv2ssFshqoLS4+Kf+huhHq6KZ7gDArsKNzXYjAwTMnhEIJ9GQ8fIfBGs5tBLNPfbIDoCKGPmOw==", + "requires": { + "bson": "1.0.6", + "require_optional": "1.0.1" + } + }, + "mongoose": { + "version": "5.0.16", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.0.16.tgz", + "integrity": "sha512-GZqoN85gpk7+MTxZkE+yEVTtvvGfG5//X3UMWfbPQJhNO3nmmF4GFdE1qro73Vsn0PCchxyst3z55JpqZuYAZA==", + "requires": { + "async": "2.1.4", + "bson": "1.0.6", + "kareem": "2.0.6", + "lodash.get": "4.4.2", + "mongodb": "3.0.7", + "mongoose-legacy-pluralize": "1.0.2", + "mpath": "0.4.1", + "mquery": "3.0.0", + "ms": "2.0.0", + "regexp-clone": "0.0.1", + "sliced": "1.0.1" + } + }, + "mongoose-legacy-pluralize": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz", + "integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==" + }, "morgan": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.0.tgz", @@ -529,6 +597,29 @@ "on-headers": "1.0.1" } }, + "mpath": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.4.1.tgz", + "integrity": "sha512-NNY/MpBkALb9jJmjpBlIi6GRoLveLUM0pJzgbp9vY9F7IQEb/HREC/nxrixechcQwd1NevOhJnWWV8QQQRE+OA==" + }, + "mquery": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-3.0.0.tgz", + "integrity": "sha512-WL1Lk8v4l8VFSSwN3yCzY9TXw+fKVYKn6f+w86TRzOLSE8k1yTgGaLBPUByJQi8VcLbOdnUneFV/y3Kv874pnQ==", + "requires": { + "bluebird": "3.5.0", + "debug": "2.6.9", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "dependencies": { + "sliced": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=" + } + } + }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", @@ -752,11 +843,25 @@ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" }, + "regexp-clone": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=" + }, "repeat-string": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "2.0.0", + "semver": "5.5.0" + } + }, "resolve": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.6.0.tgz", @@ -765,6 +870,11 @@ "path-parse": "1.0.5" } }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, "right-align": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", @@ -778,6 +888,11 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" }, + "semver": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", + "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==" + }, "send": { "version": "0.16.2", "resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", @@ -814,6 +929,11 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==" }, + "sliced": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" + }, "source-map": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", diff --git a/package.json b/package.json index 9bd2c9b..b89065d 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "debug": "~2.6.9", "express": "~4.16.0", "http-errors": "~1.6.2", + "mongoose": "^5.0.16", "morgan": "~1.9.0", "pug": "2.0.0-beta11" } diff --git a/routes/api.js b/routes/api.js index d83ae18..ef588b5 100644 --- a/routes/api.js +++ b/routes/api.js @@ -1,5 +1,6 @@ var express = require('express'); var router = express.Router(); +var controlador_ejemplo = require('../controllers/ejemplo'); const respuesta = {texto: 'Hola perro', metodo: 'GET', numeroloco: 21}; const usuario = {nombre: 'Diego Martinez', email: 'diegojmartinezzm@gmail.com', contra: 'hola1234'}; @@ -39,4 +40,57 @@ router.route('/login') } }) +router.route('/users') + .post(function(req, res, next){ + if(req.body.edad < 18) { + res.json('Eres menor mijo, pidele permiso a tus jefes'); + } else { + var modelo = new Usuario({ + nombre: req.body.nombre, + apellidop: req.body.apellidop, + apellidom: req.body.apellidom, + email: req.body.email, + password: req.body.password, + edad: req.body.edad + }); + + modelo.save(function(error, respuesta){ + if(error){ + res.json(error); + }else{ + res.json(respuesta); + } + }) + } + }) + .get(function(req, res, next){ + controlador_ejemplo.obtener(req, res, next); + }) + .put(function(req, res, next){ + Usuario.update({email: req.body.email},{ + $set: { + nombre: req.body.nombre, + apellidop: req.body.apellidop, + apellidom: req.body.apellidom, + password: req.body.password, + edad: req.body.edad + } + },function(error, resultado){ + if(error){ + res.json(error); + }else{ + res.json(resultado); + } + }); + }) + .delete(function(req, res, next){ + Usuario.remove({email: req.body.email}, function(error, resultado){ + if(error){ + res.json(error); + }else{ + res.json(resultado); + } + }) + }) + module.exports = router; \ No newline at end of file From 07fa4a432fc8a1468b21e7c68d91b90a93699c45 Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 28 Apr 2018 13:44:57 -0500 Subject: [PATCH 02/10] CRUD de producto --- controllers/ejemplo.js | 14 --- controllers/producto.js | 58 ++++++++++++ controllers/usuario.js | 66 ++++++++++++++ models/Producto.js | 10 +++ models/{Ejemplo.js => Usuario.js} | 0 routes/api.js | 144 ++++++++++++------------------ 6 files changed, 193 insertions(+), 99 deletions(-) delete mode 100644 controllers/ejemplo.js create mode 100644 controllers/producto.js create mode 100644 controllers/usuario.js create mode 100644 models/Producto.js rename models/{Ejemplo.js => Usuario.js} (100%) diff --git a/controllers/ejemplo.js b/controllers/ejemplo.js deleted file mode 100644 index b4d63c7..0000000 --- a/controllers/ejemplo.js +++ /dev/null @@ -1,14 +0,0 @@ -var Usuario = require('../models/Ejemplo'); -var controlador = {}; - -controlador.obtener = function(req, res, next){ - Usuario.find({}, function(error, resultados){ - if(error){ - res.json(error); - }else{ - res.json(resultados); - } - }) -} - -module.exports = controlador; \ No newline at end of file diff --git a/controllers/producto.js b/controllers/producto.js new file mode 100644 index 0000000..e560e6e --- /dev/null +++ b/controllers/producto.js @@ -0,0 +1,58 @@ +var Producto = require('../models/Producto'); +var controlador = {}; + +controlador.obtener = function (req, res, next) { + Producto.find({}, function (error, resultados) { + if (error) { + res.json(error); + } else { + res.json(resultados); + } + }) +} + +controlador.agregar = function (req, res, next) { + var modelo = new Producto({ + nombre: req.body.nombre, + cantidad: req.body.cantidad, + precio: req.body.precio, + imagen: req.body.imagen + }); + + modelo.save(function (error, respuesta) { + if (error) { + res.json(error); + } else { + res.json(respuesta); + } + }) +} + +controlador.cambiar = function (req, res, next) { + Producto.update({ nombre: req.body.nombre }, { + $set: { + nombre: req.body.nombre, + cantidad: req.body.cantidad, + precio: req.body.precio, + imagen: req.body.imagen + } + }, function (error, resultado) { + if (error) { + res.json(error); + } else { + res.json(resultado); + } + }); +} + +controlador.eliminar = function (req, res, next) { + Producto.remove({ nombre: req.body.nombre }, function (error, resultado) { + if (error) { + res.json(error); + } else { + res.json(resultado); + } + }) +} + +module.exports = controlador; \ No newline at end of file diff --git a/controllers/usuario.js b/controllers/usuario.js new file mode 100644 index 0000000..321238d --- /dev/null +++ b/controllers/usuario.js @@ -0,0 +1,66 @@ +var Usuario = require('../models/Usuario'); +var controlador = {}; + +controlador.login = function (req, res, next) { + Usuario.find({ email: req.body.email, password: req.body.password }, function (error, resultados) { + if (error || resultados.length < 1) { + res.json(error || 'Datos de sesion incorrectos'); + } else { + req.session.usuario = resultados; + res.json(resultados); + } + }) +} + +controlador.registro = function (req, res, next) { + if (req.body.edad < 18) { + res.json('Eres menor mijo, pidele permiso a tus jefes'); + } else { + var modelo = new Usuario({ + nombre: req.body.nombre, + apellidop: req.body.apellidop, + apellidom: req.body.apellidom, + email: req.body.email, + password: req.body.password, + edad: req.body.edad + }); + + modelo.save(function (error, respuesta) { + if (error) { + res.json(error); + } else { + res.json(respuesta); + } + }) + } +} + +controlador.modificar = function (req, res, next) { + Usuario.update({ email: req.body.email }, { + $set: { + nombre: req.body.nombre, + apellidop: req.body.apellidop, + apellidom: req.body.apellidom, + password: req.body.password, + edad: req.body.edad + } + }, function (error, resultado) { + if (error) { + res.json(error); + } else { + res.json(resultado); + } + }); +} + +controlador.borrar = function (req, res, next) { + Usuario.remove({ email: req.body.email }, function (error, resultado) { + if (error) { + res.json(error); + } else { + res.json(resultado); + } + }) +} + +module.exports = controlador; \ No newline at end of file diff --git a/models/Producto.js b/models/Producto.js new file mode 100644 index 0000000..b7c08fc --- /dev/null +++ b/models/Producto.js @@ -0,0 +1,10 @@ +var mongoose = require('mongoose'); + +var Producto = mongoose.Schema({ + nombre: {type: String, required: true}, + cantidad: {type: Number, required: true}, + precio: {type: Number, required: true}, + imagen: {type: String, required: true} +}); + +module.exports = mongoose.model('producto', Producto); \ No newline at end of file diff --git a/models/Ejemplo.js b/models/Usuario.js similarity index 100% rename from models/Ejemplo.js rename to models/Usuario.js diff --git a/routes/api.js b/routes/api.js index ef588b5..186ca43 100644 --- a/routes/api.js +++ b/routes/api.js @@ -1,96 +1,70 @@ var express = require('express'); var router = express.Router(); -var controlador_ejemplo = require('../controllers/ejemplo'); +var controlador_ejemplo = require('../controllers/usuario'); +var controlador_producto = require('../controllers/producto'); -const respuesta = {texto: 'Hola perro', metodo: 'GET', numeroloco: 21}; -const usuario = {nombre: 'Diego Martinez', email: 'diegojmartinezzm@gmail.com', contra: 'hola1234'}; +const respuesta = { texto: 'Hola perro', metodo: 'GET', numeroloco: 21 }; +const usuario = { nombre: 'Diego Martinez', email: 'diegojmartinezzm@gmail.com', contra: 'hola1234' }; router.route('/') - .get(function(req, res, next){ - respuesta.metodo = 'GET'; - //res.json responde en formato json - //res.send responde en el formato de objeto - res.json(respuesta); - }) - .post(function(req, res, next){ - respuesta.texto = req.body.nombre + ' ' + req.body.apellido; - respuesta.metodo = 'POST'; - res.json(respuesta); - }) - .put(function(req, res, next){ - respuesta.metodo = 'PUT'; - res.json(respuesta); - }) - .delete(function(req, res, next){ - respuesta.metodo = 'DELETE'; - res.json(respuesta); - }); + .get(function (req, res, next) { + respuesta.metodo = 'GET'; + //res.json responde en formato json + //res.send responde en el formato de objeto + res.json(respuesta); + }) + .post(function (req, res, next) { + respuesta.texto = req.body.nombre + ' ' + req.body.apellido; + respuesta.metodo = 'POST'; + res.json(respuesta); + }) + .put(function (req, res, next) { + respuesta.metodo = 'PUT'; + res.json(respuesta); + }) + .delete(function (req, res, next) { + respuesta.metodo = 'DELETE'; + res.json(respuesta); + }); router.route('/login') - .post(function(req, res, next){ - var body = req.body;//req.body obtiene la informacion de la peticion - if (body.email === usuario.email && body.contra === usuario.contra) { - //guardamos la informacion en la cookie - req.session.usuario = body; - res.json('Sesion iniciada'); - } else { - //eliminamos la cookie - req.session.usuario = null; - res.json('Datos de login incorrectos'); - } - }) + .post(function (req, res, next) { + /*var body = req.body;//req.body obtiene la informacion de la peticion + if (body.email === usuario.email && body.contra === usuario.contra) { + //guardamos la informacion en la cookie + req.session.usuario = body; + res.json('Sesion iniciada'); + } else { + //eliminamos la cookie + req.session.usuario = null; + res.json('Datos de login incorrectos'); + }*/ + controlador_ejemplo.login(req, res, next); + }); router.route('/users') - .post(function(req, res, next){ - if(req.body.edad < 18) { - res.json('Eres menor mijo, pidele permiso a tus jefes'); - } else { - var modelo = new Usuario({ - nombre: req.body.nombre, - apellidop: req.body.apellidop, - apellidom: req.body.apellidom, - email: req.body.email, - password: req.body.password, - edad: req.body.edad - }); - - modelo.save(function(error, respuesta){ - if(error){ - res.json(error); - }else{ - res.json(respuesta); - } - }) - } - }) - .get(function(req, res, next){ - controlador_ejemplo.obtener(req, res, next); - }) - .put(function(req, res, next){ - Usuario.update({email: req.body.email},{ - $set: { - nombre: req.body.nombre, - apellidop: req.body.apellidop, - apellidom: req.body.apellidom, - password: req.body.password, - edad: req.body.edad - } - },function(error, resultado){ - if(error){ - res.json(error); - }else{ - res.json(resultado); - } - }); - }) - .delete(function(req, res, next){ - Usuario.remove({email: req.body.email}, function(error, resultado){ - if(error){ - res.json(error); - }else{ - res.json(resultado); - } - }) - }) + .post(function (req, res, next) { + controlador_ejemplo.registro(req, res, next); + }) + .put(function (req, res, next) { + controlador_ejemplo.modificar(req, res, next); + }) + .delete(function (req, res, next) { + controlador_ejemplo.borrar(req, res, next); + }); +router.route('/producto') + .get(function (req, res, next) { + controlador_producto.obtener(req, res, next); + }) + .post(function (req, res, next) { + controlador_producto.agregar(req, res, next); + }) + .put(function (req, res, next) { + controlador_producto.cambiar(req, res, next); + }) + .delete(function (req, res, next) { + controlador_producto.eliminar(req, res, next); + }); + module.exports = router; \ No newline at end of file From 6e78eeb85f63be884acf128637c9a9067d554cfa Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 5 May 2018 12:12:59 -0500 Subject: [PATCH 03/10] Agregando angular y registro --- controllers/usuario.js | 2 +- public/javascripts/logicaFront/login.js | 25 +++++++++++++ public/javascripts/logicaFront/registro.js | 35 ++++++++++++++++++ routes/index.js | 4 ++ views/layout_no_session.pug | 4 +- views/login.pug | 11 +++--- views/registro.pug | 43 ++++++++++++++++++++++ 7 files changed, 117 insertions(+), 7 deletions(-) create mode 100644 public/javascripts/logicaFront/login.js create mode 100644 public/javascripts/logicaFront/registro.js create mode 100644 views/registro.pug diff --git a/controllers/usuario.js b/controllers/usuario.js index 321238d..0e56384 100644 --- a/controllers/usuario.js +++ b/controllers/usuario.js @@ -4,7 +4,7 @@ var controlador = {}; controlador.login = function (req, res, next) { Usuario.find({ email: req.body.email, password: req.body.password }, function (error, resultados) { if (error || resultados.length < 1) { - res.json(error || 'Datos de sesion incorrectos'); + res.status(401).send(error || 'Datos de sesion incorrectos'); } else { req.session.usuario = resultados; res.json(resultados); diff --git a/public/javascripts/logicaFront/login.js b/public/javascripts/logicaFront/login.js new file mode 100644 index 0000000..bb8244f --- /dev/null +++ b/public/javascripts/logicaFront/login.js @@ -0,0 +1,25 @@ +var app = angular.module("aplicacion", []); + +app.controller("login", function($scope, $http){ + $scope.email = ""; + $scope.password = ""; + + $scope.loguea = function() { + $http({ + method: 'POST', + url: 'http://localhost:3000/api/login', + data: { + email: $scope.email, + password: $scope.password + } + }).then( + function sucess(data) { + console.log(data); + console.log('Login correcto'); + }, + function error(err) { + console.log('Login incorrecto'); + } + ) + } +}); \ No newline at end of file diff --git a/public/javascripts/logicaFront/registro.js b/public/javascripts/logicaFront/registro.js new file mode 100644 index 0000000..7819bc3 --- /dev/null +++ b/public/javascripts/logicaFront/registro.js @@ -0,0 +1,35 @@ +var app = angular.module("aplicacion", []); + +app.controller("registro", function ($scope, $http) { + + $scope.nombre = "" + $scope.apellidop = "" + $scope.apellidom = "" + $scope.email = "" + $scope.password = "" + $scope.edad = 0; + + $scope.registrarse = function () { + $http({ + method: 'POST', + url: 'http://localhost:3000/api/users', + data: { + nombre: $scope.nombre, + apellidop: $scope.apellidop, + apellidom: $scope.apellidom, + email: $scope.email, + password: $scope.password, + edad: $scope.edad + } + }).then( + function sucess(data) { + console.log(data); + console.log('Registro correcto'); + }, + function error(err) { + console.log(err); + console.log('Registro incorrecto'); + } + ) + } +}); \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index ae96464..50f3beb 100644 --- a/routes/index.js +++ b/routes/index.js @@ -15,4 +15,8 @@ router.get('/login', function (req, res, next) { res.render('login', { title: 'Login' }); }); +router.get('/registro', function (req, res, next) { + res.render('registro', { title: 'Registrate' }); +}); + module.exports = router; diff --git a/views/layout_no_session.pug b/views/layout_no_session.pug index 28952a4..0020bd3 100644 --- a/views/layout_no_session.pug +++ b/views/layout_no_session.pug @@ -4,7 +4,9 @@ html title= title link(rel="stylesheet", href="/bower_components/bootstrap/dist/css/bootstrap.min.css") link(rel='stylesheet', href='/stylesheets/style.css') - body + body( ng-app="aplicacion" ) + + script(src="/bower_components/angular/angular.min.js") block content diff --git a/views/login.pug b/views/login.pug index 008f55a..babfb37 100644 --- a/views/login.pug +++ b/views/login.pug @@ -1,20 +1,21 @@ extends layout_no_session block content - .login-container + script( src="/javascripts/logicaFront/login.js" ) + .login-container( ng-controller="login" ) .login-form - form(action='/api/login', method='post') - h2.text-center.pb-3.mb-3 Iniciar Sesión + form(ng-submit="loguea()") + h2.text-center.pb-3.mb-3 Inicia sesion .alert.alert-danger(role='alert') | Usuario y o contraseña incorrectos .input-group.mb-3 .input-group-prepend span#login-user.input-group-text @ - input.form-control(type='text', placeholder='Usuario', aria-label='Usuario', aria-describedby='login-user', required='required', name='email') + input.form-control(type='text', placeholder='Usuario', aria-label='Usuario', aria-describedby='login-user', required='required', name='email', ng-model="email") .input-group.mb-3 .input-group-prepend span#login-psw.input-group-text ** - input.form-control(type='password', placeholder='Contraseña', aria-label='Contraseña', aria-describedby='login-psw', required='required', name='contra') + input.form-control(type='password', placeholder='Contraseña', aria-label='Contraseña', aria-describedby='login-psw', required='required', name='contra', ng-model="password") .form-group button.btn.btn-primary.btn-block(type='submit') Iniciar .clearfix diff --git a/views/registro.pug b/views/registro.pug new file mode 100644 index 0000000..76f6f92 --- /dev/null +++ b/views/registro.pug @@ -0,0 +1,43 @@ +extends layout_no_session + +block content + script( src="/javascripts/logicaFront/registro.js" ) + .login-container( ng-controller="registro" ) + .login-form + form(ng-submit="registrarse()") + h2.text-center.pb-3.mb-3 Inicia sesion + .input-group.mb-3 + .input-group-prepend + span#login-user.input-group-text @ + input.form-control(type='text', placeholder='Nombre', aria-label='Nombre', aria-describedby='login-user', required='required', name='nombre', ng-model="nombre") + .input-group.mb-3 + .input-group-prepend + span#login-user.input-group-text @ + input.form-control(type='text', placeholder='Apellido Paterno', aria-label='Apellido Paterno', aria-describedby='login-user', required='required', name='apellidop', ng-model="apellidop") + .input-group.mb-3 + .input-group-prepend + span#login-user.input-group-text @ + input.form-control(type='text', placeholder='Apellido Materno', aria-label='Apellido Materno', aria-describedby='login-user', required='required', name='apellidom', ng-model="apellidom") + .input-group.mb-3 + .input-group-prepend + span#login-user.input-group-text @ + input.form-control(type='text', placeholder='Edad', aria-label='Edad', aria-describedby='login-user', required='required', name='edad', ng-model="edad") + .input-group.mb-3 + .input-group-prepend + span#login-user.input-group-text @ + input.form-control(type='text', placeholder='Email', aria-label='Email', aria-describedby='login-user', required='required', name='email', ng-model="email") + .input-group.mb-3 + .input-group-prepend + span#login-psw.input-group-text ** + input.form-control(type='password', placeholder='Contraseña', aria-label='Contraseña', aria-describedby='login-psw', required='required', name='contra', ng-model="password") + .form-group + button.btn.btn-primary.btn-block(type='submit') Iniciar + .clearfix + .row + .col-sm-4.form-check + input#remember.form-check-input(type='checkbox') + label.form-check-label(for='remember') Recuerdame + .col-sm-8.text-right + a(href='#') ¿Olvidaste tu contraseña? + p.text-center + a(href='#') Registrarse \ No newline at end of file From a908755835f13e1d2cf7d5d829b497f0b43a9feb Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 5 May 2018 12:48:41 -0500 Subject: [PATCH 04/10] Validacion nosession sin middleware --- app.js | 7 ++++--- controllers/usuario.js | 4 +++- public/javascripts/logicaFront/login.js | 3 ++- routes/index.js | 25 +++++++++++++++++++++---- 4 files changed, 30 insertions(+), 9 deletions(-) diff --git a/app.js b/app.js index 549eeb8..134da98 100644 --- a/app.js +++ b/app.js @@ -37,15 +37,16 @@ mongoose.connect('mongodb://localhost/carrito', function(error){ }); function validateSession(req, res, next) { + console.log(req.session.usuario) if(req.session.usuario) { next(); }else { - res.redirect('/inicio'); + res.redirect('/'); } } -app.use('/', indexRouter); -app.use('/users', validateSession, usersRouter); +app.use('/', indexRouter);//usuarios sin sesion +app.use('/users', validateSession, usersRouter);//ususarios con sesion app.use('/api', apiRouter); // catch 404 and forward to error handler diff --git a/controllers/usuario.js b/controllers/usuario.js index 0e56384..bf3a62c 100644 --- a/controllers/usuario.js +++ b/controllers/usuario.js @@ -6,7 +6,8 @@ controlador.login = function (req, res, next) { if (error || resultados.length < 1) { res.status(401).send(error || 'Datos de sesion incorrectos'); } else { - req.session.usuario = resultados; + req.session.usuario = resultados[0]; + console.log(req.session.usuario); res.json(resultados); } }) @@ -29,6 +30,7 @@ controlador.registro = function (req, res, next) { if (error) { res.json(error); } else { + req.session.usuario = respuesta; res.json(respuesta); } }) diff --git a/public/javascripts/logicaFront/login.js b/public/javascripts/logicaFront/login.js index bb8244f..46a7ad9 100644 --- a/public/javascripts/logicaFront/login.js +++ b/public/javascripts/logicaFront/login.js @@ -16,9 +16,10 @@ app.controller("login", function($scope, $http){ function sucess(data) { console.log(data); console.log('Login correcto'); + window.location.href = "/inicio"; }, function error(err) { - console.log('Login incorrecto'); + alert('Login incorrecto'); } ) } diff --git a/routes/index.js b/routes/index.js index 50f3beb..06ff053 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,21 +2,38 @@ var express = require('express'); var router = express.Router(); /* GET home page. */ + router.get('/', function (req, res, next) { - res.render('index', { title: 'Express' }); + if(!req.session.usuario) { + res.render('index', { title: 'Express' }); + }else { + res.redirect('/users'); + } }); router.get('/inicio', function (req, res, next) { // Cargar vista inicio.pug - res.render('inicio', { title: 'Hola mundo', variable: 'Soy una variable xD nigga' }); + if(!req.session.usuario) { + res.render('inicio', { title: 'Hola mundo', variable: 'Soy una variable xD nigga' }); + }else { + res.redirect('/users'); + } }); router.get('/login', function (req, res, next) { - res.render('login', { title: 'Login' }); + if(!req.session.usuario) { + res.render('login', { title: 'Login' }); + }else { + res.redirect('/users'); + } }); router.get('/registro', function (req, res, next) { - res.render('registro', { title: 'Registrate' }); + if(!req.session.usuario) { + res.render('registro', { title: 'Registrate' }); + }else { + res.redirect('/users'); + } }); module.exports = router; From 25d85cd8b6a302dba31f8c2c4c129ad08147f43c Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 5 May 2018 13:53:41 -0500 Subject: [PATCH 05/10] ng-repeat --- public/javascripts/logicaFront/barra.js | 20 ++++++++++++++++++++ public/javascripts/logicaFront/carrito.js | 19 +++++++++++++++++++ routes/api.js | 4 ++++ views/inicio2.pug | 10 +++++++++- views/layout.pug | 8 +++++--- 5 files changed, 57 insertions(+), 4 deletions(-) create mode 100644 public/javascripts/logicaFront/barra.js create mode 100644 public/javascripts/logicaFront/carrito.js diff --git a/public/javascripts/logicaFront/barra.js b/public/javascripts/logicaFront/barra.js new file mode 100644 index 0000000..2a65f3e --- /dev/null +++ b/public/javascripts/logicaFront/barra.js @@ -0,0 +1,20 @@ +var app = angular.module("aplicacion", []); + +app.controller("barra", function($scope, $http){ + + $scope.cerrar_sesion = function() { + $http({ + method: 'DELETE', + url: 'http://localhost:3000/api/login' + }).then( + function sucess(data) { + console.log(data); + console.log('Sesion cerrada correctamente'); + window.location.href = "/"; + }, + function error(err) { + alert('Sesion cerrada incorrectamente'); + } + ) + } +}); \ No newline at end of file diff --git a/public/javascripts/logicaFront/carrito.js b/public/javascripts/logicaFront/carrito.js new file mode 100644 index 0000000..3c3918d --- /dev/null +++ b/public/javascripts/logicaFront/carrito.js @@ -0,0 +1,19 @@ +app.controller("carrito", function($scope, $http){ + $scope.productos = []; + + $scope.obten_productos = function() { + $http({ + method: 'GET', + url: 'http://localhost:3000/api/producto' + }).then( + function sucess(data) { + console.log(data); + $scope.productos = data.data; + console.log('Obtencion correcta'); + }, + function error(err) { + alert('Obtencion incorrecta'); + } + ) + } +}); \ No newline at end of file diff --git a/routes/api.js b/routes/api.js index 186ca43..5e37fb3 100644 --- a/routes/api.js +++ b/routes/api.js @@ -40,6 +40,10 @@ router.route('/login') res.json('Datos de login incorrectos'); }*/ controlador_ejemplo.login(req, res, next); + }) + .delete(function (req, res, next){ + req.session.usuario = undefined; + res.json('Sesion cerrada'); }); router.route('/users') diff --git a/views/inicio2.pug b/views/inicio2.pug index 0d4e45b..f76a3f7 100644 --- a/views/inicio2.pug +++ b/views/inicio2.pug @@ -10,4 +10,12 @@ block content br br br - h1 Bienvenido Usuario #{user.email} \ No newline at end of file + h1 Bienvenido Usuario #{user.email} + .carrito-container( ng-controller="carrito", ng-init="obten_productos()" ) + ol + li(ng-repeat="producto in productos") + h1 {{producto.nombre}} + h2 {{producto.precio}} + img(src="{{producto.imagen}}") + + script(src="/javascripts/logicaFront/carrito.js") diff --git a/views/layout.pug b/views/layout.pug index d8f3875..d3c8d06 100644 --- a/views/layout.pug +++ b/views/layout.pug @@ -4,8 +4,10 @@ html title= title link(rel="stylesheet", href="/bower_components/bootstrap/dist/css/bootstrap.min.css") link(rel='stylesheet', href='/stylesheets/style.css') - body - nav.navbar.navbar-expand-lg.fixed-top.navbar-dark.bg-dark + body( ng-app="aplicacion" ) + script(src="/bower_components/angular/angular.min.js") + script(src="/javascripts/logicaFront/barra.js") + nav.navbar.navbar-expand-lg.fixed-top.navbar-dark.bg-dark(ng-controller="barra") a.navbar-brand(href='#') img.d-inline-block.align-top(src='https://getbootstrap.com/assets/brand/bootstrap-solid.svg', width='30', height='30', alt='') |   Tienda @@ -32,7 +34,7 @@ html span.badge.badge-pill.badge-info 9 .dropdown-divider a.dropdown-item(href='#') Historial - a.dropdown-item.bg-danger.text-light(href='#') Cerrar sesión + a.dropdown-item.bg-danger.text-light(href='#', ng-click="cerrar_sesion()") Cerrar sesión form.form-inline.my-2.my-lg-0 input.form-control.mr-sm-2(type='search', placeholder='Search', aria-label='Search') button.btn.btn-outline-light.my-2.my-sm-0(type='submit') Search From 15de3d979c9d73749a1921987080058e1b765f05 Mon Sep 17 00:00:00 2001 From: Diego Martinez Date: Sat, 12 May 2018 10:57:20 -0500 Subject: [PATCH 06/10] Cambiando puerto --- bin/www | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/www b/bin/www index 795eca8..775332a 100644 --- a/bin/www +++ b/bin/www @@ -12,7 +12,7 @@ var http = require('http'); * Get port from environment and store in Express. */ -var port = normalizePort(process.env.PORT || '3000'); +var port = normalizePort(process.env.PORT || '80'); app.set('port', port); /** From 0bbf1dbb11ad156591bb792f26c49c1d00b87072 Mon Sep 17 00:00:00 2001 From: Diego Martinez Date: Sat, 12 May 2018 11:37:34 -0500 Subject: [PATCH 07/10] Deploy --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index b89065d..a7d25ee 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "scripts": { "start": "node ./bin/www", "debug": "set DEBUG=curso:* & nodemon ./bin/www", - "debug-linux": "DEBUG=curso:* nodemon ./bin/www" + "debug-linux": "DEBUG=curso:* nodemon ./bin/www", + "deploy": "forever start -c nodemon ./bin/www" }, "dependencies": { "cookie-parser": "~1.4.3", From 49d0a8529ec807251a68f831368aaa16c2a169fa Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 12 May 2018 12:51:01 -0500 Subject: [PATCH 08/10] Cosas carrito --- controllers/producto.js | 15 +++++++++ public/javascripts/logicaFront/barra.js | 19 ++++++++++- public/javascripts/logicaFront/carrito.js | 37 +++++++++++++++++++-- routes/api.js | 12 +++++-- routes/index.js | 39 ++++++++--------------- views/inicio2.pug | 7 ++-- views/layout.pug | 4 +-- 7 files changed, 98 insertions(+), 35 deletions(-) diff --git a/controllers/producto.js b/controllers/producto.js index e560e6e..de4b461 100644 --- a/controllers/producto.js +++ b/controllers/producto.js @@ -55,4 +55,19 @@ controlador.eliminar = function (req, res, next) { }) } +controlador.aniadeCarrito = function (req, res, next) { + if (req.session.carrito) { + req.session.carrito.push(req.body.producto); + } else { + req.session.carrito = []; + req.session.carrito.push(req.body.producto); + } + console.log(req.session.carrito); + res.json('Todo shido'); +} + +controlador.getCarrito = function (req, res, next) { + res.json(req.session.carrito); +} + module.exports = controlador; \ No newline at end of file diff --git a/public/javascripts/logicaFront/barra.js b/public/javascripts/logicaFront/barra.js index 2a65f3e..157419e 100644 --- a/public/javascripts/logicaFront/barra.js +++ b/public/javascripts/logicaFront/barra.js @@ -1,6 +1,8 @@ var app = angular.module("aplicacion", []); -app.controller("barra", function($scope, $http){ +app.controller("barra", function($scope, $http, $rootScope){ + + $rootScope.carrito = []; $scope.cerrar_sesion = function() { $http({ @@ -17,4 +19,19 @@ app.controller("barra", function($scope, $http){ } ) } + + $scope.getCarrito = function() { + $http({ + method: 'GET', + url: 'http://localhost:3000/api/carrito' + }).then( + function sucess(data) { + console.log(data); + $rootScope.carrito = data.data; + }, + function error(err) { + alert('Error'); + } + ) + } }); \ No newline at end of file diff --git a/public/javascripts/logicaFront/carrito.js b/public/javascripts/logicaFront/carrito.js index 3c3918d..b923a97 100644 --- a/public/javascripts/logicaFront/carrito.js +++ b/public/javascripts/logicaFront/carrito.js @@ -1,4 +1,4 @@ -app.controller("carrito", function($scope, $http){ +app.controller("carrito", function($scope, $http, $rootScope){ $scope.productos = []; $scope.obten_productos = function() { @@ -7,13 +7,44 @@ app.controller("carrito", function($scope, $http){ url: 'http://localhost:3000/api/producto' }).then( function sucess(data) { - console.log(data); + console.log($rootScope.carrito); $scope.productos = data.data; - console.log('Obtencion correcta'); + console.log($scope.productos) + for (let i = 0; i < $scope.productos.length; i++) { + var producto = $scope.productos[i]; + for (let j = 0; j < $rootScope.carrito.length; j++) { + const carro = $rootScope.carrito[j]; + if (producto._id === carro._id){ + $scope.productos[i].cantidad -= carro.compra; + } + } + + } }, function error(err) { alert('Obtencion incorrecta'); } ) } + + $scope.aniadir = function (producto) { + if (producto.cantidad >= producto.compra && producto.compra > 0) { + $http({ + method: 'POST', + url: 'http://localhost:3000/api/carrito', + data: { + producto: producto + } + }).then( + function sucess(data) { + console.log(data); + }, + function error(err) { + alert('Obtencion incorrecta'); + } + ) + } else { + alert("Ingrese un valor dentro del rango del stock"); + } + } }); \ No newline at end of file diff --git a/routes/api.js b/routes/api.js index 5e37fb3..8c385b0 100644 --- a/routes/api.js +++ b/routes/api.js @@ -41,7 +41,7 @@ router.route('/login') }*/ controlador_ejemplo.login(req, res, next); }) - .delete(function (req, res, next){ + .delete(function (req, res, next) { req.session.usuario = undefined; res.json('Sesion cerrada'); }); @@ -70,5 +70,13 @@ router.route('/producto') .delete(function (req, res, next) { controlador_producto.eliminar(req, res, next); }); - + +router.route('/carrito') + .get(function (req, res, next) { + controlador_producto.getCarrito(req, res, next); + }) + .post(function (req, res, next) { + controlador_producto.aniadeCarrito(req, res, next); + }); + module.exports = router; \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index 06ff053..7e16e2a 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,39 +1,28 @@ var express = require('express'); var router = express.Router(); -/* GET home page. */ - -router.get('/', function (req, res, next) { - if(!req.session.usuario) { - res.render('index', { title: 'Express' }); - }else { +function validateNoSession(req, res, next) { + if (!req.session.usuario) { + next(); + } else { res.redirect('/users'); } +} + +router.get('/', validateNoSession, function (req, res, next) { + res.render('index', { title: 'Express' }); }); -router.get('/inicio', function (req, res, next) { - // Cargar vista inicio.pug - if(!req.session.usuario) { - res.render('inicio', { title: 'Hola mundo', variable: 'Soy una variable xD nigga' }); - }else { - res.redirect('/users'); - } +router.get('/inicio', validateNoSession, function (req, res, next) { + res.render('inicio', { title: 'Hola mundo', variable: 'Soy una variable xD nigga' }); }); -router.get('/login', function (req, res, next) { - if(!req.session.usuario) { - res.render('login', { title: 'Login' }); - }else { - res.redirect('/users'); - } +router.get('/login', validateNoSession, function (req, res, next) { + res.render('login', { title: 'Login' }); }); -router.get('/registro', function (req, res, next) { - if(!req.session.usuario) { - res.render('registro', { title: 'Registrate' }); - }else { - res.redirect('/users'); - } +router.get('/registro', validateNoSession, function (req, res, next) { + res.render('registro', { title: 'Registrate' }); }); module.exports = router; diff --git a/views/inicio2.pug b/views/inicio2.pug index f76a3f7..d863816 100644 --- a/views/inicio2.pug +++ b/views/inicio2.pug @@ -15,7 +15,10 @@ block content ol li(ng-repeat="producto in productos") h1 {{producto.nombre}} - h2 {{producto.precio}} - img(src="{{producto.imagen}}") + h2 $ {{producto.precio}} + h3 Stock: {{producto.cantidad-producto.compra}} + input(type="number", min="0", max="{{producto.cantidad}}", ng-model="producto.compra") + button(ng-click="aniadir(producto)") Añadir a carrito + img(src="{{producto.imagen}}", height="200px") script(src="/javascripts/logicaFront/carrito.js") diff --git a/views/layout.pug b/views/layout.pug index d3c8d06..dd36353 100644 --- a/views/layout.pug +++ b/views/layout.pug @@ -7,7 +7,7 @@ html body( ng-app="aplicacion" ) script(src="/bower_components/angular/angular.min.js") script(src="/javascripts/logicaFront/barra.js") - nav.navbar.navbar-expand-lg.fixed-top.navbar-dark.bg-dark(ng-controller="barra") + nav.navbar.navbar-expand-lg.fixed-top.navbar-dark.bg-dark(ng-controller="barra", ng-init="getCarrito()") a.navbar-brand(href='#') img.d-inline-block.align-top(src='https://getbootstrap.com/assets/brand/bootstrap-solid.svg', width='30', height='30', alt='') |   Tienda @@ -31,7 +31,7 @@ html a.dropdown-item(href='#') Mi cuenta a.dropdown-item(href='#') | Carrito   - span.badge.badge-pill.badge-info 9 + span.badge.badge-pill.badge-info {{carrito.length}} .dropdown-divider a.dropdown-item(href='#') Historial a.dropdown-item.bg-danger.text-light(href='#', ng-click="cerrar_sesion()") Cerrar sesión From 92b4c9e3134aca4f084ad6d37acce3ec13b02854 Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 12 May 2018 12:51:46 -0500 Subject: [PATCH 09/10] puerto --- bin/www | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/www b/bin/www index 775332a..795eca8 100644 --- a/bin/www +++ b/bin/www @@ -12,7 +12,7 @@ var http = require('http'); * Get port from environment and store in Express. */ -var port = normalizePort(process.env.PORT || '80'); +var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** From 47538de431d1aaec0c1ce3cdc22fde8b09409693 Mon Sep 17 00:00:00 2001 From: cognatus Date: Sat, 12 May 2018 13:59:39 -0500 Subject: [PATCH 10/10] final --- controllers/producto.js | 31 ++++++++++++++++-- models/Usuario.js | 8 ++++- public/javascripts/logicaFront/compras.js | 40 +++++++++++++++++++++++ routes/api.js | 8 +++++ routes/users.js | 4 +++ views/carrito.pug | 23 +++++++++++++ 6 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 public/javascripts/logicaFront/compras.js create mode 100644 views/carrito.pug diff --git a/controllers/producto.js b/controllers/producto.js index de4b461..23fdda1 100644 --- a/controllers/producto.js +++ b/controllers/producto.js @@ -1,4 +1,5 @@ var Producto = require('../models/Producto'); +var Usuario = require('../models/Usuario'); var controlador = {}; controlador.obtener = function (req, res, next) { @@ -57,10 +58,10 @@ controlador.eliminar = function (req, res, next) { controlador.aniadeCarrito = function (req, res, next) { if (req.session.carrito) { - req.session.carrito.push(req.body.producto); + req.session.carrito.push(req.body.producto); } else { req.session.carrito = []; - req.session.carrito.push(req.body.producto); + req.session.carrito.push(req.body.producto); } console.log(req.session.carrito); res.json('Todo shido'); @@ -70,4 +71,30 @@ controlador.getCarrito = function (req, res, next) { res.json(req.session.carrito); } +controlador.removeCarrito = function (req, res, next) { + req.session.carrito = req.query.carrito; + res.json(req.session.carrito); +} + +controlador.shop = function (req, res, next) { + console.log(req.body.carrito); + Usuario.update( + { + + _id: req.session.usuario._id + }, + { + $push: {'compras': req.body.carrito} + }, + function (error, respuesta) { + if (error) { + res.status(500).send(error); + } else { + req.session.carrito = []; + res.json(respuesta); + } + } + ) +} + module.exports = controlador; \ No newline at end of file diff --git a/models/Usuario.js b/models/Usuario.js index fa08e3b..6b06036 100644 --- a/models/Usuario.js +++ b/models/Usuario.js @@ -6,7 +6,13 @@ var Usuario = mongoose.Schema({ apellidom: {type: String, required: true}, email: {type: String, required: true, unique: true}, password: {type: String, required: true}, - edad: {type: Number, required: true} + edad: {type: Number, required: true}, + compras: [{ + nombre: {type: String, required: true}, + cantidad: {type: Number, required: true}, + precio: {type: Number, required: true}, + imagen: {type: String, required: true} + }] }); module.exports = mongoose.model('usuario', Usuario); \ No newline at end of file diff --git a/public/javascripts/logicaFront/compras.js b/public/javascripts/logicaFront/compras.js new file mode 100644 index 0000000..cbc05ff --- /dev/null +++ b/public/javascripts/logicaFront/compras.js @@ -0,0 +1,40 @@ +app.controller("compras", function($scope, $http, $rootScope){ + + $scope.eliminar = function (producto) { + var index = $rootScope.carrito.indexOf(producto); + $rootScope.carrito.splice(index, 1); + console.log($rootScope.carrito) + $http({ + method: 'DELETE', + url: 'http://localhost:3000/api/carrito', + params: { + carrito: $rootScope.carrito + } + }).then( + function sucess(data) { + alert('Lo eliminastessss'); + }, + function error(err) { + alert('incorrecta'); + } + ) + } + + $scope.comprar = function () { + $http({ + method: 'POST', + url: 'http://localhost:3000/api/compra', + data: { + carrito: $rootScope.carrito + } + }).then( + function sucess(data) { + alert('Ya comprastesss'); + $rootScope.carrito = []; + }, + function error(err) { + alert('incorrecta'); + } + ) + } +}); \ No newline at end of file diff --git a/routes/api.js b/routes/api.js index 8c385b0..93a5efc 100644 --- a/routes/api.js +++ b/routes/api.js @@ -77,6 +77,14 @@ router.route('/carrito') }) .post(function (req, res, next) { controlador_producto.aniadeCarrito(req, res, next); + }) + .delete(function (req, res, next) { + controlador_producto.removeCarrito(req, res, next); + }); + +router.route('/compra') + .post(function (req, res, next) { + controlador_producto.shop(req, res, next); }); module.exports = router; \ No newline at end of file diff --git a/routes/users.js b/routes/users.js index 27b4f53..0b82b68 100644 --- a/routes/users.js +++ b/routes/users.js @@ -7,4 +7,8 @@ router.get('/', function(req, res, next) { res.render('inicio2', { title: 'Bienvenida', user: req.session.usuario }); }); +router.get('/carrito', function(req, res, next) { + res.render('carrito', { title: 'Compras chidas!!!', user: req.session.usuario }); +}); + module.exports = router; diff --git a/views/carrito.pug b/views/carrito.pug new file mode 100644 index 0000000..2c2d498 --- /dev/null +++ b/views/carrito.pug @@ -0,0 +1,23 @@ +extends layout + +block content + + br + br + br + br + br + br + br + br + .carrito-container( ng-controller="compras" ) + ol + li(ng-repeat="producto in carrito") + h1 {{producto.nombre}} + h2 $ {{producto.precio}} + h3 Cantidad: {{producto.compra}} + button(ng-click="eliminar(producto)") X + img(src="{{producto.imagen}}", height="200px") + button(ng-click="comprar()") Comprar + + script(src="/javascripts/logicaFront/compras.js")