Advertisement
Guest User

CNX BD 2

a guest
Mar 29th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const http = require("http");
  2. const express = require("express");
  3. const bodyParser = require("body-parser");
  4. const mysql = require("mysql");
  5.  
  6. //Conexión a la BD mediante promesas!
  7. function connectDB(options){
  8.     return new Promise(function (resolve, reject){
  9.         const conn = mysql.createConnection(options);
  10.         conn.connect(function (err){
  11.             if(err){
  12.                 reject(err);
  13.                 return;
  14.             }
  15.             resolve(conn);
  16.         });
  17.     });
  18. }
  19.  
  20. function queryDB(conn, sql, data=null){
  21.     return new Promise(function (resolve, reject){
  22.         conn.query(sql, data, function(err, result){
  23.             if(err){
  24.                 reject(err);
  25.                 return;
  26.             }
  27.             resolve(result);
  28.         });
  29.     });
  30. }
  31.  
  32. function startServer(app, port=3000){
  33.     return new Promise(function(resolve, reject){
  34.         http.createServer(app).listen(port, function(){
  35.             console.log(`Servidor iniciado en el puerto ${port}`);
  36.             resolve;
  37.         });
  38.     });
  39. }
  40.  
  41. //Dentro de la función program el código es "síncrono", pero la función program es
  42. //asíncrona, fuera de ella, puede haber otras funciones ejecutándose al mismo tiempo
  43. async function program(){
  44.  
  45.     const cnx = mysql.createConnection({
  46.         host: "132.248...",
  47.         user: "unam2",
  48.         database: "unam",
  49.         password: "pass..."
  50.     });
  51.  
  52.     const app = express();
  53.     // app.use("/", express.static("public"));
  54.     app.use(bodyParser.json());
  55.     app.use(bodyParser.urlencoded({extended: true}));
  56.  
  57.     app.get("/api/productos", async function(req, res){
  58.        
  59.         let sql=`select * from productos`;
  60.         const records = await queryDB(cnx, sql);
  61.        
  62.         console.log(records.length);
  63.  
  64.         if(records.length === 0){
  65.             res.status(400).send({
  66.                 error: true,
  67.                 message: "No existen productos registrados..."
  68.             });
  69.             return;
  70.         }
  71.  
  72.         res.send(records);
  73.  
  74.     });
  75.  
  76.     await startServer(app);
  77.  
  78. } //program
  79.  
  80. program();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement