fupuchu
fupuchu

Reputation: 307

Passing req.params around in Node MVC

I'm trying to figure out how to pass req.params around using Express in the context of MVC.

I know how to properly reference req.params but when I split my app.js up into models and controllers I'm quite lost.

Code for reference:

routes.js

app.get('/category/:category', descriptor.getSingleCategory)

model.js

let getSingleCat = (cb) => {
    let queryString = 'SELECT * FROM categories WHERE category_id = $1'
    let queryValue = [req.params.category]
    db.query(queryString, queryValue, cb)
}

controller.js

const getSingleCategory = (req, response) => {
    console.log(req.params.category);
    db.desc.getSingleCat((err, queryRes) => {
        if (err) {
            //render something went wrong
            response.send('something went wrong')
        } else {
            response.send(queryRes.rows)
        }
    })
}

I've checked all requires and they are working correctly. Is there a vanilla way of passing req.params around without using middleware?

Upvotes: 2

Views: 1064

Answers (1)

João Rodrigues
João Rodrigues

Reputation: 913

The only way to use the req.params in the model, is by sending it as parameters as the following example:

model.js

let getSingleCat = (params, cb) => {
    let queryString = 'SELECT * FROM categories WHERE category_id = $1'
    let queryValue = params.category
    db.query(queryString, queryValue, cb)
}

controller.js

const getSingleCategory = (req, response) => {
    console.log(req.params.category);
    db.desc.getSingleCat(req.params, (err, queryRes) => {
        if (err) {
            //render something went wrong
            response.send('something went wrong')
        } else {
            response.send(queryRes.rows)
        }
    })
}

You can't use global vars, so this is the only way to do it. Also, this variable (req) can only be accessed in the functions bound to an endpoint that will receive an actual request.

Upvotes: 4

Related Questions