0

I saw a similar question posted Here, but they are using MEAN-Stack.

I am currently just using a 'setTimeout' function to wait a few seconds before requesting new data from the server using a fetch api to give it time to update but this doesnt feel like the right way to do it. Is there a simple way for the front-end to update only after the database is updated in Express? I am new to Node please forgive me.

app.js:

const express = require('express');
const app = express();
const mysql = require('mysql'); 

let viewData = {
    //html data
}

var pool = mysql.createPool({
    connectionLimit : 10,
    host: "localhost",
    port: 3306,
    database: 'testing',
    user: "root",
    password: "pass"
});

function sql(type) {

    if(type == 'select') {
     //Select query here
    }
    if(request == 'addRow') {
     //Insert query here
    }
}

app.get(`/`, function (req, res) {
    res.sendFile('./views/index.html', {root: __dirname});
})

app.post('/api/add', function(req, res){
    res.setHeader('Content-Type', 'application/json');
    sql('addRow')
});

app.get('/api/viewData', function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(viewData));
})

index.js:

function loadData() {
      fetch('/api/viewData')
      .then(z => z.json())
      .then(a => {
        //update html
      })
}

function postData(a) {
    fetch('/api/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
        body: JSON.stringify({
          //data to send to app.js
      })
    }).then(setTimeout(function(){loadData();}, 3000))
  }

Brandons404
  • 109
  • 1
  • 9
  • You won’t need a timeout if you’re using promises in the backend. Meaning, you’ll await on a promise to write data to db before you return responses to front end. Then you can guarantee your data will already be there in subsequent calls from front end. Here is an example on how they wrapped a MySQL call into a promise. https://stackoverflow.com/questions/36547292/use-promise-to-process-mysql-return-value-in-node-js – Edward Romero Aug 29 '20 at 22:08

1 Answers1

1

You should use async and await function

Example: After async/await

async function fun1(req, res){
  let response = await request.get('http://localhost:3000');
    if (response.err) { console.log('error');}
    else { console.log('fetched response');
}

The complete code of our example is shown below:

npm install express jsonschema body-parser promise-mysql

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var validate = require('./validate')
var mysqlConnection = require('./connectionShare');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const addItem = function(item, connection){
 console.log("Adding Item");
 return new Promise(function(resolve, reject){
  connection.query("INSERT INTO product SET ?", item)
  .then(function(result){
   resolve(item.seller);
  }).catch(function(error){
   reject(error);
  });
 })
}

const findOrCreateUser = function(user,connection){
 console.log("Finding User");
 return new Promise(function(resolve,reject){
  connection.query("SELECT * FROM user WHERE email=" + connection.escape(user.email))
   .then(function(results){
    if(results.length == 1){
     resolve(results[0].id)
    } else {
     connection.query("INSERT INTO user SET ?", user)
     .then(function(results){
      resolve(results.insertId);
     });
    }
   }).catch(function(error){
    reject(error);
   })
 })
}

const selectUserItems = function(userID,connection){
 console.log("Selecting Items " + userID);
 return new Promise(function(resolve,reject){
  connection.query("SELECT * FROM product WHERE seller = " + connection.escape(userID))
   .then(function(results){
    resolve(results);
   }).catch(function(error){
    reject(error);return;
   });
  })
}

app.post('/add/product', validate.JsonValidation, mysqlConnection.getConnection, async function(req,res){
 var connection = req.connection;
 var item = {
  name: req.body.name,
  price: req.body.price,
  width: req.body.width,
  height: req.body.height,
  added: req.body.added,
  image: req.body.image
 };

 var user = {
  username: req.body.seller.username,
  email: req.body.seller.email,
  votes: req.body.seller.votes
 };

 try {
  item.seller = await findOrCreateUser(user,connection);
  var user_id = await addItem(item,connection);
  var items = await selectUserItems(user_id, connection);
  connection.connection.release();
  res.status(200).json(result);
 } catch(error) {
  res.status(500).end(error);
 }
});

process.on('uncaughtException', error => console.error('Uncaught exception: ', error));
process.on('unhandledRejection', error => {console.error('Unhandled rejection: ', error));

app.listen(8000, function () {
 console.log('App listening on port 8000')
});
Abdo-Host
  • 2,470
  • 34
  • 33