youngster
youngster

Reputation: 195

How to get and pass json from model to controller?

I'm trying to get json data from database (sql) with node.js and then pass it to app.get (express.js) but without success.

I have two files urls.js which should get all urls from database and in app.js I'm trying to create api endpoint with express.js. I have managed to get json data in app.js if I write query there and run it but I do not know how to separate it into two files.

code that works in app.js

app.get('/api/urls', (request, response) => {
    db.query('SELECT * FROM urls', (error, result) => {
    if (error) throw error;
    response.send(result);
  });
});

I've tried to separate it into two files so in urls.js (model like) I could have something like

class Urls {
  async getUrls() {
    const sql = `select * from urls`;
    return await db.query(sql); 
  }
}

module.exports = Urls;

and then call it in app.js (controller like):

const data = new Urls();
app.get(/api/urls, (req, res) => {
  res.send(data.getUrls());
}

In both cases result should be json

Upvotes: 0

Views: 234

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

Your getUrls function is async it will return promise,so do something like this

const data = new Urls();
app.get(/api/urls, (req, res) => {
data.getUrls().then(response=>{
res.send(response);

})

}

Upvotes: 1

Related Questions