Thursday 28 October 2021

How to follow MVC architecture in web app Using Node, Express, Postgresql

I'm unsure of how to apply the MVC architecture to my node web app, in specific separating the model from the controller.

The current structure has the views separated properly (all my .ejs files) and then I guess that my app.js is like the controller as it contains all the routes to respond to http requests. The routes are then handled in a queries.js file which is where I query my database using node-postgres (most of the views rendered are either displaying information from the database or displaying forms so the user can insert data to the database). Should I be doing this differently, or more specifically should I try to create a model that contains raw data from the database and have the route handlers manipulate this data instead of directly querying the database (not sure how I would handle inserting into the database then...)? I'm just concerned that the current way I have structured my web app will make it difficult to manage as it grows and difficult for other to understand and add on to.

Here is an example of how the web app is currently structured: Say a user clicks a button to display all the active orders, my app.js file would look something like this

const db = require('./queries')

app.get('/activeorders', db.getActiveOrders)

My queries.js file would then handle this route like so:

const Pool = require('pg').Pool
const pool = new Pool({
  user: process.env.USER,
  host: process.env.HOST,
  database: process.env.DB,
  password: process.env.PASSWORD,
  port: process.env.PORT,
})

const getActiveOrders = (request, response) => {
    const queryOrders = 'SELECT * FROM orders WHERE complete=0 ORDER BY date_rec DESC;';
    pool.query(queryOrders, (error, results) => {
        if(error) {
            throw error
        }
        var ordersObj = results.rows;
        response.render('pages/activeorders', {
            ordersObj: ordersObj
        })
    })
}

module.exports = {
    getActiveOrders,
}

As can be seen in the handler the database is queried and stores the results in an object that is then passed to the activeorders.ejs file when rendered.



from How to follow MVC architecture in web app Using Node, Express, Postgresql

No comments:

Post a Comment