0

I followed this video and here is the Github Basically, this video used a mock database (in-memory objects), which is not very practical.

I wanted to change the logic of getUsers() in a way that when I hit the endpoint (localhost:5000/users), it will return the user information from the Mysql database.

p.s. I am not sure if this is the correct way of using API, but this is the code I revised:

This is index.js file, no change:

import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';

const app = express(); 
const PORT = 5000;
app.use(bodyParser.json());

app.use('/users', usersRoutes);

app.get('/', (req, res) => {
    res.send('Hello from HomePage!');
});

This is users.js in routes folder, no change:

import express from 'express';
import { getUsers } from '../controllers/users.js';

const router = express.Router();
router.get('/', getUsers);
export default router;

This is users.js in controllers folder, where I want to make connections to MySQL:

import mysql from 'mysql';

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    connectionLimit: 10
})

const users = connection.query('SELECT * FROM SOME_TABLE', function (error, results, fields) {
    if (error)
        throw error;

    return results;
});

export const getUsers = (req, res) => {
    res.send(users);
}

So it can connect to MySQL, but the return values were not what I expected, and if I console.log(users), it gives me the following messages (kind of long, so I truncated it):

<ref *1> Query {
  _events: [Object: null prototype] {
    error: [Function (anonymous)],   
    packet: [Function (anonymous)],
    timeout: [Function (anonymous)],
    end: [Function (anonymous)]
  },
  _eventsCount: 4,
  _maxListeners: undefined,
  _callback: [Function (anonymous)],
  _callSite: Error
      at Protocol._enqueue (C:\Users\stanl\VS Code JavaScript Projects\node_express_rest_api_1\node_modules\mysql\lib\protocol\Protocol.js:144:48)    
      at Connection.query (C:\Users\stanl\VS Code JavaScript Projects\node_express_rest_api_1\node_modules\mysql\lib\Connection.js:198:25)
      at file:///C:/Users/stanl/VS%20Code%20JavaScript%20Projects/node_express_rest_api_1/database.js:23:26
      at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
      at async Promise.all (index 0)

And it gives me this (truncated) error when hitting the endpoint:

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Query'
    |     property '_timer' -> object with constructor 'Timer'
    --- property '_object' closes the circle
    at JSON.stringify (<anonymous>)

I have two questions:

(1) Is this a preferred way to build/use API?

(2) The SQL in connection.query('SELECT * FROM SOME_TABLE') is fixed, is there a way I can change it dynamically when hitting the endpoint? Basically I want to supply complex SQLs from the frontend, and pass this SQL to the API I tried to build now, then get results back.

Thank you.

RyanKao
  • 321
  • 1
  • 5
  • 14
  • Querying your database is asynchronous. You should make the query in your controller and call `res.send()` once the data is resolved – Phil Apr 29 '22 at 04:20
  • @Phil, can you elaborate more on how does this solve my question? And I did make the SQL in my controller, or is there any other way to do it? – RyanKao Apr 29 '22 at 04:27
  • I mean in the actual controller `getUsers` function. The `connection.query()` function doesn't return results. In fact, I don't think it returns anything. – Phil Apr 29 '22 at 04:31

0 Answers0