Skip to content

Commit

Permalink
websocket1
Browse files Browse the repository at this point in the history
  • Loading branch information
santi-homps committed Aug 11, 2021
1 parent 172abbd commit 9a74121
Show file tree
Hide file tree
Showing 10 changed files with 656 additions and 0 deletions.
68 changes: 68 additions & 0 deletions backend-2021/D12-Websocket_1/productos.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
class Productos {
//seteo una lista de productos vacia
listaProductos = []
//Creo un id inicial en cero
idNuevo = 0

//METODOS

//recibo producto en JSON por params y lo almaceno con id incremental sobre el id creado
productoNuevo(producto){
this.listaProductos.push({
id:++this.idNuevo, //incremento el id inicial y lo asigno al producto nuevo
title: producto.title,
price: producto.price,
thumbnail: producto.thumbnail
})
return(this.listaProductos[this.id-1]); //retorno el producto creado como objeto
}
// Valido si hay productos en el array y retorno el listado o el error (objeto) segun corresponda
leerProductos(){
if (this.listaProductos.length<=0) {
return {error:"Aun no existe ningun producto"}
} else {
return this.listaProductos
}
}
// Valido si el numero corresponde a un producto existente y retorno el producto o el error (objeto) segun corresponda
leerProductosConId(id){
if (this.listaProductos[id-1]==undefined) {
return {error:"Ese producto no existe aun"}
} else {
return this.listaProductos[id-1]
}
}
// Actualizo un producto con ID existente
actualizarConID(id, productoNuevo){
let idParsed=parseInt(id);
let productoAModificar=this.listaProductos.find((obj)=>{
return obj.id==idParsed;
});
if (productoAModificar==undefined){
return {error:"No existe el producto que desea actualizar"}
}else{
productoAModificar.titulo=productoNuevo.title;
productoAModificar.precio=productoNuevo.price;
productoAModificar.urlFoto=productoNuevo.thumbnail;
return productoAModificar;
}
}
// Elimino un producto
borrarConID(id){
let idParsed=parseInt(id);
let productoABorrar=this.listaProductos.find((obj,idx)=>{
if(obj.id==idParsed){
this.listaProductos.splice(idx,1);
return obj;
};
})

if (productoABorrar==[]){
return {error:"No existe el producto que desea borrar"}
}
return productoABorrar;
}
}

// exporto el modulo Productos
module.exports= new Productos;
26 changes: 26 additions & 0 deletions backend-2021/D12-Websocket_1/public/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Sockets desde el cliente
const socket = io();
//selecciono los elementos del html
const inputTitulo = document.querySelector("#title")
const inputPrecio = document.querySelector("#price")
const inputThumbnail = document.querySelector("#thumbnail")

const enviar = document.querySelector("#send")
const listado = document.querySelector("#list")

socket.on('productos', productos => {
console.log(productos)
//escucho evento productos y cargo los productos en el html
listado.innerHTML = productos.map(p => {
return `Nombre: ${p.title} - Precio: ${p.price} - img: ${p.thumbnail}`
}).join('<br>')
});

enviar.addEventListener('click', () => {
//envio producto nuevo con el Precio de los input
socket.emit('productoNuevo', {title: inputTitulo.value, price: inputPrecio.value, thumbnail: inputThumbnail.value})
//limpio los input
// inputNombre.value = null
// inputPrecio.value = null
// inputThumbnail.value = null
})
3 changes: 3 additions & 0 deletions backend-2021/D12-Websocket_1/public/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h1 {
color: green;
}
116 changes: 116 additions & 0 deletions backend-2021/D12-Websocket_1/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// D12 - WEBSOCKETS

//importacion
const express = require('express');
const app = express();
const Handlebars = require("express-handlebars");
const Productos = require('./productos');

const http = require('http');
const server = http.createServer(app)
const { Server } = require("socket.io")
const io = new Server(server)



const puerto = 8080;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// app.use('/', express.static(__dirname + '/views'))
app.use(express.static(__dirname + '/public'));

const routerGlobal = express.Router();

//HANDLEBARS

app.engine('.hbs',Handlebars({ //func. de config.
extname: '.hbs', //extension a utilizar
defaultLayout: 'index.hbs', //plantilla ppal
layoutsDir: __dirname + '/views/layouts', //ruta a la plantilla ppal
partialsDir: __dirname + '/views/partials' // ruta a las plant parciales
})
)

// se setea el motor de plantilla a utilizar
app.set('view engine', 'hbs')
// directorio de archivos de plantilla
app.set('views', './views')

const productos = [
// {Titulo: "title", Precio:" price", IMG: ".thumbnail"},
// {Titulo: "title", Precio:" price", IMG: ".thumbnail"},
// {Titulo: "title", Precio:" price", IMG: ".thumbnail"}
]

//socket

io.on('connection', socket => {
console.log('usuario conectado');

socket.emit('productos', productos);

socket.on('productoNuevo', data => {

productos.push({title: data.title, price: data.price, thumbnail: data.thumbnail})
io.sockets.emit('productos', productos);

})


});


//GET y render
routerGlobal.get('/productos/vista',(req,res)=>{
let arrayProductos=Productos.leerProductos();
if(arrayProductos.error){
res.render('main',{hayProductos: false})
}else{
res.render('main',{hayProductos: true, productos:arrayProductos})
}
})
//GET y render
routerGlobal.get('/',(req,res)=>{
res.render('./partials/formulario')
})
//GET listado
routerGlobal.get('/productos',(req, res) => {
res.json(Productos.leerProductos())
})
//GET producto por ID
routerGlobal.get('/productos/:id',(req, res) => {
res.json(Productos.leerProductosConId(req.params.id))
})
//POST de un producto nuevo sin ID
routerGlobal.post('/productos',(req,res) => {
let prodGuardado = Productos.productoNuevo(req.body)
res.send("Producto guardado")
res.send(prodGuardado)
})
//PUT de un producto nuevo con ID
routerGlobal.put('/productos/:id',(req,res) => {
let prodNuevo = req.body;
let idProdNuevo = req.params.id
let prodActualizado = Productos.actualizarConID(idProdNuevo, prodNuevo)
res.send("Producto actualizado")
res.send(prodActualizado)
})
//DELETE de un producto con ID
routerGlobal.delete('/productos/:id',(req,res) => {
let idProdABorrar = req.params.id
let prodBorrado = Productos.borrarConID(idProdABorrar)
res.send("Producto eliminado")
res.send(prodBorrado)
})

// aplico el router global
app.use('/api',routerGlobal)

server.listen(puerto, () => {
console.log(`servidor escuchando en http://localhost:${puerto}`);
});

server.on('error', error => {
console.log('Error en el servidor:', error);
});
32 changes: 32 additions & 0 deletions backend-2021/D12-Websocket_1/views/layouts/index.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="es">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Websocket 1 - Santiago Homps</title>
</head>

<body>
{{>header}}

{{>formulario}}

<!-- SCRIPTS -->
<!-- BOOTSTRAP -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<!-- SOCKET IO-->
<script src="/socket.io/socket.io.js"></script>
<!-- PROPIO -->
<script src="index.js"></script>


</body>

</html>
32 changes: 32 additions & 0 deletions backend-2021/D12-Websocket_1/views/main.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<style>
.table td, .table th {
vertical-align: middle;
}
h1 {
color: blue;
}
hr {
background-color: #ddd;
}
.jumbotron {
min-height: 100vh;
}
</style>

<div class="jumbotron mx-5">
<h1>Vista de Productos</h1>
<br>

{{#if hayProductos}}
<div class="table-responsive">
<table class="table table-dark">
<tr> <th>Nombre</th> <th>Precio</th> <th>Foto</th></tr>
{{#each productos}}
<tr> <td>{{this.title}}</td> <td>${{this.price}}</td> <td><img width="50" src={{this.thumbnail}} alt="not found"></td> </tr>
{{/each}}
</table>
</div>
{{else}}
<h3 class="alert alert-warning">No se encontraron productos</h3>
{{/if}}
</div>
14 changes: 14 additions & 0 deletions backend-2021/D12-Websocket_1/views/partials/formulario.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<div class="container">

<span>Título:</span> <input type="text" name="title" id="title">
<span>Precio:</span> <input type="number" name="price" id="price">
<span>UrlImagen:</span> <input type="text" name="thumbnail" id="thumbnail">
<button id="send">Enviar</button>

<div>
<h2 class="text-center py-2">Listado de productos</h2>
<p id="list">

</p>
</div>
</div>
1 change: 1 addition & 0 deletions backend-2021/D12-Websocket_1/views/partials/header.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1 class="text-center pt-5">API de Santiago Homps</h1>
Loading

0 comments on commit 9a74121

Please sign in to comment.