Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

node.js - Trying to run an API with caching, keeps seeming to crash after a few minutes each time [Node] [MySQL] [React] [Express]

I am trying to create an API that pulls from mysql databases. I have it working if I want to connect each time I make a get call, but the repeated connecting is really slowing everything down. I have tried to set up caching with the following:

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const { reject } = require('lodash');
const pino = require('express-pino-logger')();
const lru = require('lru-cache');

const cache = new lru({
  maxAge: 300000
});
 

const client = mysql.createPool({
  ##CONNECTION DETAILS##
  connectionLimit: 10, 
  multipleStatements: true, 
});

let cachedDatabase;
const getDatabase = () => {
  if (cachedDatabase) return cachedDatabase; 

  // return a promise so we can wait for the connection to happen. 
  return new Promise((resolve, reject) => {
    client.getConnection((err, database) => {
      if (err) return reject(err);
      cachedDatabase = database; // cache the database connection in memory for next time
      resolve(cachedDatabase); // resolve the promise with the database.
    });
  });
};

// Starting our app.
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);

if (cache.get('/data') === undefined)
// Creating a GET route that returns data from the 'data' table.

app.get('/data', async function (req, res) {
  const database = await getDatabase();
  database.query(
    '##SQL QUERY##',
    function (error, results, fields) {
      // If some error occurs, we throw an error.
      if (error) throw error;

      res.send(results)
      cache.set('/data',results);
    }
  );
}
);
if (cache.get('/data') !== undefined)
res.send(cache.get('/data'))

app.listen(process.env.PORT || 3000);

The erroring seems to be happening on the "if(error) throw error" line which is not too helpful.

C:UsersstorvOneDriveDocumentsGitHubdatabaseapp.js:78
      if (error) throw error;
                 ^

Error: Cannot enqueue Query after fatal error.
    at Protocol._validateEnqueue 

Does anyone know why this issue might be happening? The database it is pulling from is a heroku one with cleardb mysql.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...